Keep input focused and keyboard open after adding tasks

- Added useRef to manage input focus directly
- Added useEffect to auto-focus when form becomes visible
- Refocus input after successful task creation with setTimeout
- Modified handleBlur to preserve focus when keeping form open
- Provides seamless continuous task input experience on mobile
This commit is contained in:
2025-12-14 00:59:48 +00:00
parent 466bce862e
commit 37955f95ab

View File

@@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useState, useRef, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { createItem } from '@/lib/actions'
import { Plus } from 'lucide-react'
@@ -19,6 +19,19 @@ export default function InlineItemCreate({ listId }: InlineItemCreateProps) {
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState('')
const [keepFormOpen, setKeepFormOpen] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
// Focus input when form becomes visible
useEffect(() => {
if ((isCreating || keepFormOpen) && inputRef.current) {
// Small delay to ensure the input is rendered
setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus()
}
}, 50)
}
}, [isCreating, keepFormOpen])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -49,6 +62,13 @@ export default function InlineItemCreate({ listId }: InlineItemCreateProps) {
// The revalidatePath in createItem will refresh the data
// but we'll keep the form open due to keepFormOpen state
// Refocus the input after a short delay to keep keyboard open
setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus()
}
}, 100)
} catch (error) {
console.error('Error creating item:', error)
const errorMessage = error instanceof Error ? error.message : 'Failed to add task'
@@ -77,9 +97,13 @@ export default function InlineItemCreate({ listId }: InlineItemCreateProps) {
}
}
const handleBlur = () => {
// Force viewport reset on iOS Safari
window.scrollTo(0, 0)
const handleBlur = (e: React.FocusEvent) => {
// Only handle blur if we're not keeping the form open
// This prevents the keyboard from closing when we want it to stay open
if (!keepFormOpen) {
// Force viewport reset on iOS Safari
window.scrollTo(0, 0)
}
}
if (!isCreating && !keepFormOpen) {
@@ -98,6 +122,7 @@ export default function InlineItemCreate({ listId }: InlineItemCreateProps) {
<form onSubmit={handleSubmit} className="bg-white border-2 border-blue-400 rounded-lg p-4 sm:p-5 shadow-sm">
<div className="mb-3 sm:mb-4">
<input
ref={inputRef}
type="text"
value={title}
onChange={(e) => {