Compare commits

...

41 Commits

Author SHA1 Message Date
andrzej 9950814ca6 improve title styling 2024-08-06 12:03:21 +02:00
andrzej 71f5a44c8e give each genrePicker cell a unique form id 2024-07-24 22:04:30 +02:00
andrzej cd90c92c6d improve genre picker cell 2024-07-24 17:24:04 +02:00
andrzej 055b3c254d fix missing keys 2024-07-24 17:23:42 +02:00
andrzej 79e3403902 implement genre picker cell (janky) 2024-07-23 17:40:35 +02:00
andrzej 41951a2ac6 move edit submission dialog to context menu 2024-07-21 19:14:20 +02:00
andrzej 0fa28a46eb edit submission, fix client side data validation 2024-07-20 14:07:13 +02:00
andrzej 6ee4128c85 edit submission functionality (partial) 2024-07-20 11:52:19 +02:00
andrzej aec413ba7a rearrange sub cols 2024-07-04 18:31:22 +02:00
andrzej 57cc55f414 delete unused imports 2024-07-03 00:41:20 +02:00
andrzej bc244497cd make inputs work with Enter 2024-07-02 23:01:26 +02:00
andrzej 29ab837aca fix added space 2024-07-02 22:52:10 +02:00
andrzej 1bad3ba5f8 Revert "make form input work with number and string"
This reverts commit 2294d0c0b0.
2024-07-02 22:16:17 +02:00
andrzej 2294d0c0b0 make form input work with number and string 2024-07-02 19:49:00 +02:00
andrzej 2e1409cf46 make fields open with space (to avoid conflicts) 2024-07-02 17:18:23 +02:00
andrzej f3dbd2cb9e fix enter key buy (partially) 2024-07-02 17:11:30 +02:00
andrzej 5206e415ed implement number input data validation (basic functionality) 2024-07-01 17:23:48 +02:00
andrzej fe9878cb7a implement inline number input 2024-06-30 23:28:05 +02:00
andrzej b6a56fca2b make update function concise/flexible 2024-06-30 23:21:48 +02:00
andrzej 8c4b9d27f2 improve tab nav 2024-06-30 20:28:02 +02:00
andrzej 5ea7a61915 add get method 2024-06-30 20:15:57 +02:00
andrzej 7c6f06e194 add open handler 2024-06-30 20:15:30 +02:00
andrzej 540413173c remove unneccessary buttons 2024-06-30 17:42:33 +02:00
andrzej 330226ecd6 implement inline text input 2024-06-30 17:36:44 +02:00
andrzej 23584a0a50 select checkboxes 2024-06-30 14:22:35 +02:00
andrzej 8ad3583c4e begin implementation of edit feature 2024-06-29 21:38:21 +02:00
andrzej c6496130e3 add deselect option to context menu 2024-06-29 16:26:46 +02:00
andrzej 97a537f5a2 fix multi-delete 2024-06-27 23:12:53 +02:00
andrzej 1fca1a2b81 partially implement multi-delete button 2024-06-27 16:49:56 +02:00
andrzej 4aa7194427 enable row selection 2024-06-27 16:08:14 +02:00
andrzej f163de99c8 add multi delete function 2024-06-27 16:08:03 +02:00
andrzej 10408f604a fix layout for smaller (laptop) screens 2024-06-27 15:35:48 +02:00
andrzej ee2a7c4cbf context menu -- keyboard navigation 2024-06-27 12:44:31 +02:00
andrzej 06fb2831ef context menu initial import 2024-06-26 22:52:33 +02:00
andrzej 5b919db59b neaten labels, capitalizations 2024-06-26 21:41:52 +02:00
andrzej 06b69b5ce7 fix focus issues on nested form items
now aria compliant!
2024-06-26 21:40:03 +02:00
andrzej 54a001183a implement basic create submission popover functionality 2024-06-26 19:55:18 +02:00
andrzej d210b13bde implement create pubs popup 2024-06-26 19:33:12 +02:00
andrzej 45af32d091 extrapolate genre picker 2024-06-26 18:21:06 +02:00
andrzej 0c39838f6a add createStoryDialog 2024-06-26 18:19:09 +02:00
andrzej 788051fa10 extrapolate create function 2024-06-26 18:18:44 +02:00
42 changed files with 6120 additions and 2474 deletions

6836
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@
"@hookform/resolvers": "^3.6.0", "@hookform/resolvers": "^3.6.0",
"@prisma/client": "^5.15.0", "@prisma/client": "^5.15.0",
"@radix-ui/react-checkbox": "^1.0.4", "@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-context-menu": "^2.2.1",
"@radix-ui/react-dialog": "^1.1.0", "@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-dropdown-menu": "^2.0.6", "@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-icons": "^1.3.0",
@ -48,5 +49,9 @@
"prisma": "^5.15.0", "prisma": "^5.15.0",
"tailwindcss": "^3.4.4", "tailwindcss": "^3.4.4",
"typescript": "^5" "typescript": "^5"
},
"overrides": {
"@radix-ui/react-dismissable-layer": "^1.0.5",
"@radix-ui/react-focus-scope": "^1.0.4"
} }
} }

Binary file not shown.

View File

@ -0,0 +1,200 @@
"use client"
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
const ContextMenuTrigger = ContextMenuPrimitive.Trigger
const ContextMenuGroup = ContextMenuPrimitive.Group
const ContextMenuPortal = ContextMenuPrimitive.Portal
const ContextMenuSub = ContextMenuPrimitive.Sub
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
const ContextMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}

View File

