@sirenodeck/sirenodeck 0.2.7 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/config-ui/index.html +13 -0
  2. package/config-ui/src/App.tsx +675 -0
  3. package/config-ui/src/DeckFrame.tsx +445 -0
  4. package/config-ui/src/Shell.tsx +108 -0
  5. package/config-ui/src/SidePanel.tsx +96 -0
  6. package/config-ui/src/bridge-log-store.ts +115 -0
  7. package/config-ui/src/bridge.ts +303 -0
  8. package/config-ui/src/components/ActionValueEditor.tsx +209 -0
  9. package/config-ui/src/components/ButtonActionsEditor.tsx +84 -0
  10. package/config-ui/src/components/DisconnectedOverlay.tsx +77 -0
  11. package/config-ui/src/components/EmojiPicker.tsx +65 -0
  12. package/config-ui/src/components/IconPicker.tsx +264 -0
  13. package/config-ui/src/components/MacroPreview.tsx +22 -0
  14. package/config-ui/src/components/ReconnectingBanner.tsx +35 -0
  15. package/config-ui/src/gesture.ts +45 -0
  16. package/config-ui/src/index.css +8 -0
  17. package/config-ui/src/main.tsx +20 -0
  18. package/config-ui/src/pages/AboutPage.tsx +65 -0
  19. package/config-ui/src/pages/AddonsPage.tsx +232 -0
  20. package/config-ui/src/pages/BridgeLogsPage.tsx +94 -0
  21. package/config-ui/src/pages/ButtonConfigEditor/ButtonAppearanceFields.tsx +77 -0
  22. package/config-ui/src/pages/ButtonConfigEditor/ButtonTypePicker.tsx +80 -0
  23. package/config-ui/src/pages/ButtonConfigEditor/ConfigForm.tsx +50 -0
  24. package/config-ui/src/pages/ButtonConfigEditor/FormFieldParts.tsx +23 -0
  25. package/config-ui/src/pages/ButtonConfigEditor/PositionPicker.tsx +68 -0
  26. package/config-ui/src/pages/ButtonConfigEditor/controls/ActionControl.tsx +27 -0
  27. package/config-ui/src/pages/ButtonConfigEditor/controls/ArrayControl.tsx +77 -0
  28. package/config-ui/src/pages/ButtonConfigEditor/controls/BooleanControl.tsx +34 -0
  29. package/config-ui/src/pages/ButtonConfigEditor/controls/DeckSelectControl.tsx +47 -0
  30. package/config-ui/src/pages/ButtonConfigEditor/controls/EmojiControl.tsx +70 -0
  31. package/config-ui/src/pages/ButtonConfigEditor/controls/IconControl.tsx +31 -0
  32. package/config-ui/src/pages/ButtonConfigEditor/controls/ObjectControl.tsx +52 -0
  33. package/config-ui/src/pages/ButtonConfigEditor/controls/RecordControl.tsx +104 -0
  34. package/config-ui/src/pages/ButtonConfigEditor/controls/SelectControl.tsx +46 -0
  35. package/config-ui/src/pages/ButtonConfigEditor/controls/ShellControl.tsx +29 -0
  36. package/config-ui/src/pages/ButtonConfigEditor/controls/TextControl.tsx +36 -0
  37. package/config-ui/src/pages/ButtonConfigEditor/controls/UnionControl.tsx +96 -0
  38. package/config-ui/src/pages/ButtonConfigEditor/controls/registry.ts +17 -0
  39. package/config-ui/src/pages/ButtonConfigEditor/types.ts +67 -0
  40. package/config-ui/src/pages/ButtonConfigEditor/utils.ts +56 -0
  41. package/config-ui/src/pages/ButtonConfigEditor.tsx +226 -0
  42. package/config-ui/src/pages/ConfigPage.tsx +326 -0
  43. package/config-ui/src/pages/DecksPage.tsx +104 -0
  44. package/config-ui/src/pages/EditorPage.tsx +1697 -0
  45. package/config-ui/src/pages/ServiceLogsPage.tsx +130 -0
  46. package/config-ui/vite.config.ts +105 -0
  47. package/dist/main.mjs +327 -41554
  48. package/frontend/index.html +12 -0
  49. package/frontend/src/App.tsx +536 -0
  50. package/frontend/src/__mocks__/addons-registry.ts +2 -0
  51. package/frontend/src/__mocks__/theme.ts +1 -0
  52. package/frontend/src/__mocks__/themes-manifest.tsx +78 -0
  53. package/frontend/src/__mocks__/token.ts +2 -0
  54. package/frontend/src/bridge/client.ts +186 -0
  55. package/frontend/src/bridge/use-button-action.ts +31 -0
  56. package/frontend/src/bridge/ws-context.tsx +24 -0
  57. package/frontend/src/components/Deck.tsx +486 -0
  58. package/frontend/src/components/DisconnectedOverlay.tsx +82 -0
  59. package/frontend/src/components/ErrorBoundary.tsx +92 -0
  60. package/frontend/src/components/ReconnectingBanner.tsx +40 -0
  61. package/frontend/src/index.css +40 -0
  62. package/frontend/src/main.tsx +23 -0
  63. package/frontend/vite.config.ts +132 -0
  64. package/package.json +20 -6
  65. package/src/builtin-addons/coding-agents/global/backend.ts +15 -1
  66. package/src/builtin-addons/internal-settings/index.ts +0 -1
  67. package/src/builtin-addons/internal-settings/logo72x72.png +0 -0
  68. package/src/builtin-addons/media/backend.ts +21 -0
  69. package/src/builtin-addons/system-status/README.md +1 -1
  70. package/src/builtin-addons/system-status/domain/display-metrics.ts +1 -1
  71. package/src/builtin-addons/system-status/manifest.ts +1 -1
  72. package/src/cli/commands/emulator-mode.ts +27 -4
  73. package/src/cli/commands/service-manager.ts +53 -1
  74. package/src/device/black-frame.ts +3 -7
  75. package/src/vite/virtual-modules.ts +16 -1
