Skip to content

Commit 9243855

Browse files
committed
task input autofocus
1 parent ac3cd31 commit 9243855

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/lib/components/AddTask.svelte

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,17 @@
77
disabled = false,
88
loading = false,
99
show = false,
10-
onsubmit,
11-
oninput,
10+
onsubmit = undefined,
11+
oninput = undefined,
1212
} = $props()
1313
14+
let inputElement
15+
16+
// Expose focus method to parent
17+
export function focus() {
18+
inputElement?.focus()
19+
}
20+
1421
const handleSubmit = (event) => {
1522
event.preventDefault()
1623
onsubmit?.(event)
@@ -88,6 +95,7 @@
8895
{/if}
8996
</div>
9097
<input
98+
bind:this={inputElement}
9199
class="add-task-input"
92100
type="text"
93101
bind:value

src/lib/components/Tasks.svelte

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
let newTaskContent = $state('')
2323
let addingTask = $state(false)
2424
let togglingTasks = $state(new Set())
25+
let addTaskComponent = $state()
2526
2627
// Derived project match
2728
let parsedProject = $derived(
@@ -83,6 +84,28 @@
8384
}
8485
}
8586
87+
function handleGlobalKeydown(event) {
88+
// Only auto-focus if:
89+
// 1. No input, textarea, or contenteditable element is currently focused
90+
// 2. The key is a printable character (not a modifier or special key)
91+
const activeElement = document.activeElement
92+
const isInputFocused =
93+
activeElement?.tagName === 'INPUT' ||
94+
activeElement?.tagName === 'TEXTAREA' ||
95+
(activeElement instanceof HTMLElement && activeElement.isContentEditable)
96+
97+
if (
98+
addTaskComponent &&
99+
!isInputFocused &&
100+
event.key.length === 1 && // Printable character
101+
!event.ctrlKey &&
102+
!event.metaKey &&
103+
!event.altKey
104+
) {
105+
addTaskComponent.focus()
106+
}
107+
}
108+
86109
$effect(() => {
87110
const backend = settings.taskBackend
88111
const token = settings.todoistApiToken
@@ -334,10 +357,12 @@
334357
onMount(() => {
335358
initializeAPI(settings.taskBackend, settings.todoistApiToken)
336359
document.addEventListener('visibilitychange', handleVisibilityChange)
360+
document.addEventListener('keydown', handleGlobalKeydown)
337361
})
338362
339363
onDestroy(() => {
340364
document.removeEventListener('visibilitychange', handleVisibilityChange)
365+
document.removeEventListener('keydown', handleGlobalKeydown)
341366
})
342367
</script>
343368
@@ -379,6 +404,7 @@
379404
</span>
380405
{/if}
381406
<AddTask
407+
bind:this={addTaskComponent}
382408
bind:value={newTaskContent}
383409
bind:parsed={parsedDate}
384410
{parsedProject}

0 commit comments

Comments
 (0)