@ -31,15 +31,15 @@ export default function RootLayout({
disableTransitionOnChange disableTransitionOnChange
> >
<div id="layout-container" className="p-4 w-screen h-screen mt-6 flex justify-center"> <div id="layout-container" className="p-4 w-screen h-screen mt-6 flex justify-center">
<div className="grid grid-cols-12 w-5/6"> <div className="w-5/6 flex">
<div id="sidebar" className="col-start-1 col-end-3 h-5/6 flex flex-col"> <header className=""> <div id="sidebar" className="h-5/6 flex flex-col"> <header className="">
<h1 className="font-black text-4xl text-primary-foreground bg-primary antialiased w-full p-2 rounded-tl-3xl pl-6">SubMan</h1> <h1 className="font-black text-4xl text-primary-foreground bg-primary antialiased w-full p-2 rounded-tl-3xl pl-6 pr-4">SubMan</h1>
<p className="mt-2 mx-1 text-sm antialiased">The self-hosted literary submission tracker.</p> <p className="mt-2 mx-1 text-sm antialiased w-40">The self-hosted literary submission tracker.</p>
</header> </header>
<Navlinks className="mt-6" /> <Navlinks className="mt-6" />
<footer className="mt-auto"><ModeToggle /></footer> <footer className="mt-auto"><ModeToggle /></footer>
</div> </div>
<div className="col-start-3 col-span-full"> <div className="flex justify-center w-full">
{children} {children}
</div> </div>
</div> </div>

59
src/app/lib/create.ts Normal file
View File

@ -0,0 +1,59 @@
"use server"
import { Genre, Story } from "@prisma/client"
import prisma from "./db"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
export async function createStory(data: Story & { genres: number[] }) {
"use server"
const genresArray = data.genres.map((e) => { return { id: e } })
const res = await prisma.story.create({
data: {
title: data.title,
word_count: data.word_count,
}
})
console.log(res)
const genresRes = await prisma.story.update({
where: { id: res.id },
data: {
genres: { set: genresArray }
}
})
console.log(genresRes)
revalidatePath("/story")
redirect("/story")
}
export async function createPub(data) {
"use server"
const genresArray = data.genres.map(e => { return { id: e } })
const res = await prisma.pub.create({
data: {
title: data.title,
link: data.link,
query_after_days: data.query_after_days
}
})
console.log(res)
const genresRes = await prisma.pub.update({
where: { id: res.id },
data:
{ genres: { set: genresArray } }
})
console.log(genresRes)
revalidatePath("/publication")
redirect("/publication")
}
export async function createSub(data) {
"use server"
const res = await prisma.sub.create({ data })
console.log(res)
revalidatePath("/submission")
redirect("/submission")
}

View File

@ -2,29 +2,32 @@
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import prisma from "./db"; import prisma from "./db";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { Pathname } from "app/types";
export async function deleteStory(id: number) { const tableMap = {
const res = await prisma.story.delete({ "/story": "story",
where: { id } "/publication": "pub",
}) "/submission": "sub"
console.log(`deleted: ${res}`)
revalidatePath("/story")
redirect("/story")
}
export async function deletePub(id: number) {
const res = await prisma.pub.delete({
where: { id }
})
console.log(`deleted: ${res}`)
revalidatePath("/publication")
redirect("/publication")
} }
export async function deleteSub(id: number) { export async function deleteRecord(id: number, pathname: Pathname) {
const res = await prisma.sub.delete({ const table = tableMap[pathname]
where: { id } const res = await prisma[table].delete({ where: { id } })
}) console.log(`deleted from ${table}: ${res.id}`)
console.log(`deleted: ${res}`) console.log("revalidating: " + pathname)
revalidatePath("/submission") revalidatePath(pathname)
redirect("/submission") redirect(pathname)
} }
export async function deleteRecords(ids: number[], pathname: "/story" | "/publication" | "/submission") {
const table = tableMap[pathname]
ids.forEach(async (id) => {
const res = await prisma[table].delete({
where: { id }
})
console.log(`deleted from ${table}: ${res.id}`)
})
revalidatePath(pathname)
redirect(pathname)
}

15
src/app/lib/edit.ts Normal file
View File

@ -0,0 +1,15 @@
"use server"
import prisma from "./db"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
import { SubForm } from "app/ui/forms/sub"
export async function editSubmission(data: SubForm) {
const res = await prisma.sub.update({
where: { id: data.id },
data
})
console.log(`updated ${data} to ${res}`)
revalidatePath("/submission")
redirect("/submission")
}

View File

@ -13,6 +13,14 @@ export async function getStoriesWithGenres() {
) )
} }
export async function getStoriesWithGenresAndSubs() {
return prisma.story.findMany({
include: {
genres: true,
subs: true
}
})
}
export async function getPubs() { export async function getPubs() {
return prisma.pub.findMany() return prisma.pub.findMany()

8
src/app/lib/nameMaps.ts Normal file
View File

@ -0,0 +1,8 @@
export function tableNameToItemName(tableName: string) {
const map = {
subs: "submission",
pubs: "publication",
story: "story"
}
return map[tableName]
}

8
src/app/lib/pluralize.ts Normal file
View File

@ -0,0 +1,8 @@
export default function pluralize(word: "story" | "publication" | "submission"): string {
const map = {
story: "stories",
publication: "publications",
submission: "submissions"
}
return map[word]
}

30
src/app/lib/update.ts Normal file
View File

@ -0,0 +1,30 @@
"use server"
import { Genre } from "@prisma/client"
import prisma from "./db"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
export async function updateField({ datum, table, column, id, pathname }: { datum?: string | number | Genre[], table: string, column: string, id: number, pathname: string }) {
const res = await prisma[table].update({
where: { id },
data: {
[column]: datum
}
})
console.log(`updated record in ${table}: ${JSON.stringify(res)}`)
revalidatePath(pathname)
redirect(pathname)
}
export async function updateGenres({ genres, table, id, pathname }: { genres: { id: number }[], table: string, id: number, pathname: string }) {
const res = await prisma[table].update({
where: { id },
data: {
genres: { set: genres }
}
})
console.log(`updated record in ${table}: ${JSON.stringify(res)}`)
revalidatePath(pathname)
redirect(pathname)
}

View File

@ -1,28 +1,20 @@
"use client" "use client"
import { ColumnDef, createColumnHelper } from "@tanstack/react-table" import { ColumnDef, createColumnHelper } from "@tanstack/react-table"
import { ArrowUpDown, MoreHorizontal } from "lucide-react" import { ArrowUpDown } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge"
import { Trash2, Search } from "lucide-react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { deletePub } from "app/lib/del"
import Link from "next/link"
import { PubsWithGenres } from "./page" import { PubsWithGenres } from "./page"
import { DialogClose } from "@radix-ui/react-dialog" import { TextInputCell } from "app/ui/tables/inputs/textInput"
import { actions } from "app/ui/tables/actions" import { selectCol } from "app/ui/tables/selectColumn"
import NumberInputCell from "app/ui/tables/inputs/numberInput"
import { formSchema } from "app/ui/forms/pub"
import GenrePickerInputCell from "app/ui/tables/inputs/genrePickerInput"
const columnHelper = createColumnHelper<PubsWithGenres>() const columnHelper = createColumnHelper<PubsWithGenres>()
export const columns: ColumnDef<PubsWithGenres>[] = [ export const columns: ColumnDef<PubsWithGenres>[] = [
selectCol,
{ {
accessorKey: "title", accessorKey: "title",
header: ({ column }) => { header: ({ column }) => {
@ -36,30 +28,32 @@ export const columns: ColumnDef<PubsWithGenres>[] = [
</Button> </Button>
) )
}, },
cell: TextInputCell,
meta: { formSchema }
}, },
{ {
accessorKey: "link", accessorKey: "link",
header: "Link", header: "Link",
cell: TextInputCell,
meta: { formSchema }
}, },
columnHelper.accessor("genres", { columnHelper.accessor("genres", {
cell: props => { cell: GenrePickerInputCell,
const genres = props.getValue()
.map(e => <Badge>{e.name}</Badge>)
return genres
},
filterFn: "arrIncludes" filterFn: "arrIncludes"
//TODO - write custom filter function, to account for an array of objects //TODO - write custom filter function, to account for an array of objects
}), }),
{ {
accessorKey: "query_after_days", accessorKey: "query_after_days",
header: "Query After (days)" header: "Query After (days)",
cell: NumberInputCell,
meta: {
step: 10,
formSchema
},
}, },
actions({ pathname: "/publication", deleteFn: deletePub })
] ]

View File

@ -0,0 +1,30 @@
"use client"
import { Dialog, DialogHeader, DialogTrigger, DialogContent, DialogClose, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ComponentProps } from "react";
import { Genre } from "@prisma/client";
import { createPub } from "app/lib/create";
import PubForm from "app/ui/forms/pub";
export default function CreatePubDialog({ genres }: ComponentProps<"div"> & { genres: Genre[] }) {
return (
<Dialog>
<DialogTrigger asChild>
<Button>Create new publication</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>New publication</DialogTitle>
<DialogDescription>Create an entry for a new publication i.e. a place you intend to submit stories to.</DialogDescription>
</DialogHeader>
<PubForm createPub={createPub} genres={genres} />
<DialogFooter>
<Button form="pubform">Submit</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@ -1,40 +0,0 @@
import PubForm from "app/ui/forms/pub";
import { getGenres } from "app/lib/get";
import prisma from "app/lib/db";
import { CreateContainer, CreateContainerContent, CreateContainerDescription, CreateContainerHeader } from "app/ui/createContainer";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
export default async function Page() {
async function createPub(data) {
"use server"
const genresArray = data.genres.map(e => { return { id: e } })
const res = await prisma.pub.create({
data: {
title: data.title,
link: data.link,
query_after_days: data.query_after_days
}
})
console.log(res)
const genresRes = await prisma.pub.update({
where: { id: res.id },
data:
{ genres: { set: genresArray } }
})
console.log(genresRes)
revalidatePath("/publication")
redirect("/publication")
}
const genres = await getGenres()
return (
<CreateContainer>
<CreateContainerHeader>New publication</CreateContainerHeader>
<CreateContainerContent>
<CreateContainerDescription>
Create a new entry for a publication i.e. a place you intend to submit to.
</CreateContainerDescription>
<PubForm genres={genres} createPub={createPub} className="mt-6" />
</CreateContainerContent>
</CreateContainer>
)
}

View File

@ -1,15 +1,21 @@
import { Genre, Pub } from "@prisma/client"; import { Genre, Pub } from "@prisma/client";
import { getPubsWithGenres } from "app/lib/get"; import { getGenres, getPubsWithGenres } from "app/lib/get";
import { columns } from "./columns"; import { columns } from "./columns";
import { DataTable } from "app/ui/tables/data-table"; import { DataTable } from "app/ui/tables/data-table";
import CreatePubDialog from "./create";
export type PubsWithGenres = Pub & { genres: Array<Genre> } export type PubsWithGenres = Pub & { genres: Array<Genre> }
export default async function Page() { export default async function Page() {
const genres = await getGenres()
const pubs = await getPubsWithGenres() const pubs = await getPubsWithGenres()
return ( return (
<div className="container mx-auto"> <div className="container mx-auto">
<DataTable data={pubs} columns={columns} type="publication" /> <DataTable data={pubs} columns={columns} tableName="pubs" genres={genres}>
<CreatePubDialog genres={genres} />
</DataTable>
</div> </div>
) )

View File

@ -31,7 +31,7 @@ export default async function Page({ params }: { params: { id: string } }) {
<PageHeader>{story?.title ?? ""}</PageHeader> <PageHeader>{story?.title ?? ""}</PageHeader>
<GenreBadges genres={story.genres} className="my-6" /> <GenreBadges genres={story.genres} className="my-6" />
<PageSubHeader>Submissions:</PageSubHeader> <PageSubHeader>Submissions:</PageSubHeader>
<DataTable columns={columns} data={storySubs} type="submission" /> <DataTable columns={columns} data={storySubs} tableName="subs" />
</div> </div>

View File

@ -3,14 +3,16 @@ import { ColumnDef, createColumnHelper } from "@tanstack/react-table"
import { StoryWithGenres } from "./page" import { StoryWithGenres } from "./page"
import { ArrowUpDown } from "lucide-react" import { ArrowUpDown } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { deleteStory } from "app/lib/del"
import GenreBadges from "app/ui/genreBadges" import GenreBadges from "app/ui/genreBadges"
import { actions } from "app/ui/tables/actions" import { selectCol } from "app/ui/tables/selectColumn"
import NumberInputCell from "app/ui/tables/inputs/numberInput"
import { formSchema } from "app/ui/forms/story"
import { TextInputCell } from "app/ui/tables/inputs/textInput"
import GenrePickerInputCell from "app/ui/tables/inputs/genrePickerInput"
const columnHelper = createColumnHelper<StoryWithGenres>() const columnHelper = createColumnHelper<StoryWithGenres>()
export const columns: ColumnDef<StoryWithGenres>[] = [ export const columns: ColumnDef<StoryWithGenres>[] = [
selectCol,
{ {
accessorKey: "title", accessorKey: "title",
header: ({ column }) => { header: ({ column }) => {
@ -24,6 +26,8 @@ export const columns: ColumnDef<StoryWithGenres>[] = [
</Button> </Button>
) )
}, },
cell: TextInputCell,
meta: { formSchema }
}, },
{ {
@ -39,17 +43,18 @@ export const columns: ColumnDef<StoryWithGenres>[] = [
</Button> </Button>
) )
}, },
enableColumnFilter: false enableColumnFilter: false,
cell: NumberInputCell,
meta: {
step: 50,
formSchema
}
}, },
columnHelper.accessor("genres", { columnHelper.accessor("genres", {
cell: props => { cell: GenrePickerInputCell,
const genres = props.getValue() filterFn: "arrIncludes",
return <GenreBadges genres={genres} /> meta: {}
},
filterFn: "arrIncludes"
//TODO - write custom filter function, to account for an array of objects
}), }),
//this is a function so that the actions column can be uniform across tables
actions({ pathname: "/story", deleteFn: deleteStory })
] ]

31
src/app/story/create.tsx Normal file
View File

@ -0,0 +1,31 @@
"use client"
import { createStory } from "app/lib/create"
import { Dialog, DialogHeader, DialogTrigger, DialogContent, DialogClose, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ComponentProps } from "react";
import { Genre } from "@prisma/client";
import StoryForm from "app/ui/forms/story";
export default function CreateStoryDialog({ genres }: ComponentProps<"div"> & { genres: Genre[] }) {
return (
<Dialog>
<DialogTrigger asChild>
<Button>Create new story</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>New story</DialogTitle>
<DialogDescription>Create an entry for a new story i.e. a thing you intend to submit for publication.</DialogDescription>
</DialogHeader>
<StoryForm createStory={createStory} genres={genres} existingData={null} />
<DialogFooter>
<Button form="storyform">Submit</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@ -1,16 +1,30 @@
import { Story } from "@prisma/client"; import { Story } from "@prisma/client";
import { DataTable } from "app/ui/tables/data-table"; import { DataTable } from "app/ui/tables/data-table";
import { columns } from "./columns"; import { columns } from "./columns";
import { getStoriesWithGenres } from "app/lib/get"; import { getGenres, getStoriesWithGenres, getPubsWithGenres } from "app/lib/get";
import { Genre } from "@prisma/client"; import { Genre } from "@prisma/client";
import CreateStoryDialog from "./create";
export type StoryWithGenres = Story & { genres: Array<Genre> } export type StoryWithGenres = Story & { genres: Array<Genre> }
export default async function Page() { export default async function Page() {
const stories: Array<StoryWithGenres> = await getStoriesWithGenres() const genres = await getGenres()
const storiesWithGenres: Array<StoryWithGenres> = await getStoriesWithGenres()
return ( return (
<div className="container mx-auto"> <div className="container mx-auto">
<DataTable columns={columns} data={stories} type="story" /> <DataTable columns={columns} data={storiesWithGenres} tableName="story"
genres={genres}
>
<CreateStoryDialog genres={genres} />
</DataTable>
</div> </div>
) )
} }

View File

@ -1,15 +1,37 @@
"use client" "use client"
import { ColumnDef, createColumnHelper } from "@tanstack/react-table" import { CellContext, ColumnDef, createColumnHelper } from "@tanstack/react-table"
import { ArrowUpDown } from "lucide-react" import { ArrowUpDown } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { deleteSub } from "app/lib/del"
import { SubComplete } from "./page" import { SubComplete } from "./page"
import { actions } from "app/ui/tables/actions" import { selectCol } from "app/ui/tables/selectColumn"
import TitleContainer from "app/ui/titleContainer"
const columnHelper = createColumnHelper<SubComplete>()
export const columns: ColumnDef<SubComplete>[] = [ export const columns: ColumnDef<SubComplete>[] = [
selectCol,
{
accessorFn: row => {
if (row.story) {
return row.story.title
}
return "RECORD DELETED"
},
id: "story",
header: "Story",
cell: (props: CellContext<any, any>) => (<TitleContainer>{props.getValue()}</TitleContainer>)
},
{
accessorFn: row => {
if (row.pub) {
return row.pub.title
}
return "RECORD DELETED"
},
id: "pub",
header: "Publication",
cell: (props: CellContext<any, any>) => (<TitleContainer>{props.getValue()}</TitleContainer>)
},
{ {
accessorFn: row => new Date(row.submitted), accessorFn: row => new Date(row.submitted),
id: "submitted", id: "submitted",
@ -26,7 +48,7 @@ export const columns: ColumnDef<SubComplete>[] = [
}, },
enableColumnFilter: false, enableColumnFilter: false,
sortingFn: "datetime", sortingFn: "datetime",
cell: props => { return props.getValue().toLocaleDateString() } cell: (props: CellContext<any, any>) => (<p className="w-full text-center">{props.getValue().toLocaleDateString()}</p>)
}, },
{ {
accessorFn: row => row.responded ? new Date(row.responded) : null, accessorFn: row => row.responded ? new Date(row.responded) : null,
@ -44,7 +66,7 @@ export const columns: ColumnDef<SubComplete>[] = [
}, },
enableColumnFilter: false, enableColumnFilter: false,
sortingFn: "datetime", sortingFn: "datetime",
cell: props => props.getValue() ? props.getValue().toLocaleDateString() : '-' cell: (props: CellContext<any, any>) => (<p className="w-full text-center">{props.getValue()?.toLocaleDateString()}</p>)
}, },
{ {
accessorFn: row => { accessorFn: row => {
@ -54,29 +76,9 @@ export const columns: ColumnDef<SubComplete>[] = [
return "RECORD DELETED" return "RECORD DELETED"
}, },
id: "response", id: "response",
header: "Response" header: "Response",
cell: (props: CellContext<any, any>) => (<p className="w-full text-center">{props.getValue()}</p>)
}, },
{
accessorFn: row => {
if (row.pub) {
return row.pub.title
}
return "RECORD DELETED"
},
id: "pub",
header: "Publication"
},
{
accessorFn: row => {
if (row.story) {
return row.story.title
}
return "RECORD DELETED"
},
id: "story",
header: "Story"
},
actions({ pathname: "/submission", deleteFn: deleteSub })
] ]

View File

@ -0,0 +1,41 @@
"use client"
import { createSub } from "app/lib/create"
import { Dialog, DialogHeader, DialogTrigger, DialogContent, DialogClose, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ComponentProps } from "react";
import { Pub, Response, Story } from "@prisma/client";
import SubmissionForm from "app/ui/forms/sub";
type CreateSubDefaults = {
subId?: number,
storyId: number,
pubId: number,
submitted: Date,
responded: Date,
respoonseId: number
}
export default function CreateSubmissionDialog({ stories, pubs, responses, defaults }: ComponentProps<"div"> & { stories: Story[], pubs: Pub[], responses: Response[], defaults?: CreateSubDefaults }) {
return (
<Dialog>
<DialogTrigger asChild>
<Button>Create new submission</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>New submission</DialogTitle>
<DialogDescription>Create an entry for a new story i.e. a thing you intend to submit for publication.</DialogDescription>
</DialogHeader>
<SubmissionForm createSub={createSub} pubs={pubs} responses={responses} stories={stories} defaults={defaults} />
<DialogFooter>
<DialogClose asChild>
</DialogClose>
<Button form="subform">Submit</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@ -0,0 +1,27 @@
"use client"
import { createSub } from "app/lib/create"
import { Dialog, DialogHeader, DialogTrigger, DialogContent, DialogClose, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ComponentProps } from "react";
import { Pub, Response, Story } from "@prisma/client";
import SubmissionForm, { SubForm } from "app/ui/forms/sub";
export default function EditSubmissionDialog({ stories, pubs, responses, defaults, children }: ComponentProps<"div"> & { stories: Story[], pubs: Pub[], responses: Response[], defaults: SubForm }) {
return (
<>
<DialogHeader>
<DialogTitle>Edit Submission</DialogTitle>
<DialogDescription>Change response status, edit dates etc</DialogDescription>
</DialogHeader>
<SubmissionForm pubs={pubs} responses={responses} stories={stories} defaults={defaults} />
<DialogFooter>
<DialogClose asChild>
</DialogClose>
<Button form="subform">Submit</Button>
</DialogFooter>
</>
)
}

View File

@ -1,7 +1,9 @@
import { getSubsComplete } from "app/lib/get" import { getGenres, getPubs, getResponses, getStories, getSubsComplete } from "app/lib/get"
import { DataTable } from "app/ui/tables/data-table" import { DataTable } from "app/ui/tables/data-table"
import { columns } from "./columns" import { columns } from "./columns"
import { Pub, Response, Story, Sub } from "@prisma/client" import { Pub, Response, Story, Sub } from "@prisma/client"
import CreateSubmissionDialog from "./create"
import { Trash2 } from "lucide-react"
export type SubComplete = Sub & { export type SubComplete = Sub & {
pub: Pub, pub: Pub,
@ -10,9 +12,24 @@ export type SubComplete = Sub & {
} }
export default async function Page() { export default async function Page() {
const subs: Array<SubComplete> = await getSubsComplete() const subs: Array<SubComplete> = await getSubsComplete()
const stories = await getStories()
const pubs = await getPubs()
const responses = await getResponses()
const genres = await getGenres()
return ( return (
<div className="container"> <div className="container">
<DataTable data={subs} columns={columns} type="submission" /> <DataTable data={subs} columns={columns} tableName="sub"
stories={stories}
pubs={pubs}
responses={responses}
genres={genres}
>
<CreateSubmissionDialog
stories={stories}
pubs={pubs}
responses={responses}
/>
</DataTable>
</div> </div>
) )
} }

View File

@ -706,22 +706,6 @@ body {
z-index: 100; z-index: 100;
} }
.col-span-full {
grid-column: 1 / -1;
}
.col-start-1 {
grid-column-start: 1;
}
.col-start-3 {
grid-column-start: 3;
}
.col-end-3 {
grid-column-end: 3;
}
.m-auto { .m-auto {
margin: auto; margin: auto;
} }
@ -926,6 +910,10 @@ body {
width: 1rem; width: 1rem;
} }
.w-40 {
width: 10rem;
}
.w-5\/6 { .w-5\/6 {
width: 83.333333%; width: 83.333333%;
} }
@ -1064,10 +1052,6 @@ body {
user-select: none; user-select: none;
} }
.grid-cols-12 {
grid-template-columns: repeat(12, minmax(0, 1fr));
}
.flex-row { .flex-row {
flex-direction: row; flex-direction: row;
} }
@ -1108,10 +1092,6 @@ body {
justify-content: space-between; justify-content: space-between;
} }
.justify-around {
justify-content: space-around;
}
.gap-1 { .gap-1 {
gap: 0.25rem; gap: 0.25rem;
} }
@ -1283,6 +1263,10 @@ body {
background-color: rgb(0 0 0 / 0.8); background-color: rgb(0 0 0 / 0.8);
} }
.bg-border {
background-color: hsl(var(--border));
}
.bg-card { .bg-card {
background-color: hsl(var(--card)); background-color: hsl(var(--card));
} }
@ -1427,6 +1411,10 @@ body {
padding-right: 0.5rem; padding-right: 0.5rem;
} }
.pr-4 {
padding-right: 1rem;
}
.pr-8 { .pr-8 {
padding-right: 2rem; padding-right: 2rem;
} }
@ -1679,6 +1667,20 @@ body {
} }
} }
.animate-in {
animation-name: enter;
animation-duration: 150ms;
--tw-enter-opacity: initial;
--tw-enter-scale: initial;
--tw-enter-rotate: initial;
--tw-enter-translate-x: initial;
--tw-enter-translate-y: initial;
}
.fade-in-80 {
--tw-enter-opacity: 0.8;
}
.duration-200 { .duration-200 {
animation-duration: 200ms; animation-duration: 200ms;
} }
@ -2156,6 +2158,10 @@ body {
color: hsl(var(--primary-foreground)); color: hsl(var(--primary-foreground));
} }
.data-\[state\=open\]\:text-accent-foreground[data-state=open] {
color: hsl(var(--accent-foreground));
}
.data-\[state\=open\]\:text-muted-foreground[data-state=open] { .data-\[state\=open\]\:text-muted-foreground[data-state=open] {
color: hsl(var(--muted-foreground)); color: hsl(var(--muted-foreground));
} }