@@ -0,0 +1,1697 @@
1
+ import { useEffect, useMemo, useRef, useState } from "react"
2
+ import {
3
+ Button,
4
+ Card,
5
+ Fieldset,
6
+ Input,
7
+ Label,
8
+ Modal,
9
+ Switch,
10
+ Tabs,
11
+ TextField,
12
+ toast,
13
+ } from "@heroui/react"
14
+ import { Check, CircleX, Layers, Plus, Rows3 } from "lucide-react"
15
+
16
+ import type { DeviceModelSpec } from "@sirenodeck/sirenodeck"
17
+ import { isSystemButtonType } from "@/deck/system-buttons/types"
18
+
19
+ import type { WsClient } from "../bridge"
20
+ import { DeckFrame } from "../DeckFrame"
21
+ import type { AddonInventory } from "./AddonsPage"
22
+ import {
23
+ ButtonConfigEditor,
24
+ type JsonSchema,
25
+ type ValidationState,
26
+ } from "./ButtonConfigEditor"
27
+ import { ButtonAppearanceFields } from "./ButtonConfigEditor/ButtonAppearanceFields"
28
+ import { PositionPicker } from "./ButtonConfigEditor/PositionPicker"
29
+ import type {
30
+ ButtonAppearance,
31
+ ButtonThemeVariant,
32
+ } from "./ButtonConfigEditor/types"
33
+ import type { PendingIconAsset } from "../components/IconPicker"
34
+ import {
35
+ ButtonTypePicker,
36
+ type ButtonTypeOption,
37
+ } from "./ButtonConfigEditor/ButtonTypePicker"
38
+ import { isValidActionValue } from "../components/ActionValueEditor"
39
+
40
+ type Button = Record<string, unknown> | string
41
+ const INLINE_CONTROL_ROW_CLASS =
42
+ "grid min-w-0 grid-cols-[minmax(min(10rem,42%),0.85fr)_minmax(0,1.15fr)] items-center gap-x-3 gap-y-1"
43
+
44
+ const gestureConfigKeys = {
45
+ tap: "tap",
46
+ "dbl-tap": "dbltap",
47
+ hold: "hold",
48
+ } as const
49
+
50
+ const withoutOwnedGestures = (
51
+ actions: ButtonAppearance["actions"],
52
+ owned: readonly (keyof typeof gestureConfigKeys)[],
53
+ ): ButtonAppearance["actions"] => {
54
+ const next = { ...actions }
55
+ for (const gesture of owned) delete next[gestureConfigKeys[gesture]]
56
+ return next
57
+ }
58
+ type Config = {
59
+ theme?: string | { src: string; global?: boolean }
60
+ decks?: Record<
61
+ string,
62
+ {
63
+ name?: string
64
+ label?: string
65
+ columns?: number
66
+ rows?: number
67
+ icon?: string
68
+ background?: string
69
+ paginated?: boolean
70
+ autoShow?: boolean
71
+ trigger?: {
72
+ process_name?: string | string[]
73
+ window_name?: string | string[]
74
+ }
75
+ buttons?: Button[]
76
+ }
77
+ >
78
+ }
79
+
80
+ interface DeckDraft {
81
+ name: string
82
+ columns: string
83
+ rows: string
84
+ icon: string
85
+ background: string
86
+ paginated: boolean
87
+ autoShow: boolean
88
+ processName: string
89
+ windowName: string
90
+ }
91
+
92
+ export interface ThemeOption {
93
+ readonly name: string
94
+ readonly active?: boolean
95
+ }
96
+
97
+ export interface EditorState {
98
+ readonly revision: number
99
+ readonly config: unknown
100
+ readonly sources: string[]
101
+ readonly sourceContents?: Record<string, string>
102
+ readonly themes?: readonly ThemeOption[]
103
+ readonly themeVariants?: Record<string, ButtonThemeVariant>
104
+ readonly surfaces?: Array<{
105
+ readonly id: string
106
+ readonly buttons: Array<{
107
+ readonly type: string
108
+ readonly position: number
109
+ }>
110
+ }>
111
+ readonly buttonSchemas?: Record<string, JsonSchema>
112
+ readonly canUndo: boolean
113
+ }
114
+
115
+ interface MutationResult {
116
+ readonly requestId: string
117
+ readonly ok: boolean
118
+ readonly error?: string
119
+ }
120
+
121
+ export interface EditorPageProps {
122
+ readonly wsClient: WsClient | null
123
+ readonly state: EditorState | null
124
+ readonly result: MutationResult | null
125
+ readonly addonInventory?: AddonInventory | null
126
+ readonly frontendUrl?: string
127
+ readonly device?: DeviceModelSpec
128
+ readonly token?: string
129
+ readonly onGesture?: (msg: {
130
+ deckId: string
131
+ position: number
132
+ gesture: "tap" | "dbl-tap" | "hold"
133
+ }) => void
134
+ readonly onDeckSelect?: (deckId: string) => void
135
+ readonly runtimeDeckId?: string | null
136
+ readonly validation?: ValidationState | null
137
+ }
138
+
139
+ let requestNumber = 0
140
+ const nextRequestId = (): string => `editor-${Date.now()}-${requestNumber++}`
141
+
142
+ const isButton = (button: Button): button is Record<string, unknown> =>
143
+ typeof button === "object" && button !== null && !Array.isArray(button)
144
+
145
+ type DragData =
146
+ | { kind: "palette"; button: Record<string, unknown> }
147
+ | { kind: "existing"; index: number }
148
+
149
+ const readDragData = (event: React.DragEvent): DragData | null => {
150
+ try {
151
+ const value = JSON.parse(event.dataTransfer.getData("application/json"))
152
+ if (
153
+ value?.kind === "palette" &&
154
+ typeof value.button === "object" &&
155
+ value.button !== null
156
+ )
157
+ return value as DragData
158
+ if (value?.kind === "existing" && typeof value.index === "number")
159
+ return value as DragData
160
+ } catch {
161
+ // Ignore drops from outside the editor.
162
+ }
163
+ return null
164
+ }
165
+
166
+ const buttonPositions = (buttons: Button[]): number[] => {
167
+ const used = new Set<number>()
168
+ let next = 0
169
+ return buttons.map((button) => {
170
+ const explicit =
171
+ isButton(button) && typeof button.position === "number"
172
+ ? button.position
173
+ : undefined
174
+ const position =
175
+ explicit !== undefined && explicit >= 0 && !used.has(explicit)
176
+ ? explicit
177
+ : (() => {
178
+ while (used.has(next)) next += 1
179
+ return next
180
+ })()
181
+ used.add(position)
182
+ next = Math.max(next, position + 1)
183
+ return position
184
+ })
185
+ }
186
+
187
+ export const EditorPage = ({
188
+ wsClient,
189
+ state,
190
+ result,
191
+ addonInventory = null,
192
+ frontendUrl,
193
+ device,
194
+ token,
195
+ onGesture,
196
+ onDeckSelect,
197
+ runtimeDeckId,
198
+ validation = null,
199
+ }: EditorPageProps) => {
200
+ const [deckSelection, setDeckSelection] = useState<{
201
+ readonly id: string
202
+ readonly runtimeDeckId: string | null
203
+ } | null>(null)
204
+ const [selectedIndex, setSelectedIndex] = useState<number | null>(null)
205
+ const [selectedPosition, setSelectedPosition] = useState<number | null>(null)
206
+ const [clipboard, setClipboard] = useState<Button | null>(null)
207
+ const [message, setMessage] = useState<string | null>(null)
208
+ const [pendingButton, setPendingButton] = useState<Record<
209
+ string,
210
+ unknown
211
+ > | null>(null)
212
+ const [pendingPosition, setPendingPosition] = useState<number | null>(null)
213
+ const [positionToReplace, setPositionToReplace] = useState<number | null>(
214
+ null,
215
+ )
216
+ const [newPage, setNewPage] = useState(false)
217
+ const [newPageId, setNewPageId] = useState("")
218
+ const [newPageName, setNewPageName] = useState("")
219
+ const [newPageIcon, setNewPageIcon] = useState("")
220
+ const [newPageBackground, setNewPageBackground] = useState("")
221
+ const [newPagePaginated, setNewPagePaginated] = useState(false)
222
+ const [positionUnset, setPositionUnset] = useState(false)
223
+ const [buttonTypeOverride, setButtonTypeOverride] = useState<string | null>(
224
+ null,
225
+ )
226
+ const [selectionDeckId, setSelectionDeckId] = useState<string | null>(null)
227
+ const skipPositionSelectionSync = useRef(false)
228
+ const [pendingRequestId, setPendingRequestId] = useState<string | null>(null)
229
+ const lastResultId = useRef<string | null>(null)
230
+ const [deckDraft, setDeckDraft] = useState<DeckDraft | null>(null)
231
+ const [creatingDeck, setCreatingDeck] = useState(false)
232
+ const [newDeckId, setNewDeckId] = useState("")
233
+ const [newDeckName, setNewDeckName] = useState("")
234
+ const [buttonAppearance, setButtonAppearance] = useState<ButtonAppearance>({
235
+ variant: "",
236
+ actions: {},
237
+ })
238
+ const [pendingAssets, setPendingAssets] = useState<
239
+ Record<string, PendingIconAsset>
240
+ >({})
241
+ const [assetWriteQueue, setAssetWriteQueue] = useState<{
242
+ requestId: string
243
+ assets: PendingIconAsset[]
244
+ next: number
245
+ mutation: Record<string, unknown>
246
+ } | null>(null)
247
+
248
+ useEffect(() => {
249
+ wsClient?.send(JSON.stringify({ type: "editor-state-request" }))
250
+ }, [wsClient])
251
+
252
+ useEffect(() => {
253
+ if (result === null || result.requestId === lastResultId.current) return
254
+ lastResultId.current = result.requestId
255
+ if (
256
+ assetWriteQueue !== null &&
257
+ result.requestId === assetWriteQueue.requestId
258
+ ) {
259
+ if (!result.ok) {
260
+ toast.danger(result.error ?? "Could not save icon asset")
261
+ setMessage(null)
262
+ setAssetWriteQueue(null)
263
+ return
264
+ }
265
+ const next = assetWriteQueue.next + 1
266
+ const asset = assetWriteQueue.assets[next]
267
+ if (asset !== undefined) {
268
+ const requestId = nextRequestId()
269
+ wsClient?.send(
270
+ JSON.stringify({
271
+ type: "editor-asset-write",
272
+ requestId,
273
+ revision: state?.revision ?? 0,
274
+ filename: asset.filename,
275
+ data: asset.data,
276
+ }),
277
+ )
278
+ setAssetWriteQueue({ ...assetWriteQueue, requestId, next })
279
+ } else {
280
+ const mutationRequestId = sendMutation(assetWriteQueue.mutation)
281
+ if (pendingButton !== null && mutationRequestId !== null)
282
+ setPendingRequestId(mutationRequestId)
283
+ setAssetWriteQueue(null)
284
+ setPendingAssets({})
285
+ }
286
+ return
287
+ }
288
+ if (result.ok) toast.success("Saved")
289
+ else toast.danger(result.error ?? "Edit failed")
290
+ setMessage(null)
291
+ if (result.requestId !== pendingRequestId) return
292
+ if (result.ok) {
293
+ if (newPage) {
294
+ const nextDeckId = newPageId.trim()
295
+ setDeckSelection({
296
+ id: nextDeckId,
297
+ runtimeDeckId: runtimeDeckId ?? null,
298
+ })
299
+ onDeckSelect?.(nextDeckId)
300
+ setSelectedIndex(null)
301
+ setSelectedPosition(null)
302
+ setSelectionDeckId(null)
303
+ }
304
+ setPendingButton(null)
305
+ setPendingPosition(null)
306
+ setNewPage(false)
307
+ setPendingRequestId(null)
308
+ }
309
+ }, [
310
+ assetWriteQueue,
311
+ newPage,
312
+ newPageId,
313
+ onDeckSelect,
314
+ pendingButton,
315
+ pendingRequestId,
316
+ result,
317
+ runtimeDeckId,
318
+ state?.revision,
319
+ wsClient,
320
+ ])
321
+
322
+ const config = (state?.config ?? {}) as Config
323
+ const decks = Object.entries(config.decks ?? {})
324
+ const activeDeckId =
325
+ deckSelection?.runtimeDeckId === (runtimeDeckId ?? null)
326
+ ? deckSelection.id
327
+ : (runtimeDeckId ?? decks[0]?.[0] ?? null)
328
+ const activeDeck =
329
+ activeDeckId === null ? undefined : config.decks?.[activeDeckId]
330
+ const buttons =
331
+ activeDeckId === null ? [] : (config.decks?.[activeDeckId]?.buttons ?? [])
332
+ const pageMatch = activeDeckId?.match(/^(.+)-p(\d+)$/)
333
+ const pageBase = pageMatch?.[1] ?? activeDeckId
334
+ const pageNumber =
335
+ pageMatch === null || pageMatch === undefined ? 1 : Number(pageMatch[2])
336
+ const previousPage =
337
+ pageNumber > 1 ? `${pageBase}-p${pageNumber - 1}` : pageBase
338
+ const nextPage = `${pageBase}-p${pageNumber + 1}`
339
+ const hasPreviousPage =
340
+ previousPage !== activeDeckId && decks.some(([id]) => id === previousPage)
341
+ const hasNextPage = decks.some(([id]) => id === nextPage)
342
+ const positions = buttonPositions(buttons)
343
+
344
+ useEffect(() => {
345
+ if (activeDeckId === null || activeDeck === undefined) {
346
+ setDeckDraft(null)
347
+ return
348
+ }
349
+ const processName = activeDeck.trigger?.process_name
350
+ const windowName = activeDeck.trigger?.window_name
351
+ setDeckDraft({
352
+ name: activeDeck.name ?? activeDeckId,
353
+ columns:
354
+ activeDeck.columns === undefined ? "" : String(activeDeck.columns),
355
+ rows: activeDeck.rows === undefined ? "" : String(activeDeck.rows),
356
+ icon: activeDeck.icon ?? "",
357
+ background: activeDeck.background ?? "",
358
+ paginated: activeDeck.paginated === true,
359
+ autoShow: activeDeck.autoShow === true,
360
+ processName: Array.isArray(processName)
361
+ ? processName.join(", ")
362
+ : (processName ?? ""),
363
+ windowName: Array.isArray(windowName)
364
+ ? windowName.join(", ")
365
+ : (windowName ?? ""),
366
+ })
367
+ }, [activeDeckId, state?.revision])
368
+ const selected =
369
+ selectionDeckId === activeDeckId && selectedIndex !== null
370
+ ? buttons[selectedIndex]
371
+ : undefined
372
+ const activeSelectedPosition =
373
+ selectionDeckId === activeDeckId ? selectedPosition : null
374
+ const selectedType =
375
+ selected === undefined
376
+ ? null
377
+ : isButton(selected) && typeof selected.type === "string"
378
+ ? selected.type
379
+ : String(selected)
380
+ const currentButtonType =
381
+ pendingButton?.type ?? buttonTypeOverride ?? selectedType
382
+ const selectedGenerated =
383
+ selected !== undefined &&
384
+ ((isButton(selected) && selected.generated === true) ||
385
+ addonInventory?.addons.some((addon) =>
386
+ addon.buttonTypes.some(
387
+ (type) => type.type === selectedType && type.generated === true,
388
+ ),
389
+ ) === true)
390
+ const buttonSchema =
391
+ currentButtonType === undefined || currentButtonType === null
392
+ ? undefined
393
+ : state?.buttonSchemas?.[String(currentButtonType)]
394
+ const deckOptions = [
395
+ ...decks.map(([id, deck]) => ({ id, name: deck.name ?? id })),
396
+ ...(addonInventory?.addons ?? []).flatMap((addon) =>
397
+ addon.internal
398
+ ? []
399
+ : addon.decks
400
+ .filter((deck) => !deck.internal)
401
+ .map((deck) => ({ id: deck.id, name: deck.id })),
402
+ ),
403
+ ].filter(
404
+ (deck, index, all) =>
405
+ all.findIndex((item) => item.id === deck.id) === index,
406
+ )
407
+ const addableButtonTypes: ButtonTypeOption[] = [
408
+ ...(addonInventory?.addons ?? []).flatMap((addon) =>
409
+ addon.buttonTypes
410
+ .filter((buttonType) => !buttonType.internal)
411
+ .map((buttonType) => ({
412
+ addon: addon.name,
413
+ type: buttonType.type,
414
+ defaultConfig: buttonType.defaultConfig,
415
+ gestureHandlers: buttonType.gestureHandlers,
416
+ })),
417
+ ),
418
+ ].filter(
419
+ (buttonType, index, all) =>
420
+ all.findIndex((candidate) => candidate.type === buttonType.type) ===
421
+ index,
422
+ )
423
+ const currentButtonTypeInfo = addonInventory?.addons
424
+ .flatMap((addon) => addon.buttonTypes)
425
+ .find((buttonType) => buttonType.type === currentButtonType)
426
+ const ownedGestures = currentButtonTypeInfo?.gestureHandlers ?? []
427
+ const buttonEditorConfig = useMemo(() => {
428
+ if (buttonTypeOverride !== null)
429
+ return currentButtonTypeInfo?.defaultConfig ?? {}
430
+ const config =
431
+ isButton(selected) &&
432
+ typeof selected.config === "object" &&
433
+ selected.config !== null &&
434
+ !Array.isArray(selected.config)
435
+ ? { ...(selected.config as Record<string, unknown>) }
436
+ : {}
437
+ if (isButton(selected)) {
438
+ for (const key of ["icon", "label"] as const) {
439
+ if (
440
+ buttonSchema?.properties?.[key] !== undefined &&
441
+ typeof selected[key] === "string"
442
+ )
443
+ config[key] = selected[key]
444
+ }
445
+ }
446
+ return config
447
+ }, [buttonSchema, buttonTypeOverride, currentButtonTypeInfo, selected])
448
+ const activeSurface = state?.surfaces?.find(
449
+ (surface) => surface.id === activeDeckId,
450
+ )
451
+ const systemPositions =
452
+ activeSurface?.buttons
453
+ .filter((button) => isSystemButtonType(button.type))
454
+ .map((button) => button.position) ?? []
455
+ const firstFreePosition = (): number | undefined => {
456
+ const used = new Set([...positions, ...systemPositions])
457
+ for (let position = 0; position < (device?.keyCount ?? 15); position += 1) {
458
+ if (!used.has(position)) return position
459
+ }
460
+ return undefined
461
+ }
462
+ const [editionTab, setEditionTab] = useState<"buttons" | "decks">("buttons")
463
+ const [showButtonTypes, setShowButtonTypes] = useState(false)
464
+ const [hoveredPosition, setHoveredPosition] = useState<number | null>(null)
465
+ const [buttonDraft, setButtonDraft] = useState<Record<
466
+ string,
467
+ unknown
468
+ > | null>(null)
469
+ const [buttonPreviewDraft, setButtonPreviewDraft] = useState<Record<
470
+ string,
471
+ unknown
472
+ > | null>(null)
473
+
474
+ const changeDeck = (nextDeckId: string): void => {
475
+ setDeckSelection({
476
+ id: nextDeckId,
477
+ runtimeDeckId: runtimeDeckId ?? null,
478
+ })
479
+ setSelectedIndex(null)
480
+ setSelectedPosition(null)
481
+ setSelectionDeckId(null)
482
+ setPendingButton(null)
483
+ setPendingPosition(null)
484
+ setPositionToReplace(null)
485
+ setButtonTypeOverride(null)
486
+ setShowButtonTypes(false)
487
+ setButtonDraft(null)
488
+ setButtonPreviewDraft(null)
489
+ setPendingAssets({})
490
+ onDeckSelect?.(nextDeckId)
491
+ }
492
+
493
+ const previousActiveDeckId = useRef(activeDeckId)
494
+ const previousRuntimeDeckId = useRef(runtimeDeckId)
495
+
496
+ useEffect(() => {
497
+ if (previousRuntimeDeckId.current === runtimeDeckId) return
498
+ previousRuntimeDeckId.current = runtimeDeckId
499
+ setDeckSelection(null)
500
+ }, [runtimeDeckId])
501
+
502
+ useEffect(() => {
503
+ if (previousActiveDeckId.current === activeDeckId) return
504
+ previousActiveDeckId.current = activeDeckId
505
+ setSelectedIndex(null)
506
+ setSelectedPosition(null)
507
+ setSelectionDeckId(null)
508
+ setPendingButton(null)
509
+ setPendingPosition(null)
510
+ setPositionToReplace(null)
511
+ setButtonTypeOverride(null)
512
+ setShowButtonTypes(false)
513
+ setButtonDraft(null)
514
+ }, [activeDeckId])
515
+
516
+ useEffect(() => {
517
+ if (selectionDeckId !== activeDeckId) return
518
+ if (skipPositionSelectionSync.current) {
519
+ skipPositionSelectionSync.current = false
520
+ return
521
+ }
522
+ if (activeSelectedPosition !== null) {
523
+ const index = positions.indexOf(activeSelectedPosition)
524
+ if (index >= 0 && index !== selectedIndex) setSelectedIndex(index)
525
+ }
526
+ if (selectedIndex !== null && selectedIndex >= buttons.length) {
527
+ setSelectedIndex(buttons.length === 0 ? null : buttons.length - 1)
528
+ }
529
+ }, [
530
+ activeDeckId,
531
+ activeSelectedPosition,
532
+ selectedIndex,
533
+ selectionDeckId,
534
+ state?.revision,
535
+ ])
536
+
537
+ useEffect(
538
+ () => setButtonDraft(null),
539
+ [buttonTypeOverride, pendingButton, selectedIndex],
540
+ )
541
+ useEffect(
542
+ () => setButtonPreviewDraft(null),
543
+ [buttonTypeOverride, pendingButton, selectedIndex],
544
+ )
545
+ useEffect(() => setButtonTypeOverride(null), [activeDeckId, selectedIndex])
546
+
547
+ useEffect(() => {
548
+ const current = pendingButton ?? selected
549
+ const fields =
550
+ typeof current === "object" && current !== null && !Array.isArray(current)
551
+ ? current
552
+ : {}
553
+ setButtonAppearance({
554
+ variant: typeof fields.variant === "string" ? fields.variant : "",
555
+ actions:
556
+ typeof fields.actions === "object" && fields.actions !== null
557
+ ? (fields.actions as ButtonAppearance["actions"])
558
+ : {},
559
+ })
560
+ setPendingAssets({})
561
+ }, [activeDeckId, pendingButton, selected, selectedIndex, state?.revision])
562
+
563
+ const chooseAsset = (
564
+ path: string,
565
+ asset: PendingIconAsset | undefined,
566
+ ): void =>
567
+ setPendingAssets((current) => {
568
+ const next = { ...current }
569
+ if (asset === undefined) delete next[path]
570
+ else next[path] = asset
571
+ return next
572
+ })
573
+
574
+ const sendMutation = (mutation: Record<string, unknown>): string | null => {
575
+ if (state === null) return null
576
+ const requestId = nextRequestId()
577
+ wsClient?.send(
578
+ JSON.stringify({
579
+ type: "editor-mutate",
580
+ requestId,
581
+ revision: state.revision,
582
+ mutation,
583
+ }),
584
+ )
585
+ setMessage("Saving…")
586
+ return requestId
587
+ }
588
+
589
+ const persistMutation = (mutation: Record<string, unknown>): void => {
590
+ const assets = Object.values(pendingAssets)
591
+ if (assets.length === 0) {
592
+ const requestId = sendMutation(mutation)
593
+ if (pendingButton !== null && requestId !== null)
594
+ setPendingRequestId(requestId)
595
+ setPendingAssets({})
596
+ return
597
+ }
598
+ const first = assets[0]!
599
+ const requestId = nextRequestId()
600
+ wsClient?.send(
601
+ JSON.stringify({
602
+ type: "editor-asset-write",
603
+ requestId,
604
+ revision: state?.revision ?? 0,
605
+ filename: first.filename,
606
+ data: first.data,
607
+ }),
608
+ )
609
+ setAssetWriteQueue({ requestId, assets, next: 0, mutation })
610
+ setMessage("Saving icon asset…")
611
+ }
612
+
613
+ const selectPosition = (position: number): void => {
614
+ const index = buttons.findIndex((_, i) => positions[i] === position)
615
+ setSelectedPosition(position)
616
+ setSelectedIndex(index === -1 ? null : index)
617
+ setSelectionDeckId(activeDeckId)
618
+ }
619
+
620
+ const stagePendingPosition = (position: number): void => {
621
+ setPendingPosition(position)
622
+ setPositionUnset(false)
623
+ setNewPage(false)
624
+ }
625
+
626
+ const moveSelectedToPosition = (position: number): void => {
627
+ if (selectedIndex === null || activeDeckId === null) return
628
+ const targetIndex = positions.indexOf(position)
629
+ if (targetIndex >= 0 && targetIndex !== selectedIndex) {
630
+ skipPositionSelectionSync.current = true
631
+ sendMutation({
632
+ kind: "move-position",
633
+ deckId: activeDeckId,
634
+ from: selectedIndex,
635
+ to: targetIndex,
636
+ })
637
+ }
638
+ setSelectedPosition(position)
639
+ setSelectionDeckId(activeDeckId)
640
+ }
641
+
642
+ const beginInsert = (
643
+ button: Record<string, unknown>,
644
+ position?: number,
645
+ ): void => {
646
+ setShowButtonTypes(false)
647
+ setPendingButton(button)
648
+ setPendingPosition(position ?? firstFreePosition() ?? null)
649
+ setPositionToReplace(null)
650
+ setPositionUnset(false)
651
+ setNewPage(false)
652
+ setNewPageId(activeDeckId === null ? "page-2" : `${activeDeckId}-p2`)
653
+ setNewPageName(
654
+ `${config.decks?.[activeDeckId ?? ""]?.name ?? activeDeckId ?? "Deck"} 2`,
655
+ )
656
+ setSelectedIndex(null)
657
+ setSelectedPosition(null)
658
+ setSelectionDeckId(null)
659
+ }
660
+
661
+ const add = (index?: number): void => {
662
+ if (activeDeckId === null) return
663
+ const button =
664
+ clipboard === null ? { type: "core:action", config: {} } : clipboard
665
+ if (activeSelectedPosition !== null)
666
+ return beginInsert(
667
+ isButton(button) ? button : { type: button, config: {} },
668
+ activeSelectedPosition,
669
+ )
670
+ beginInsert(
671
+ isButton(button) ? button : { type: button },
672
+ index === undefined ? undefined : firstFreePosition(),
673
+ )
674
+ }
675
+
676
+ const dropAt = (event: React.DragEvent, index: number): void => {
677
+ event.preventDefault()
678
+ if (activeDeckId === null) return
679
+ const data = readDragData(event)
680
+ if (data?.kind === "palette") {
681
+ beginInsert(data.button, index)
682
+ } else if (data?.kind === "existing" && data.index !== index) {
683
+ sendMutation({
684
+ kind: "reorder",
685
+ deckId: activeDeckId,
686
+ from: data.index,
687
+ to: index,
688
+ })
689
+ }
690
+ }
691
+
692
+ const keyAction = (
693
+ position: number,
694
+ action: "edit" | "copy" | "duplicate" | "up" | "down" | "delete",
695
+ ): void => {
696
+ const index = positions.indexOf(position)
697
+ const button = index < 0 ? undefined : buttons[index]
698
+ if (action === "edit") return selectPosition(position)
699
+ if (button === undefined || activeDeckId === null) return
700
+ if (action === "copy") {
701
+ setClipboard(button)
702
+ setMessage("Copied")
703
+ } else if (action === "duplicate") {
704
+ sendMutation({
705
+ kind: "add",
706
+ deckId: activeDeckId,
707
+ index: index + 1,
708
+ button,
709
+ })
710
+ } else if (action === "delete") {
711
+ sendMutation({ kind: "delete", deckId: activeDeckId, index })
712
+ } else {
713
+ const to = action === "up" ? index - 1 : index + 1
714
+ if (to >= 0 && to < buttons.length)
715
+ sendMutation({
716
+ kind: "move-position",
717
+ deckId: activeDeckId,
718
+ from: index,
719
+ to,
720
+ })
721
+ }
722
+ }
723
+
724
+ const saveConfig = (config: Record<string, unknown>): void => {
725
+ if (
726
+ activeDeckId === null ||
727
+ selectedIndex === null ||
728
+ selected === undefined
729
+ )
730
+ return
731
+ const actions = withoutOwnedGestures(
732
+ buttonAppearance.actions,
733
+ ownedGestures,
734
+ )
735
+ if (!Object.values(actions).every(isValidActionValue)) {
736
+ toast.danger("Fix the keyboard macro before saving")
737
+ return
738
+ }
739
+ const button = isButton(selected) ? { ...selected } : { type: selected }
740
+ delete button.icon
741
+ delete button.label
742
+ const type = buttonTypeOverride ?? selectedType ?? String(button.type)
743
+ persistMutation({
744
+ kind: "update",
745
+ deckId: activeDeckId,
746
+ index: selectedIndex,
747
+ button: {
748
+ ...button,
749
+ type,
750
+ ...buttonAppearance,
751
+ ...(buttonAppearance.variant === "" ? { variant: undefined } : {}),
752
+ ...(Object.values(actions).some(Boolean)
753
+ ? { actions }
754
+ : { actions: undefined }),
755
+ ...(activeSelectedPosition !== null &&
756
+ activeSelectedPosition !== positions[selectedIndex]
757
+ ? { position: activeSelectedPosition }
758
+ : {}),
759
+ config,
760
+ },
761
+ })
762
+ }
763
+
764
+ const addPending = (config: Record<string, unknown>): void => {
765
+ if (activeDeckId === null || pendingButton === null) return
766
+ const actions = withoutOwnedGestures(
767
+ buttonAppearance.actions,
768
+ ownedGestures,
769
+ )
770
+ if (!Object.values(actions).every(isValidActionValue)) {
771
+ toast.danger("Fix the keyboard macro before adding this button")
772
+ return
773
+ }
774
+ const position = newPage
775
+ ? 0
776
+ : positionUnset
777
+ ? undefined
778
+ : (pendingPosition ?? firstFreePosition())
779
+ const targetDeckId = newPage ? newPageId.trim() : activeDeckId
780
+ if (
781
+ targetDeckId.length === 0 ||
782
+ (newPage && newPageName.trim().length === 0)
783
+ )
784
+ return
785
+ const index =
786
+ newPage || position === undefined ? -1 : positions.indexOf(position)
787
+ const nextConfig =
788
+ pendingButton.type === "core:change-deck" && newPage
789
+ ? { ...config, deck: targetDeckId }
790
+ : config
791
+ persistMutation({
792
+ kind: "add-button",
793
+ deckId: activeDeckId,
794
+ ...(index >= 0 && !newPage ? { replaceIndex: index } : {}),
795
+ ...(newPage
796
+ ? {
797
+ index: 0,
798
+ newDeck: {
799
+ id: targetDeckId,
800
+ name: newPageName.trim(),
801
+ ...(newPageIcon.trim() ? { icon: newPageIcon.trim() } : {}),
802
+ ...(newPageBackground.trim()
803
+ ? { background: newPageBackground.trim() }
804
+ : {}),
805
+ ...(newPagePaginated ? { paginated: true } : {}),
806
+ },
807
+ }
808
+ : { index: index >= 0 ? index : buttons.length }),
809
+ button: {
810
+ ...pendingButton,
811
+ ...buttonAppearance,
812
+ ...(buttonAppearance.variant === "" ? { variant: undefined } : {}),
813
+ ...(Object.values(actions).some(Boolean)
814
+ ? { actions }
815
+ : { actions: undefined }),
816
+ config: nextConfig,
817
+ ...(position === undefined ? {} : { position }),
818
+ },
819
+ })
820
+ }
821
+
822
+ const undo = (): void => {
823
+ if (state === null) return
824
+ wsClient?.send(
825
+ JSON.stringify({
826
+ type: "editor-undo",
827
+ requestId: nextRequestId(),
828
+ revision: state.revision,
829
+ }),
830
+ )
831
+ setMessage("Undoing…")
832
+ }
833
+
834
+ useEffect(() => {
835
+ const onKeyDown = (event: KeyboardEvent): void => {
836
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
837
+ event.preventDefault()
838
+ undo()
839
+ }
840
+ }
841
+ window.addEventListener("keydown", onKeyDown)
842
+ return () => window.removeEventListener("keydown", onKeyDown)
843
+ })
844
+
845
+ return (
846
+ <section className="flex h-full min-h-0 flex-col gap-4 overflow-hidden p-1">
847
+ {message !== null && (
848
+ <p role="status" aria-live="polite" className="text-sm text-muted">
849
+ {message}
850
+ </p>
851
+ )}
852
+ {state === null ? (
853
+ <p className="text-sm text-neutral-400">Loading configured decks…</p>
854
+ ) : (
855
+ <div className="grid min-h-0 flex-1 gap-4 lg:grid-cols-2">
856
+ <Card
857
+ aria-labelledby="preview-title"
858
+ className="flex min-w-0 min-h-0 flex-col"
859
+ >
860
+ <Card.Header>
861
+ <Card.Title id="preview-title">Live preview</Card.Title>
862
+ </Card.Header>
863
+ <Card.Content className="flex min-h-0 flex-1 items-center justify-center overflow-auto">
864
+ {frontendUrl !== undefined &&
865
+ device !== undefined &&
866
+ activeDeckId !== null ? (
867
+ <div
868
+ data-testid="editor-preview"
869
+ onDragOver={(event) => event.preventDefault()}
870
+ className="overflow-hidden rounded-xl"
871
+ >
872
+ <DeckFrame
873
+ frontendUrl={frontendUrl}
874
+ device={device}
875
+ deckId={activeDeckId}
876
+ token={token}
877
+ onGesture={onGesture}
878
+ onKeyAction={keyAction}
879
+ systemPositions={systemPositions}
880
+ fitToContainer
881
+ highlightedKey={
882
+ hoveredPosition ??
883
+ activeSelectedPosition ??
884
+ pendingPosition
885
+ }
886
+ previewConfig={
887
+ buttonPreviewDraft === null
888
+ ? null
889
+ : {
890
+ index:
891
+ pendingButton === null
892
+ ? (selectedIndex ??
893
+ firstFreePosition() ??
894
+ buttons.length)
895
+ : (pendingPosition ??
896
+ firstFreePosition() ??
897
+ buttons.length),
898
+ position:
899
+ pendingButton === null
900
+ ? (activeSelectedPosition ??
901
+ positions[selectedIndex ?? -1])
902
+ : (pendingPosition ?? firstFreePosition()),
903
+ ...(currentButtonType !== null &&
904
+ currentButtonType !== undefined
905
+ ? { type: String(currentButtonType) }
906
+ : {}),
907
+ config: buttonPreviewDraft,
908
+ appearance: buttonAppearance,
909
+ assets: Object.values(pendingAssets).map(
910
+ ({ filename, preview }) => ({
911
+ filename,
912
+ preview,
913
+ }),
914
+ ),
915
+ }
916
+ }
917
+ onDropPosition={(position, event) =>
918
+ dropAt(event, position)
919
+ }
920
+ />
921
+ </div>
922
+ ) : (
923
+ <p className="text-sm text-neutral-500">
924
+ Preview unavailable until the device is connected.
925
+ </p>
926
+ )}
927
+ </Card.Content>
928
+ </Card>
929
+ <Card
930
+ aria-labelledby="edition-panel-title"
931
+ className="flex min-w-0 min-h-0 flex-col"
932
+ >
933
+ <Card.Header className="flex flex-row items-center justify-between gap-3">
934
+ <Card.Title id="edition-panel-title">Edition panel</Card.Title>
935
+ <div className="flex items-center gap-2">
936
+ {editionTab === "buttons" &&
937
+ pendingButton === null &&
938
+ !showButtonTypes &&
939
+ (selected === undefined || !selectedGenerated) && (
940
+ <Button
941
+ type="button"
942
+ variant="primary"
943
+ onPress={() => setShowButtonTypes(true)}
944
+ >
945
+ {selected === undefined ? (
946
+ <>
947
+ <Plus aria-hidden="true" className="size-4" />
948
+ New button
949
+ </>
950
+ ) : (
951
+ `Change type: ${String(currentButtonType ?? selectedType)}`
952
+ )}
953
+ </Button>
954
+ )}
955
+ <Tabs
956
+ selectedKey={editionTab}
957
+ onSelectionChange={(key) =>
958
+ setEditionTab(String(key) as typeof editionTab)
959
+ }
960
+ >
961
+ <Tabs.ListContainer>
962
+ <Tabs.List className="w-fit rounded-full bg-neutral-800 p-1">
963
+ <Tabs.Tab
964
+ id="buttons"
965
+ className="rounded-full px-3 py-1.5 text-xs"
966
+ >
967
+ <Rows3 aria-hidden="true" className="size-4" />
968
+ Buttons
969
+ <Tabs.Indicator />
970
+ </Tabs.Tab>
971
+ <Tabs.Tab
972
+ id="decks"
973
+ className="rounded-full px-3 py-1.5 text-xs"
974
+ >
975
+ <Layers aria-hidden="true" className="size-4" />
976
+ Decks
977
+ <Tabs.Indicator />
978
+ </Tabs.Tab>
979
+ </Tabs.List>
980
+ </Tabs.ListContainer>
981
+ </Tabs>
982
+ {editionTab === "decks" && !creatingDeck && (
983
+ <Button
984
+ type="button"
985
+ variant="primary"
986
+ className="order-first"
987
+ onPress={() => setCreatingDeck(true)}
988
+ >
989
+ <Plus aria-hidden="true" className="size-4" />
990
+ New deck
991
+ </Button>
992
+ )}
993
+ </div>
994
+ </Card.Header>
995
+ <Card.Content className="min-h-0 flex-1 overflow-y-auto">
996
+ {editionTab === "decks" && (
997
+ <div role="tabpanel" aria-label="Decks" className="space-y-4">
998
+ <section aria-labelledby="deck-config-title">
999
+ <h3
1000
+ id="deck-config-title"
1001
+ className="mb-2 text-xs font-semibold uppercase tracking-wider text-neutral-500"
1002
+ >
1003
+ Active deck
1004
+ </h3>
1005
+ {activeDeckId === null ? (
1006
+ <p className="text-sm text-neutral-500">
1007
+ No deck selected.
1008
+ </p>
1009
+ ) : deckDraft === null ? (
1010
+ <p className="text-sm text-neutral-500">
1011
+ Addon-provided decks are read-only here; edit their
1012
+ configured overrides in YAML.
1013
+ </p>
1014
+ ) : (
1015
+ <div className="grid gap-3 sm:grid-cols-2">
1016
+ <p className="text-sm text-neutral-300 sm:col-span-2">
1017
+ <span className="block text-xs uppercase tracking-wider text-neutral-500">
1018
+ ID
1019
+ </span>
1020
+ <code>{activeDeckId}</code>
1021
+ </p>
1022
+ <p className="text-sm text-neutral-300">
1023
+ <span className="block text-xs uppercase tracking-wider text-neutral-500">
1024
+ Buttons
1025
+ </span>
1026
+ {buttons.length}
1027
+ </p>
1028
+ {(hasPreviousPage || hasNextPage) && (
1029
+ <div className="flex gap-2 sm:col-span-2">
1030
+ <Button
1031
+ type="button"
1032
+ variant="tertiary"
1033
+ isDisabled={!hasPreviousPage}
1034
+ onPress={() => {
1035
+ if (!hasPreviousPage) return
1036
+ changeDeck(previousPage)
1037
+ }}
1038
+ >
1039
+ Previous page
1040
+ </Button>
1041
+ <Button
1042
+ type="button"
1043
+ variant="tertiary"
1044
+ isDisabled={!hasNextPage}
1045
+ onPress={() => {
1046
+ if (!hasNextPage) return
1047
+ changeDeck(nextPage)
1048
+ }}
1049
+ >
1050
+ Next page
1051
+ </Button>
1052
+ </div>
1053
+ )}
1054
+ <TextField
1055
+ className={`${INLINE_CONTROL_ROW_CLASS} sm:col-span-2`}
1056
+ >
1057
+ <Label className="min-w-0 break-words">Name</Label>
1058
+ <Input
1059
+ aria-label="Deck name"
1060
+ value={deckDraft.name}
1061
+ onChange={(event) =>
1062
+ setDeckDraft({
1063
+ ...deckDraft,
1064
+ name: event.target.value,
1065
+ })
1066
+ }
1067
+ />
1068
+ </TextField>
1069
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1070
+ <Label className="min-w-0 break-words">Icon</Label>
1071
+ <Input
1072
+ aria-label="Deck icon"
1073
+ value={deckDraft.icon}
1074
+ onChange={(event) =>
1075
+ setDeckDraft({
1076
+ ...deckDraft,
1077
+ icon: event.target.value,
1078
+ })
1079
+ }
1080
+ />
1081
+ </TextField>
1082
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1083
+ <Label className="min-w-0 break-words">
1084
+ Background
1085
+ </Label>
1086
+ <Input
1087
+ aria-label="Deck background"
1088
+ value={deckDraft.background}
1089
+ onChange={(event) =>
1090
+ setDeckDraft({
1091
+ ...deckDraft,
1092
+ background: event.target.value,
1093
+ })
1094
+ }
1095
+ />
1096
+ </TextField>
1097
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1098
+ <Label className="min-w-0 break-words">
1099
+ Trigger process
1100
+ </Label>
1101
+ <Input
1102
+ aria-label="Trigger process"
1103
+ placeholder="chrome, slack"
1104
+ value={deckDraft.processName}
1105
+ onChange={(event) =>
1106
+ setDeckDraft({
1107
+ ...deckDraft,
1108
+ processName: event.target.value,
1109
+ })
1110
+ }
1111
+ />
1112
+ </TextField>
1113
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1114
+ <Label className="min-w-0 break-words">
1115
+ Trigger window
1116
+ </Label>
1117
+ <Input
1118
+ aria-label="Trigger window"
1119
+ value={deckDraft.windowName}
1120
+ onChange={(event) =>
1121
+ setDeckDraft({
1122
+ ...deckDraft,
1123
+ windowName: event.target.value,
1124
+ })
1125
+ }
1126
+ />
1127
+ </TextField>
1128
+ <Switch
1129
+ isSelected={deckDraft.paginated}
1130
+ onChange={(paginated) =>
1131
+ setDeckDraft({
1132
+ ...deckDraft,
1133
+ paginated,
1134
+ })
1135
+ }
1136
+ className="w-full min-w-0"
1137
+ >
1138
+ <Switch.Content
1139
+ className={`${INLINE_CONTROL_ROW_CLASS} w-full cursor-pointer`}
1140
+ >
1141
+ <Label>Paginated</Label>
1142
+ <Switch.Control>
1143
+ <Switch.Thumb />
1144
+ </Switch.Control>
1145
+ </Switch.Content>
1146
+ </Switch>
1147
+ <Switch
1148
+ isSelected={deckDraft.autoShow}
1149
+ onChange={(autoShow) =>
1150
+ setDeckDraft({
1151
+ ...deckDraft,
1152
+ autoShow,
1153
+ })
1154
+ }
1155
+ className="w-full min-w-0"
1156
+ >
1157
+ <Switch.Content
1158
+ className={`${INLINE_CONTROL_ROW_CLASS} w-full cursor-pointer`}
1159
+ >
1160
+ <Label>Auto show overlay</Label>
1161
+ <Switch.Control>
1162
+ <Switch.Thumb />
1163
+ </Switch.Control>
1164
+ </Switch.Content>
1165
+ </Switch>
1166
+ <Button
1167
+ type="button"
1168
+ variant="primary"
1169
+ onPress={() => {
1170
+ if (activeDeckId === null) return
1171
+ const process = deckDraft.processName
1172
+ .split(",")
1173
+ .map((value) => value.trim())
1174
+ .filter(Boolean)
1175
+ const window = deckDraft.windowName
1176
+ .split(",")
1177
+ .map((value) => value.trim())
1178
+ .filter(Boolean)
1179
+ sendMutation({
1180
+ kind: "update-deck",
1181
+ deckId: activeDeckId,
1182
+ patch: {
1183
+ name: deckDraft.name,
1184
+ icon: deckDraft.icon || null,
1185
+ background: deckDraft.background || null,
1186
+ paginated: deckDraft.paginated,
1187
+ autoShow: deckDraft.autoShow,
1188
+ trigger:
1189
+ process.length || window.length
1190
+ ? {
1191
+ ...(process.length === 1
1192
+ ? { process_name: process[0] }
1193
+ : process.length
1194
+ ? { process_name: process }
1195
+ : {}),
1196
+ ...(window.length === 1
1197
+ ? { window_name: window[0] }
1198
+ : window.length
1199
+ ? { window_name: window }
1200
+ : {}),
1201
+ }
1202
+ : null,
1203
+ },
1204
+ })
1205
+ }}
1206
+ >
1207
+ Save deck
1208
+ </Button>
1209
+ </div>
1210
+ )}
1211
+ <div className="border-t border-neutral-800 pt-4">
1212
+ <div className="mb-3">
1213
+ <h3 className="text-xs font-semibold uppercase tracking-wider text-neutral-500">
1214
+ Decks
1215
+ </h3>
1216
+ </div>
1217
+ {creatingDeck && (
1218
+ <div className="mb-3 grid gap-2 rounded-lg border border-neutral-800 p-3">
1219
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1220
+ <Label className="min-w-0 break-words">ID</Label>
1221
+ <Input
1222
+ aria-label="New deck ID"
1223
+ value={newDeckId}
1224
+ onChange={(event) =>
1225
+ setNewDeckId(event.target.value)
1226
+ }
1227
+ />
1228
+ </TextField>
1229
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1230
+ <Label className="min-w-0 break-words">Name</Label>
1231
+ <Input
1232
+ aria-label="New deck name"
1233
+ value={newDeckName}
1234
+ onChange={(event) =>
1235
+ setNewDeckName(event.target.value)
1236
+ }
1237
+ />
1238
+ </TextField>
1239
+ <Button
1240
+ type="button"
1241
+ variant="primary"
1242
+ isDisabled={newDeckId.trim().length === 0}
1243
+ onPress={() => {
1244
+ const id = newDeckId.trim()
1245
+ const requestId = sendMutation({
1246
+ kind: "create-deck",
1247
+ deck: {
1248
+ id,
1249
+ ...(newDeckName.trim()
1250
+ ? { name: newDeckName.trim() }
1251
+ : {}),
1252
+ },
1253
+ })
1254
+ if (requestId !== null) {
1255
+ setCreatingDeck(false)
1256
+ setNewDeckId("")
1257
+ setNewDeckName("")
1258
+ }
1259
+ }}
1260
+ >
1261
+ Add deck
1262
+ </Button>
1263
+ </div>
1264
+ )}
1265
+ <div className="grid gap-1">
1266
+ {decks.map(([id, deck]) => (
1267
+ <Button
1268
+ key={id}
1269
+ type="button"
1270
+ size="sm"
1271
+ variant="tertiary"
1272
+ onPress={() => {
1273
+ changeDeck(id)
1274
+ }}
1275
+ aria-pressed={id === activeDeckId}
1276
+ className="min-h-10 h-auto justify-start rounded border border-separator px-3 py-2 text-left text-sm aria-pressed:border-primary aria-pressed:bg-surface-secondary"
1277
+ >
1278
+ <span className="block truncate">
1279
+ {deck.name ?? id}
1280
+ </span>
1281
+ <span className="block truncate text-xs text-neutral-500">
1282
+ #{id}
1283
+ </span>
1284
+ </Button>
1285
+ ))}
1286
+ {addonInventory?.addons
1287
+ .filter((addon) => !addon.internal)
1288
+ .flatMap((addon) =>
1289
+ addon.decks.filter((deck) => !deck.internal),
1290
+ )
1291
+ .filter(
1292
+ (deck) =>
1293
+ deck.generated === true &&
1294
+ deck.addonIndex !== undefined &&
1295
+ deck.overrideKey !== undefined,
1296
+ )
1297
+ .map((deck) => (
1298
+ <Button
1299
+ key={deck.id}
1300
+ type="button"
1301
+ size="sm"
1302
+ variant="tertiary"
1303
+ onPress={() => {
1304
+ sendMutation({
1305
+ kind: "set-addon-deck-override",
1306
+ addonIndex: deck.addonIndex,
1307
+ deckId: deck.overrideKey,
1308
+ override: {},
1309
+ })
1310
+ setMessage("Saving addon override…")
1311
+ }}
1312
+ className="min-h-10 h-auto justify-start rounded border border-separator px-3 py-2 text-left text-sm text-amber-300 hover:border-amber-400"
1313
+ >
1314
+ {deck.id}
1315
+ </Button>
1316
+ ))}
1317
+ </div>
1318
+ </div>
1319
+ </section>
1320
+ </div>
1321
+ )}
1322
+ {editionTab === "buttons" && (
1323
+ <Fieldset
1324
+ aria-labelledby="button-config-title"
1325
+ className={`grid min-h-0 gap-2 ${showButtonTypes ? "h-full grid-rows-[auto_minmax(0,1fr)]" : ""}`}
1326
+ >
1327
+ <Fieldset.Legend
1328
+ id="button-config-title"
1329
+ className="flex w-full items-center justify-between gap-2"
1330
+ >
1331
+ <span className="text-xs font-semibold uppercase tracking-wider text-muted">
1332
+ {pendingButton === null && selected === undefined
1333
+ ? showButtonTypes
1334
+ ? "New button"
1335
+ : "Button"
1336
+ : "Selected button"}
1337
+ </span>
1338
+ </Fieldset.Legend>
1339
+ {showButtonTypes && pendingButton === null && (
1340
+ <div className="flex min-h-0 min-w-0 items-stretch gap-2">
1341
+ <ButtonTypePicker
1342
+ options={addableButtonTypes}
1343
+ value={
1344
+ selected === undefined
1345
+ ? undefined
1346
+ : String(currentButtonType)
1347
+ }
1348
+ label={
1349
+ selected === undefined
1350
+ ? "Button type"
1351
+ : "Change button type"
1352
+ }
1353
+ onSelect={(option) => {
1354
+ if (selected === undefined) {
1355
+ const config = option.defaultConfig
1356
+ beginInsert(
1357
+ {
1358
+ type: option.type,
1359
+ config:
1360
+ typeof config === "object" &&
1361
+ config !== null &&
1362
+ !Array.isArray(config)
1363
+ ? config
1364
+ : {},
1365
+ },
1366
+ activeSelectedPosition ?? undefined,
1367
+ )
1368
+ } else {
1369
+ setButtonTypeOverride(option.type)
1370
+ }
1371
+ setShowButtonTypes(false)
1372
+ }}
1373
+ />
1374
+ <Button
1375
+ type="button"
1376
+ variant="tertiary"
1377
+ className="self-end"
1378
+ onPress={() => setShowButtonTypes(false)}
1379
+ >
1380
+ <CircleX aria-hidden="true" className="size-4" />
1381
+ Cancel
1382
+ </Button>
1383
+ </div>
1384
+ )}
1385
+ {!showButtonTypes &&
1386
+ (pendingButton !== null ? (
1387
+ <div className="space-y-3">
1388
+ <div className="flex flex-wrap gap-2">
1389
+ {pendingButton.type === "core:change-deck" && (
1390
+ <Button
1391
+ type="button"
1392
+ variant="secondary"
1393
+ onPress={() => {
1394
+ setNewPage(true)
1395
+ setPendingPosition(0)
1396
+ }}
1397
+ >
1398
+ Add new page
1399
+ </Button>
1400
+ )}
1401
+ </div>
1402
+ {newPage && (
1403
+ <Fieldset className="grid gap-2 rounded-lg border border-separator bg-surface-secondary p-2">
1404
+ <Fieldset.Legend className="px-1 text-sm font-medium">
1405
+ New page
1406
+ </Fieldset.Legend>
1407
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1408
+ <Label className="min-w-0 break-words">
1409
+ Page ID
1410
+ </Label>
1411
+ <Input
1412
+ aria-label="Page ID"
1413
+ value={newPageId}
1414
+ onChange={(event) =>
1415
+ setNewPageId(event.target.value)
1416
+ }
1417
+ />
1418
+ </TextField>
1419
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1420
+ <Label className="min-w-0 break-words">
1421
+ Page name
1422
+ </Label>
1423
+ <Input
1424
+ aria-label="Page name"
1425
+ value={newPageName}
1426
+ onChange={(event) =>
1427
+ setNewPageName(event.target.value)
1428
+ }
1429
+ />
1430
+ </TextField>
1431
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1432
+ <Label className="min-w-0 break-words">
1433
+ Icon source
1434
+ </Label>
1435
+ <Input
1436
+ aria-label="Icon source"
1437
+ placeholder="icon://layout-grid"
1438
+ value={newPageIcon}
1439
+ onChange={(event) =>
1440
+ setNewPageIcon(event.target.value)
1441
+ }
1442
+ />
1443
+ </TextField>
1444
+ <TextField className={INLINE_CONTROL_ROW_CLASS}>
1445
+ <Label className="min-w-0 break-words">
1446
+ Background
1447
+ </Label>
1448
+ <Input
1449
+ aria-label="Background"
1450
+ value={newPageBackground}
1451
+ onChange={(event) =>
1452
+ setNewPageBackground(event.target.value)
1453
+ }
1454
+ />
1455
+ </TextField>
1456
+ <Switch
1457
+ isSelected={newPagePaginated}
1458
+ onChange={setNewPagePaginated}
1459
+ className="w-full min-w-0"
1460
+ >
1461
+ <Switch.Content
1462
+ className={`${INLINE_CONTROL_ROW_CLASS} w-full cursor-pointer`}
1463
+ >
1464
+ <Label>Paginated page</Label>
1465
+ <Switch.Control>
1466
+ <Switch.Thumb />
1467
+ </Switch.Control>
1468
+ </Switch.Content>
1469
+ </Switch>
1470
+ </Fieldset>
1471
+ )}
1472
+ <ButtonAppearanceFields
1473
+ value={buttonAppearance}
1474
+ variants={state?.themeVariants ?? {}}
1475
+ ownedGestures={ownedGestures}
1476
+ positionControl={
1477
+ <PositionPicker
1478
+ mode="add"
1479
+ keyCount={device?.keyCount ?? 15}
1480
+ selected={pendingPosition}
1481
+ unset={positionUnset}
1482
+ disabledPositions={systemPositions}
1483
+ onHover={setHoveredPosition}
1484
+ onSelect={(position) => {
1485
+ if (systemPositions.includes(position)) return
1486
+ const index = positions.indexOf(position)
1487
+ if (index >= 0) setPositionToReplace(position)
1488
+ else stagePendingPosition(position)
1489
+ }}
1490
+ onUnset={() => {
1491
+ setPendingPosition(null)
1492
+ setPositionToReplace(null)
1493
+ setPositionUnset(true)
1494
+ setNewPage(false)
1495
+ }}
1496
+ onFirstAvailable={() => {
1497
+ const position = firstFreePosition()
1498
+ if (position === undefined) return
1499
+ stagePendingPosition(position)
1500
+ }}
1501
+ />
1502
+ }
1503
+ onChange={setButtonAppearance}
1504
+ />
1505
+ <ButtonConfigEditor
1506
+ key={`pending:${pendingButton.type as string}`}
1507
+ wsClient={wsClient}
1508
+ revision={state?.revision ?? 0}
1509
+ buttonType={String(pendingButton.type ?? "")}
1510
+ config={pendingButton.config ?? {}}
1511
+ schema={
1512
+ state?.buttonSchemas?.[
1513
+ String(pendingButton.type ?? "")
1514
+ ]
1515
+ }
1516
+ validation={validation}
1517
+ deckOptions={deckOptions}
1518
+ saveLabel="Add button"
1519
+ hideActions
1520
+ onDraftChange={setButtonDraft}
1521
+ onPreviewChange={setButtonPreviewDraft}
1522
+ onPendingAssetChange={(path, asset) =>
1523
+ chooseAsset(`config.${path}`, asset ?? undefined)
1524
+ }
1525
+ onCancel={() => {
1526
+ setPendingButton(null)
1527
+ setPendingPosition(null)
1528
+ setPositionToReplace(null)
1529
+ setSelectedPosition(null)
1530
+ setSelectedIndex(null)
1531
+ setButtonTypeOverride(null)
1532
+ }}
1533
+ onSave={addPending}
1534
+ />
1535
+ </div>
1536
+ ) : selected === undefined ? (
1537
+ <div className="space-y-3">
1538
+ <p className="py-3 text-sm text-muted">
1539
+ Select a button using its ⋮ menu.
1540
+ </p>
1541
+ {clipboard !== null && (
1542
+ <Button
1543
+ type="button"
1544
+ variant="secondary"
1545
+ onPress={() => add()}
1546
+ className="min-h-10"
1547
+ >
1548
+ Paste button
1549
+ </Button>
1550
+ )}
1551
+ </div>
1552
+ ) : (
1553
+ <div className="grid gap-2">
1554
+ {!selectedGenerated && (
1555
+ <ButtonAppearanceFields
1556
+ value={buttonAppearance}
1557
+ variants={state?.themeVariants ?? {}}
1558
+ ownedGestures={ownedGestures}
1559
+ positionControl={
1560
+ <PositionPicker
1561
+ mode="edit"
1562
+ keyCount={device?.keyCount ?? 15}
1563
+ selected={activeSelectedPosition}
1564
+ disabledPositions={systemPositions}
1565
+ onHover={setHoveredPosition}
1566
+ onSelect={moveSelectedToPosition}
1567
+ onFirstAvailable={() => {
1568
+ const position = firstFreePosition()
1569
+ if (position === undefined) return
1570
+ setSelectedPosition(position)
1571
+ setSelectionDeckId(activeDeckId)
1572
+ }}
1573
+ />
1574
+ }
1575
+ onChange={setButtonAppearance}
1576
+ />
1577
+ )}
1578
+ {!selectedGenerated && (
1579
+ <ButtonConfigEditor
1580
+ key={`${activeDeckId}:${selectedIndex}:${state?.revision ?? 0}`}
1581
+ wsClient={wsClient}
1582
+ revision={state?.revision ?? 0}
1583
+ buttonType={String(
1584
+ currentButtonType ?? selectedType,
1585
+ )}
1586
+ config={buttonEditorConfig}
1587
+ schema={
1588
+ state?.buttonSchemas?.[
1589
+ String(currentButtonType ?? selectedType)
1590
+ ]
1591
+ }
1592
+ validation={validation}
1593
+ deckOptions={deckOptions}
1594
+ hideActions
1595
+ onDraftChange={setButtonDraft}
1596
+ onPreviewChange={setButtonPreviewDraft}
1597
+ onPendingAssetChange={(path, asset) =>
1598
+ chooseAsset(`config.${path}`, asset ?? undefined)
1599
+ }
1600
+ onCancel={() => {
1601
+ setSelectedIndex(null)
1602
+ setSelectedPosition(null)
1603
+ setButtonTypeOverride(null)
1604
+ }}
1605
+ onSave={saveConfig}
1606
+ />
1607
+ )}
1608
+ </div>
1609
+ ))}
1610
+ </Fieldset>
1611
+ )}
1612
+ </Card.Content>
1613
+ {(pendingButton !== null ||
1614
+ (selected !== undefined && !selectedGenerated)) &&
1615
+ !showButtonTypes && (
1616
+ <Card.Footer className="mt-auto shrink-0 justify-end gap-2 border-t border-separator">
1617
+ <Button
1618
+ type="button"
1619
+ variant="tertiary"
1620
+ onPress={() => {
1621
+ setPendingButton(null)
1622
+ setPendingPosition(null)
1623
+ setPositionToReplace(null)
1624
+ setSelectedPosition(null)
1625
+ setSelectedIndex(null)
1626
+ setButtonTypeOverride(null)
1627
+ }}
1628
+ >
1629
+ <CircleX aria-hidden="true" className="size-4" />
1630
+ Cancel
1631
+ </Button>
1632
+ <Button
1633
+ type="button"
1634
+ variant="primary"
1635
+ isDisabled={buttonDraft === null}
1636
+ onPress={() => {
1637
+ if (buttonDraft === null) return
1638
+ if (pendingButton !== null) addPending(buttonDraft)
1639
+ else saveConfig(buttonDraft)
1640
+ }}
1641
+ >
1642
+ <Check aria-hidden="true" className="size-4" />
1643
+ {pendingButton === null ? "Save button" : "Add button"}
1644
+ </Button>
1645
+ </Card.Footer>
1646
+ )}
1647
+ <Modal>
1648
+ {positionToReplace !== null && (
1649
+ <Modal.Backdrop
1650
+ isOpen
1651
+ onOpenChange={(isOpen) => {
1652
+ if (!isOpen) setPositionToReplace(null)
1653
+ }}
1654
+ >
1655
+ <Modal.Container placement="center" size="sm">
1656
+ <Modal.Dialog aria-label="Replace button position">
1657
+ <Modal.Header>
1658
+ <Modal.Heading>
1659
+ Replace key {positionToReplace + 1}?
1660
+ </Modal.Heading>
1661
+ </Modal.Header>
1662
+ <Modal.Body>
1663
+ <p>
1664
+ The button currently in this position will be replaced
1665
+ when you add this button.
1666
+ </p>
1667
+ </Modal.Body>
1668
+ <Modal.Footer>
1669
+ <Button
1670
+ type="button"
1671
+ variant="tertiary"
1672
+ onPress={() => setPositionToReplace(null)}
1673
+ >
1674
+ Cancel
1675
+ </Button>
1676
+ <Button
1677
+ type="button"
1678
+ variant="primary"
1679
+ onPress={() => {
1680
+ stagePendingPosition(positionToReplace)
1681
+ setPositionToReplace(null)
1682
+ }}
1683
+ >
1684
+ Replace key
1685
+ </Button>
1686
+ </Modal.Footer>
1687
+ </Modal.Dialog>
1688
+ </Modal.Container>
1689
+ </Modal.Backdrop>
1690
+ )}
1691
+ </Modal>
1692
+ </Card>
1693
+ </div>
1694
+ )}
1695
+ </section>
1696
+ )
1697
+ }