Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

NewCard.tsx

89 lines2.5 KB

1import { useRef } from 'react'
2import { invariant } from '../invariant'
3​
4import { ItemMutationFields } from '../types'
5import { useCreateItemMutation } from '../queries'
6import { itemSchema } from '../db/schema'
7import { SaveButton } from '~/components/SaveButton'
8import { CancelButton } from '~/components/CancelButton'
9​
10export function NewCard({
11 columnId,
12 boardId,
13 nextOrder,
14 onComplete,
15}: {
16 columnId: string
17 boardId: string
18 nextOrder: number
19 onComplete: () => void
20}) {
21 const textAreaRef = useRef<HTMLTextAreaElement>(null)
22 const buttonRef = useRef<HTMLButtonElement>(null)
23 const { mutate } = useCreateItemMutation()
24​
25 return (
26 <form
27 method="post"
28 className="px-2 py-1 border-t-2 border-b-2 border-transparent"
29 onSubmit={(event) => {
30 event.preventDefault()
31​
32 const formData = new FormData(event.currentTarget)
33 const id = crypto.randomUUID()
34 formData.set(ItemMutationFields.id.name, id)
35​
36 invariant(textAreaRef.current)
37 textAreaRef.current.value = ''
38​
39 mutate({
40 data: itemSchema.parse(Object.fromEntries(formData.entries())),
41 })
42 }}
43 onBlur={(event) => {
44 if (!event.currentTarget.contains(event.relatedTarget)) {
45 onComplete()
46 }
47 }}
48 >
49 <input type="hidden" name="boardId" value={boardId} />
50 <input
51 type="hidden"
52 name={ItemMutationFields.columnId.name}
53 value={columnId}
54 />
55 <input
56 type="hidden"
57 name={ItemMutationFields.order.name}
58 value={nextOrder}
59 />
60​
61 <textarea
62 autoFocus
63 required
64 ref={textAreaRef}
65 name={ItemMutationFields.title.name}
66 placeholder="Enter a title for this card"
67 className="outline-hidden shadow-sm text-sm rounded-lg w-full py-1 px-2 resize-none placeholder:text-sm placeholder:text-slate-500 h-14"
68 onKeyDown={(event) => {
69 if (event.key === 'Enter') {
70 event.preventDefault()
71 invariant(buttonRef.current, 'expected button ref')
72 buttonRef.current.click()
73 }
74 if (event.key === 'Escape') {
75 onComplete()
76 }
77 }}
78 onChange={(event) => {
79 const el = event.currentTarget
80 el.style.height = el.scrollHeight + 'px'
81 }}
82 />
83 <div className="flex justify-between">
84 <SaveButton ref={buttonRef}>Save Card</SaveButton>
85 <CancelButton onClick={onComplete}>Cancel</CancelButton>
86 </div>
87 </form>
88 )