1
src/app/types.ts Normal file
View File

@ -0,0 +1 @@
export type Pathname = "/story" | "/publication" | "/submission"

View File

@ -1,30 +0,0 @@
import { FormItem, FormControl, FormLabel } from "@/components/ui/form"
import { Checkbox } from "@/components/ui/checkbox"
export default function GenreCheckbox({ field, item }) {
return (
<FormItem
key={item.id}
className="flex flex-row items-start space-x-3 space-y-0"
>
<FormControl>
<Checkbox
checked={field.value?.includes(item.id)}
onCheckedChange={(checked) => {
return checked
? field.onChange([...field.value, item.id])
: field.onChange(
field.value?.filter(
(value) => value !== item.id
)
)
}}
/>
</FormControl>
<FormLabel className="text-sm font-normal">
{item.name}
</FormLabel>
</FormItem>
)
}

View File

@ -1,17 +0,0 @@
import { getGenres } from "app/lib/get"
import React from "react"
import { letterCase } from "app/lib/functions"
export default async function GenreCheckboxes() {
const genres = await getGenres()
const genreCheckboxes = genres.map(e => {
const label = letterCase(e.name)
return (<React.Fragment key={`fragment${e.name}`}>
<input type="checkbox" id={e.name} key={`genreCheckboxInput${e.id}`} />
<label htmlFor={e.name} key={`genreCheckboxLabel${e.id}`}>{label}</label>
</React.Fragment>
)
})
return <>{genreCheckboxes}</>
}

