subman-nextjs/src/app/ui/tables/inputs/textInput.tsx

104 lines
3.0 KiB
TypeScript
Raw Normal View History

2024-07-02 20:52:10 +00:00
"use client"
import { Input } from "@/components/ui/input";
import { CellContext } from "@tanstack/react-table";
import { updateField } from "app/lib/update";
import { useState } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@/components/ui/use-toast";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
2024-07-24 20:41:46 +00:00
import TitleContainer from "app/ui/titleContainer";
2024-07-02 20:52:10 +00:00
export function TextInputCell(props: CellContext<any, any>) {
const [isActive, setIsActive] = useState(false)
const table = props.table.options.meta.tableName
const id = props.row.original.id
const column = props.column.id
const pathname = props.table.options.meta.pathname
2024-07-02 20:52:10 +00:00
const value = props.cell.getValue()
const formSchema = props.column.columnDef.meta.formSchema.pick({ [column]: true })
2024-07-02 20:52:10 +00:00
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
[column]: props.cell.getValue()
},
})
2024-07-02 21:01:26 +00:00
async function onSubmit(value: z.infer<typeof formSchema>) {
2024-07-02 20:52:10 +00:00
toast({
title: "You submitted the following values:",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(value, null, 2)}</code>
</pre>
),
})
2024-07-02 21:01:26 +00:00
const res = await updateField({
id,
table,
2024-07-23 15:40:35 +00:00
datum: value[column],
column,
pathname
})
setIsActive(false)
}
2024-07-02 20:52:10 +00:00
function onErrors(errors) {
toast({
title: "You have errors",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(errors, null, 2)}</code>
</pre>
),
})
console.log(JSON.stringify(errors))
}
return (
2024-07-02 20:52:10 +00:00
<div
onDoubleClick={() => setIsActive(prev => !prev)}
2024-07-23 15:40:35 +00:00
className="w-full h-fit flex items-center justify-left"
2024-07-02 20:52:10 +00:00
tabIndex={0}
onKeyDown={e => {
2024-07-02 21:01:26 +00:00
if (e.code === "Enter" && !isActive) {
2024-07-02 20:52:10 +00:00
e.preventDefault()
setIsActive(true)
}
}}
>
{isActive ?
2024-07-02 20:52:10 +00:00
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)}
>
<FormField
control={form.control}
name={column}
render={({ field }) => (
<FormItem
onBlur={() => setIsActive(false)}
>
<FormControl
>
<Input
className="w-full"
2024-07-02 20:52:10 +00:00
type="text"
autoFocus={true}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
2024-07-24 20:41:46 +00:00
: <TitleContainer>{props.cell.getValue()}</TitleContainer>
}
2024-07-02 20:52:10 +00:00
</div >
)
}