live hotkey capture

This commit is contained in:
2026-05-12 00:08:24 +03:00
parent 14d02cdad4
commit 7a821f54fc
3 changed files with 144 additions and 45 deletions
+125
View File
@@ -0,0 +1,125 @@
<script lang="ts">
let {
value = $bindable(),
placeholder = "click to assign",
}: {
value: string | null
placeholder?: string
} = $props()
let capturing: boolean = $state(false)
let buttonEl: HTMLButtonElement | null = $state(null)
const MODIFIER_KEYS = new Set(["Control", "Shift", "Alt", "Meta", "ControlLeft", "ControlRight"])
function startCapture() {
capturing = true
buttonEl?.focus()
}
function handleKeydown(e: KeyboardEvent) {
if (!capturing) return
e.preventDefault()
e.stopPropagation()
if (e.key === "Escape") {
capturing = false
buttonEl?.blur()
return
}
if (MODIFIER_KEYS.has(e.key)) {
return
}
const parts: string[] = []
if (e.ctrlKey) parts.push("Ctrl")
if (e.altKey) parts.push("Alt")
if (e.shiftKey) parts.push("Shift")
if (e.metaKey) parts.push("Meta")
let key = e.key
if (key === " ") key = "Space"
else if (key.length === 1) key = key.toUpperCase()
parts.push(key)
value = parts.join("+")
capturing = false
buttonEl?.blur()
}
function handleBlur() {
capturing = false
}
function clear(e: MouseEvent) {
e.stopPropagation()
value = null
capturing = false
}
</script>
<div class="row">
<button
bind:this={buttonEl}
class:capturing
onclick={startCapture}
onkeydown={handleKeydown}
onblur={handleBlur}
type="button"
>
{#if capturing}
press a combo (Esc to cancel)
{:else if value}
{value}
{:else}
{placeholder}
{/if}
</button>
{#if value && !capturing}
<button class="clear" onclick={clear} type="button" title="clear">×</button>
{/if}
</div>
<style>
.row {
display: flex;
gap: 0.4rem;
align-items: stretch;
}
button {
font: inherit;
padding: 0.45rem 0.7rem;
border: 1px solid #444;
background: #222;
color: inherit;
border-radius: 4px;
cursor: pointer;
text-align: left;
flex: 1;
}
button:hover {
border-color: #888;
}
button.capturing {
border-color: #4a8;
background: #1a2a24;
color: #4a8;
outline: none;
}
button:focus {
outline: none;
border-color: #4a8;
}
button.clear {
flex: 0 0 auto;
padding: 0.45rem 0.7rem;
color: #888;
background: transparent;
border-color: #2a2a2a;
}
button.clear:hover {
color: #ec9a9a;
border-color: #ec9a9a;
}
</style>