View File

@ -1 +0,0 @@

View File

@ -0,0 +1,85 @@
import { FormField, FormItem, FormLabel, FormMessage, FormControl } from "@/components/ui/form"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { cn } from "@/lib/utils"
import { ComponentProps } from "react"
import { Genre } from "@prisma/client"
import { UseFormReturn } from "react-hook-form"
export default function GenrePicker({ genres, form }: ComponentProps<"div"> & { genres: Genre[], form: UseFormReturn }) {
return (
<Popover modal={true}>
<FormField
control={form.control}
name="genres"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="h-5">Genres</FormLabel>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"min-w-fit max-w-full w-fit pl-3 text-left font-normal flex-wrap gap-y-1 h-fit min-h-10",
!field.value && "text-muted-foreground"
)}
>
{field.value.length !== 0 ? (
field.value.map((e, i) => (<Badge key={i}>{genres.find(f => e === f.id).name}</Badge>))
) : (
<p>Select</p>
)}
</Button>
</PopoverTrigger>
<PopoverContent align="start">
{genres.map((item) => (
< FormField
key={item.id}
control={form.control}
name="genres"
render={({ field }) => {
return (
<FormItem
key={item.id}
className="flex flex-row items-start space-x-3 space-y-0"
>
<FormControl>
<Checkbox
checked={field.value?.includes(item.id)}
onCheckedChange={(checked) => {
return checked
? field.onChange([...field.value, item.id])
: field.onChange(
field.value?.filter(
(value) => value !== item.id
)
)
}}
/>
</FormControl>
<FormLabel className="text-sm font-normal">
{item.name}
</FormLabel>
</FormItem>
)
}}
/>
))}
<Button variant="link" className="p-0" onClick={() => form.setValue("genres", [])}>Clear</Button>
</PopoverContent>
<FormMessage />
</FormItem>
)}
/>
</Popover>
)
}

View File

@ -1,27 +0,0 @@
import { FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { Popover, PopoverContent, PopoverTrigger } from "@radix-ui/react-popover"
import { Checkbox } from "@radix-ui/react-checkbox"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
export default function GenresTrigger({ value, genres }) {
return (
<>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"min-w-fit max-w-full w-fit pl-3 text-left font-normal flex-wrap gap-y-1 h-fit min-h-10",
!value && "text-muted-foreground"
)}
>
{value.length !== 0 ? (
value.map((e, i) => (<Badge>{genres.find(f => e === f.id).name}</Badge>))
) : (
<p>Select</p>
)}
</Button>
</PopoverTrigger>
</>
)
}

View File

@ -3,7 +3,6 @@
import { z } from "zod" import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { Button } from "@/components/ui/button"
import { import {
Form, Form,
FormControl, FormControl,
@ -16,17 +15,12 @@ import {
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { toast } from "@/components/ui/use-toast" import { toast } from "@/components/ui/use-toast"
import {
Popover,
PopoverContent,
} from "@/components/ui/popover"
import GenresTrigger from "./genresTrigger"
import GenreCheckbox from "./genreCheckbox"
import { randomPublicationTitle } from "app/lib/shortStoryTitleGenerator" import { randomPublicationTitle } from "app/lib/shortStoryTitleGenerator"
import { ComponentProps } from "react" import { ComponentProps } from "react"
import { Genre } from "@prisma/client" import { Genre } from "@prisma/client"
import GenrePicker from "./genrePicker"
const formSchema = z.object({ export const formSchema = z.object({
title: z.string().min(2).max(50), title: z.string().min(2).max(50),
link: z.string(), link: z.string(),
query_after_days: z.coerce.number().min(30), query_after_days: z.coerce.number().min(30),
@ -79,7 +73,7 @@ export default function PubForm({ genres, createPub, className }: ComponentProps
return ( return (
<div className={className}> <div className={className}>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8"> <form id="pubform" onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8">
<FormField <FormField
control={form.control} control={form.control}
name="title" name="title"
@ -109,35 +103,7 @@ export default function PubForm({ genres, createPub, className }: ComponentProps
/> />
<div className="inline-flex flex-wrap w-full gap-x-16 gap-y-8 max-w-full h-fit"> <div className="inline-flex flex-wrap w-full gap-x-16 gap-y-8 max-w-full h-fit">
<FormField <GenrePicker genres={genres} form={form} />
control={form.control}
name="genres"
render={({ field }) => (
<FormItem className="flex flex-col flex-wrap">
<FormLabel className="h-5">Genres</FormLabel>
<Popover>
<GenresTrigger value={field.value} genres={genres} />
<PopoverContent align="start">
{genres.map((item) => (
<FormField
key={item.id}
control={form.control}
name="genres"
render={({ field }) => {
return (
<GenreCheckbox field={field} item={item} />
)
}}
/>
))}
<Button variant="link" className="p-0" onClick={() => form.setValue("genres", [])}>Clear</Button>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
<FormField <FormField
control={form.control} control={form.control}
@ -154,7 +120,6 @@ export default function PubForm({ genres, createPub, className }: ComponentProps
/> />
</div> </div>
<Button type="submit">Submit</Button>
</form> </form>
</Form> </Form>
</div> </div>

View File

@ -3,7 +3,6 @@
import { z } from "zod" import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { Button } from "@/components/ui/button"
import { import {
Form, Form,
FormControl, FormControl,
@ -16,37 +15,32 @@ import {
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { toast } from "@/components/ui/use-toast" import { toast } from "@/components/ui/use-toast"
import {
Popover,
PopoverContent,
} from "@/components/ui/popover"
import GenresTrigger from "./genresTrigger"
import GenreCheckbox from "./genreCheckbox"
import { ComponentProps } from "react" import { ComponentProps } from "react"
import { Genre } from "@prisma/client" import { Genre, Story } from "@prisma/client"
import { randomStoryTitle } from "app/lib/shortStoryTitleGenerator" import { randomStoryTitle } from "app/lib/shortStoryTitleGenerator"
import { usePathname } from "next/navigation" import GenrePicker from "./genrePicker"
const formSchema = z.object({ export const formSchema = z.object({
id: z.number().optional(),
title: z.string().min(2).max(50), title: z.string().min(2).max(50),
word_count: z.coerce.number().min(100), word_count: z.coerce.number().min(100),
genres: z.array(z.number()) genres: z.array(z.number())
}) })
export default function StoryForm({ genres, createStory, className }: ComponentProps<"div"> & { genres: Array<Genre>, createStory: (data: any) => void }) { export default function StoryForm({ genres, createStory, className, existingData }: ComponentProps<"div"> & { genres: Array<Genre>, createStory: (data: any) => void, existingData: Story & { genres: number[] } | null }) {
// 1. Define your form.
const form = useForm<z.infer<typeof formSchema>>({ const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
defaultValues: { defaultValues: {
title: "", id: existingData?.id,
word_count: 0, title: existingData?.title ?? "",
genres: [] word_count: existingData?.word_count ?? 500,
genres: existingData?.genres ?? []
}, },
}) })
// 2. Define a submit handler.
function onSubmit(values: z.infer<typeof formSchema>) { function onSubmit(values: z.infer<typeof formSchema>) {
// Do something with the form values.
// ✅ This will be type-safe and validated.
toast({ toast({
title: "You submitted the following values:", title: "You submitted the following values:",
description: ( description: (
@ -73,12 +67,10 @@ export default function StoryForm({ genres, createStory, className }: ComponentP
console.log(JSON.stringify(errors)) console.log(JSON.stringify(errors))
} }
const pathname = usePathname()
return ( return (
<div className={className}> <div className={className}>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8"> <form onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8" id="storyform">
<FormField <FormField
control={form.control} control={form.control}
name="title" name="title"
@ -95,35 +87,9 @@ export default function StoryForm({ genres, createStory, className }: ComponentP
<div className="inline-flex flex-wrap w-full gap-x-16 gap-y-8 items-baseline max-w-full"> <div className="inline-flex flex-wrap w-full gap-x-16 gap-y-8 items-baseline max-w-full">
<GenrePicker
<FormField genres={genres}
control={form.control} form={form}
name="genres"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="h-5">Genres</FormLabel>
<Popover>
<GenresTrigger value={field.value} genres={genres} />
<PopoverContent align="start">
{genres.map((item) => (
<FormField
key={item.id}
control={form.control}
name="genres"
render={({ field }) => {
return (
<GenreCheckbox field={field} item={item} />
)
}}
/>
))}
<Button variant="link" className="p-0" onClick={() => form.setValue("genres", [])}>Clear</Button>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/> />
<FormField <FormField
@ -133,7 +99,7 @@ export default function StoryForm({ genres, createStory, className }: ComponentP
<FormItem className="flex flex-col"> <FormItem className="flex flex-col">
<FormLabel className="h-5">Word count</FormLabel> <FormLabel className="h-5">Word count</FormLabel>
<FormControl> <FormControl>
<Input className=" w-24" type="number" step={500} min={0} {...field}></Input> <Input className=" w-24" type="number" step={500} min={1} {...field}></Input>
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@ -142,7 +108,6 @@ export default function StoryForm({ genres, createStory, className }: ComponentP
</div> </div>
<Button type="submit" className="">Submit</Button>
</form> </form>

View File

@ -32,12 +32,21 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select" } from "@/components/ui/select"
import { useState } from "react" import { useState } from "react"
import { editSubmission } from "app/lib/edit"
import { createSub } from "app/lib/create"
const FormSchema = z.object({ export const formSchema = z.object({
id: z.number().optional(),
storyId: z.coerce.number(), storyId: z.coerce.number(),
pubId: z.coerce.number(), pubId: z.coerce.number(),
submitted: z.date().transform((date) => date.toString()), submitted: z.coerce.date().transform((date) => date.toString()),
responded: z.date().transform((date) => date.toString()).optional(), responded: z.coerce.date().transform((date) => {
if (date.toString() !== new Date(null).toString()) {
return date.toString()
}
return null
}).optional(),
responseId: z.coerce.number() responseId: z.coerce.number()
}) })
.refine(object => { .refine(object => {
@ -65,12 +74,15 @@ const FormSchema = z.object({
} }
) )
export type SubForm = z.infer<typeof formSchema>
export default function SubmissionForm({ stories, pubs, responses, createSub }) {
const form = useForm<z.infer<typeof FormSchema>>({ export default function SubmissionForm({ stories, pubs, responses, defaults }) {
resolver: zodResolver(FormSchema), const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: { defaultValues: {
responseId: responses[0].id responseId: responses[0].id,
...defaults
} }
}) })
const [isSubCalendarOpen, setIsSubCalendarOpen] = useState(false); const [isSubCalendarOpen, setIsSubCalendarOpen] = useState(false);
@ -94,7 +106,7 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
// 2. Define a submit handler. // 2. Define a submit handler.
function onSubmit(values: z.infer<typeof FormSchema>) { function onSubmit(values: z.infer<typeof formSchema>) {
// Do something with the form values. // Do something with the form values.
// ✅ This will be type-safe and validated. // ✅ This will be type-safe and validated.
toast({ toast({
@ -105,7 +117,11 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
</pre> </pre>
), ),
}) })
createSub(values) if (values.id) {
editSubmission(values)
} else {
createSub(values)
}
console.log(values) console.log(values)
} }
@ -123,7 +139,7 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
return ( return (
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8"> <form id="subform" onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8">
<FormField <FormField
control={form.control} control={form.control}
name="storyId" name="storyId"
@ -177,7 +193,7 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-col"> <FormItem className="flex flex-col">
<FormLabel>Date of submission</FormLabel> <FormLabel>Date of submission</FormLabel>
<Popover open={isSubCalendarOpen} onOpenChange={setIsSubCalendarOpen}> <Popover modal={true} open={isSubCalendarOpen} onOpenChange={setIsSubCalendarOpen}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<FormControl> <FormControl>
<Button <Button
@ -222,7 +238,7 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-col"> <FormItem className="flex flex-col">
<FormLabel>Date of response</FormLabel> <FormLabel>Date of response</FormLabel>
<Popover open={isRespCalendarOpen} onOpenChange={setIsRespCalendarOpen}> <Popover modal={true} open={isRespCalendarOpen} onOpenChange={setIsRespCalendarOpen}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<FormControl> <FormControl>
<Button <Button
@ -286,7 +302,6 @@ export default function SubmissionForm({ stories, pubs, responses, createSub })
)} )}
/> />
<Button type="submit">Submit</Button>
</form> </form>
</Form> </Form>
) )

View File

@ -1,45 +0,0 @@
import { Dialog, DialogTrigger, DialogClose, DialogDescription, DialogContent, DialogTitle, DialogHeader, DialogFooter } from "@/components/ui/dialog"
import Link from "next/link"
import { Trash2, Search, Pencil } from "lucide-react"
import { Button } from "@/components/ui/button"
export function actions({ pathname, deleteFn }: { pathname: string, deleteFn: (id: number) => void }) {
return {
id: "actions",
// header: "Actions",
cell: ({ row }) => {
return <div className="flex items-center justify-around">
{!(pathname === "/submission") ?
<Link href={`${pathname}/${row.original.id}`}><Button variant="ghost"><Search /></Button></Link>
: ""
}
<Link href={`${pathname}/edit/${row.original.id}`}><Button variant="ghost"><Pencil /></Button></Link>
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost"><Trash2 color="red" /></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure?</DialogTitle>
<DialogDescription>
Deleting a {pathname.slice(1)} cannot be undone!
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose asChild>
<Button variant="destructive"
onClick={() => {
deleteFn(row.original.id)
}}>Yes, delete it!
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
}
}
}

View File

@ -0,0 +1,87 @@
import { Dialog, DialogTrigger, DialogClose, DialogDescription, DialogContent, DialogTitle, DialogHeader, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { ContextMenuContent, ContextMenuItem, ContextMenuSubTrigger, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent } from "@/components/ui/context-menu"
import { deleteRecord } from "app/lib/del"
import Link from "next/link"
import { ComponentProps, useState } from "react"
import { Row, Table, TableState } from "@tanstack/react-table"
import { tableNameToItemName } from "app/lib/nameMaps"
import EditSubmissionDialog from "app/submission/edit"
export default function FormContextMenu({ table, row }: ComponentProps<"div"> & { table: Table<any>, row: Row<any> }) {
const pathname = table.options.meta.pathname
const selectedRows = table.getSelectedRowModel().flatRows
const [dialog, setDialog] = useState<"edit" | "delete" | null>("delete")
return (
<Dialog modal={true}>
<ContextMenuContent >
{pathname !== "/submission" && selectedRows.length <= 1 ?
<>
<Link href={`${pathname}/${row.original.id}`}>
<ContextMenuItem>Inspect</ContextMenuItem>
</Link>
</>
: ""
}
{
pathname === "/submission" ?
<>
<DialogTrigger asChild>
<ContextMenuItem onClick={() => setDialog("edit")}>
Edit
</ContextMenuItem>
</DialogTrigger>
</>
: ""
}
{
selectedRows.length > 0 ?
<ContextMenuItem onClick={() => { table.resetRowSelection() }}>Deselect</ContextMenuItem>
: ""
}
<ContextMenuSeparator />
<DialogTrigger asChild>
<ContextMenuItem className="text-destructive" onClick={() => setDialog("delete")}>Delete</ContextMenuItem>
</DialogTrigger>
</ContextMenuContent>
<DialogContent>
{
dialog === "delete" ?
<>
<DialogHeader>
<DialogTitle>Are you sure?</DialogTitle>
<DialogDescription>
Deleting a {tableNameToItemName(table.options.meta.tableName)} cannot be undone!
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose asChild>
<Button variant="destructive"
onClick={() => {
deleteRecord(row.original.id, pathname)
}}>Yes, delete it!
</Button>
</DialogClose>
</DialogFooter>
</>
: dialog === "edit" ?
<EditSubmissionDialog
stories={table.options.meta.stories}
pubs={table.options.meta.pubs}
responses={table.options.meta.responses}
defaults={row.original}
/>
:
<>
<DialogTitle>Edit/delete dialog</DialogTitle>
</>
}
</DialogContent>
</Dialog>
)
}

View File

@ -1,5 +1,11 @@
"use client" "use client"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuCheckboxItem, DropdownMenuCheckboxItem,
@ -9,7 +15,7 @@ import {
DropdownMenuRadioGroup DropdownMenuRadioGroup
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { useState } from "react" import { Component, ComponentProps, use, useState } from "react"
import { import {
ColumnDef, ColumnDef,
flexRender, flexRender,
@ -20,7 +26,7 @@ import {
getFilteredRowModel, getFilteredRowModel,
getCoreRowModel, getCoreRowModel,
getPaginationRowModel, getPaginationRowModel,
useReactTable, useReactTable
} from "@tanstack/react-table" } from "@tanstack/react-table"
import { import {
@ -31,12 +37,18 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table" } from "@/components/ui/table"
import { EyeIcon } from "lucide-react" import { EyeIcon, Trash2 } from "lucide-react"
import { usePathname } from "next/navigation" import { usePathname } from "next/navigation"
import { useRouter } from "next/navigation" import FormContextMenu from "./contextMenu"
import Link from "next/link" import { deleteRecords } from "app/lib/del"
import { Pathname } from "app/types"
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTrigger } from "@/components/ui/dialog"
import pluralize from "app/lib/pluralize"
import { updateField } from "app/lib/update"
import { tableNameToItemName } from "app/lib/nameMaps"
import { Genre, Pub, Response, Story } from "@prisma/client"
interface DataTableProps<TData, TValue> { export interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[] columns: ColumnDef<TData, TValue>[]
data: TData[] data: TData[]
} }
@ -45,8 +57,13 @@ interface DataTableProps<TData, TValue> {
export function DataTable<TData, TValue>({ export function DataTable<TData, TValue>({
columns, columns,
data, data,
type children,
}: DataTableProps<TData, TValue> & { type: "publication" | "submission" | "story" | "genre" | "response" }) { tableName,
stories,
pubs,
responses,
genres
}: DataTableProps<TData, TValue> & ComponentProps<"div"> & { tableName: string, stories?: Story[], pubs?: Pub[], responses?: Response[], genres?: Genre[] }) {
//STATE //STATE
const [sorting, setSorting] = useState<SortingState>([]) const [sorting, setSorting] = useState<SortingState>([])
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>( const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(
@ -55,9 +72,12 @@ export function DataTable<TData, TValue>({
const [columnVisibility, setColumnVisibility] = const [columnVisibility, setColumnVisibility] =
useState<VisibilityState>({}) useState<VisibilityState>({})
// //
const pathname: Pathname = usePathname()
const table = useReactTable({ const table = useReactTable({
data, data,
columns, columns,
enableRowSelection: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(), getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting, onSortingChange: setSorting,
@ -70,11 +90,25 @@ export function DataTable<TData, TValue>({
columnFilters, columnFilters,
columnVisibility, columnVisibility,
}, },
//this is where you put arbitrary functions etc to make them accessible via the table api
meta: {
updateTextField: updateField,
tableName,
pathname,
stories,
pubs,
responses,
genres
}
}) })
const pathname = usePathname()
const [filterBy, setFilterBy] = useState(table.getAllColumns()[0]) const [filterBy, setFilterBy] = useState(table.getAllColumns()[0])
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false)
return (<> return (<>
<div className="flex justify-between py-4"> <div className="flex justify-between items-center py-4">
<div className="flex gap-2"> <div className="flex gap-2">
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
@ -107,9 +141,38 @@ export function DataTable<TData, TValue>({
/> />
</div> </div>
<Link href={pathname + "/create"}> {children}
<Button>Create new {type}</Button>
</Link> <Dialog>
<DialogTrigger asChild>
<Button variant="destructive" disabled={!(table.getIsSomeRowsSelected() || table.getIsAllRowsSelected())}>
<Trash2 />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
{`Delete ${Object.keys(table.getState().rowSelection).length} ${pluralize(pathname.slice(1))}?`}
</DialogHeader>
<DialogDescription>
{`Deleting ${pluralize(tableNameToItemName(table.options.meta.tableName))} cannot be undone!`}
</DialogDescription>
<DialogFooter>
<DialogClose asChild>
<Button variant="destructive"
onClick={() => {
const selectedRows = table.getState().rowSelection
const rowIds = Object.keys(selectedRows)
const recordIds = rowIds.map(id => Number(table.getRow(id).original.id))
console.table(recordIds)
deleteRecords(recordIds, pathname)
}}>
Yes, delete them!</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
@ -141,6 +204,7 @@ export function DataTable<TData, TValue>({
</DropdownMenu> </DropdownMenu>
</div> </div>
<div className="rounded-md border"> <div className="rounded-md border">
<Table> <Table>
<TableHeader> <TableHeader>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (
@ -163,19 +227,26 @@ export function DataTable<TData, TValue>({
<TableBody> <TableBody>
{table.getRowModel().rows?.length ? ( {table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => ( table.getRowModel().rows.map((row) => (
<TableRow <ContextMenu onOpenChange={open => setIsContextMenuOpen(open)} key={row.id + "contextMenu"}>
key={row.id} <ContextMenuTrigger asChild>
data-state={row.getIsSelected() && "selected"} <TableRow
> key={row.id}
{row.getVisibleCells().map((cell) => ( data-state={row.getIsSelected() && "selected"}
<TableCell key={cell.id} tabIndex={0}
onClick={(e) => { console.log(`row: ${JSON.stringify(row.original)} cell: ${cell.id} ${JSON.stringify(e.timeStamp)}`) }}
> >
{flexRender(cell.column.columnDef.cell, cell.getContext())} {row.getVisibleCells().map((cell) => (
</TableCell> <TableCell key={cell.id}>
))} {flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableRow> </TableCell>
))}
<FormContextMenu
key={"formContextMenu" + row.id}
row={row}
table={table}
/>
</TableRow>
</ContextMenuTrigger>
</ContextMenu>
)) ))
) : ( ) : (
<TableRow> <TableRow>

View File

@ -0,0 +1,142 @@
"use client"
import { FormField, FormItem, FormLabel, FormMessage, FormControl, Form } from "@/components/ui/form"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { ComponentProps, useState } from "react"
import { EventType, useForm, UseFormReturn } from "react-hook-form"
import { CellContext } from "@tanstack/react-table"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "@/components/ui/use-toast"
import GenreBadges from "app/ui/genreBadges"
import { updateField, updateGenres } from "app/lib/update"
import { Genre } from "@prisma/client"
export default function GenrePickerInputCell(props: CellContext<any, any>) {
const table = props.table.options.meta.tableName
const pathname = props.table.options.meta.pathname
const id = props.row.original.id
const column = props.column.id
const value = props.cell.getValue()
const genres = props.table.options.meta.genres
const [isActive, setIsActive] = useState(false)
async function onSubmit({ genres }: { genres: number[] }) {
event.preventDefault()
const genresArray = genres.map((e) => { return { id: e } })
console.log(`genres: ${genres}, genresArray: ${JSON.stringify(genresArray)}`)
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(genres)}</code>
</pre>
),
})
const res = await updateGenres({
id,
table,
genres: genresArray,
pathname
})
setIsActive(false)
}
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))
}
const formSchema = z.object({
genres: z.array(z.coerce.number())
})
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
genres: value.map(e => e.id)
}
})
const formId = "editGenresForm" + props.cell.id
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)} id={formId}>
<Popover modal={true} open={isActive} onOpenChange={() => setIsActive(prev => !prev)}>
<FormField
control={form.control}
name="genres"
render={({ field }) => (
<FormItem className="flex flex-col">
<PopoverTrigger>
{value.length > 0 ? <GenreBadges genres={value} /> : <p>Add genres</p>
}
</PopoverTrigger>
<PopoverContent align="start">
{genres.map((item: Genre) => (
< FormField
key={item.id}
control={form.control}
name="genres"
render={({ field }) => {
return (
<FormItem
key={item.id}
className="flex flex-row items-start space-x-3 space-y-0"
>
<FormControl>
<Checkbox
checked={field.value?.includes(item.id)}
onCheckedChange={(checked) => {
console.log(field.value)
return checked
? field.onChange(
[...field.value, item.id]
)
: field.onChange(
field.value?.filter(
(value) => value !== item.id
)
)
}}
/>
</FormControl>
<FormLabel className="text-sm font-normal">
{item.name}
</FormLabel>
</FormItem>
)
}}
/>
))}
<Button variant="ghost" form={formId}>Submit</Button>
<Button variant="link" className="p-0" onClick={() => form.setValue("genres", [])}>Clear</Button>
</PopoverContent>
<FormMessage />
</FormItem>
)}
/>
</Popover>
</form>
</Form>
)
}

View File

@ -0,0 +1,104 @@
"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";
export default function NumberInputCell(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
const value = props.cell.getValue()
const formSchema = props.column.columnDef.meta.formSchema.pick({ [column]: true })
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
[column]: props.cell.getValue()
},
})
function onSubmit(value: z.infer<typeof formSchema>) {
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>
),
})
updateField({
id,
table,
number: value[column],
column,
pathname
})
setIsActive(false)
}
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 (
<div
onDoubleClick={() => setIsActive(prev => !prev)}
className="w-full h-fit flex items-center justify-center"
tabIndex={0}
onKeyDown={e => {
if (e.code === "Enter" && !isActive) {
e.preventDefault()
setIsActive(true)
}
}}
>
{isActive ?
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)}
>
<FormField
control={form.control}
name={column}
render={({ field }) => (
<FormItem
onBlur={() => setIsActive(false)}
>
<FormControl
>
<Input
className="w-24"
type="number"
autoFocus={true}
step={props.column.columnDef.meta?.step}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
: <p>{props.cell.getValue()}</p>
}
</div >
)
}

View File

@ -0,0 +1,103 @@
"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";
import TitleContainer from "app/ui/titleContainer";
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
const value = props.cell.getValue()
const formSchema = props.column.columnDef.meta.formSchema.pick({ [column]: true })
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
[column]: props.cell.getValue()
},
})
async function onSubmit(value: z.infer<typeof formSchema>) {
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>
),
})
const res = await updateField({
id,
table,
datum: value[column],
column,
pathname
})
setIsActive(false)
}
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 (
<div
onDoubleClick={() => setIsActive(prev => !prev)}
className="w-full h-fit flex items-center justify-left"
tabIndex={0}
onKeyDown={e => {
if (e.code === "Enter" && !isActive) {
e.preventDefault()
setIsActive(true)
}
}}
>
{isActive ?
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)}
>
<FormField
control={form.control}
name={column}
render={({ field }) => (
<FormItem
onBlur={() => setIsActive(false)}
>
<FormControl
>
<Input
className="w-fit"
type="text"
autoFocus={true}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
: <TitleContainer>{props.cell.getValue()}</TitleContainer>
}
</div >
)
}

View File

@ -0,0 +1,32 @@
import { Checkbox } from "@/components/ui/checkbox";
import { CellContext, Column, ColumnDef, ColumnMeta, Header, HeaderContext, RowSelectionTableState, Table, TableState } from "@tanstack/react-table";
export const selectCol = {
id: "select",
header: (props: HeaderContext<any, any>) => {
return (
<div className="flex items-center justify-center">
<Checkbox
checked={props.table.getIsAllRowsSelected()}
onCheckedChange={props.table.toggleAllRowsSelected}
aria-label="select/deselect all rows"
/>
</div>
)
},
cell: (props: CellContext<any, any>) => {
return (
<div className="flex items-center justify-center">
<Checkbox
checked={props.row.getIsSelected()}
onCheckedChange={props.row.toggleSelected}
aria-label="select/deselect row"
/>
</div>
)
}
}

View File

@ -0,0 +1,11 @@
import { ComponentProps } from "react";
export default function itleContainer({ children }: ComponentProps<"div">) {
let classes = "w-full text-left m-auto"
console.table(children)
if (children == "RECORD DELETED") {
console.log("BINGO")
classes = classes + " text-destructive font-bold"
}
return <span className="h-10 flex align-center"><p className={classes}>{children}</p></span>
}