drag and drop for custom page links

This commit is contained in:
2025-04-01 13:43:32 +02:00
parent 01975c900e
commit 46d10d6ef4
4 changed files with 158 additions and 46 deletions
+77 -2
View File
@@ -30,7 +30,8 @@ export async function createLinkBlock(prevState: any, formData: FormData) {
const customPage = await prisma.customPage.findUnique({ const customPage = await prisma.customPage.findUnique({
where: { uuid: data.data.customPageUuid }, where: { uuid: data.data.customPageUuid },
include: { include: {
page: true page: true,
linkBlock: true
} }
}); });
if (!customPage) { if (!customPage) {
@@ -53,12 +54,15 @@ export async function createLinkBlock(prevState: any, formData: FormData) {
} }
try { try {
const currentLinkCount = customPage.linkBlock.length;
const newOrder = currentLinkCount + 1;
await prisma.linkBlock.create({ await prisma.linkBlock.create({
data: { data: {
customPageUuid: data.data.customPageUuid, customPageUuid: data.data.customPageUuid,
redirectPageUuid: redirectPage?.uuid, redirectPageUuid: redirectPage?.uuid,
title: data.data.title, title: data.data.title,
order: data.data.order order: newOrder
} }
}); });
} catch (e: any) { } catch (e: any) {
@@ -112,3 +116,74 @@ export async function deleteLinkBlock(prevState: any, formData: FormData) {
}; };
} }
export async function updateLinkBlockOrder(prevState: any, formData: FormData) {
const schema = z.object({
linkBlockUuid: z.string().uuid(),
newOrder: z.coerce.number()
});
const data = schema.safeParse({
linkBlockUuid: formData.get("linkBlockUuid"),
newOrder: formData.get("newOrder")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
try {
// Get the link block being moved
const movedLinkBlock = await prisma.linkBlock.findUnique({
where: { uuid: data.data.linkBlockUuid },
include: { customPage: true }
});
if (!movedLinkBlock) {
return {
message: "Link block not found",
error: {}
};
}
// Get all link blocks for this custom page ordered by their current order
const allLinkBlocks = await prisma.linkBlock.findMany({
where: { customPageUuid: movedLinkBlock.customPageUuid },
orderBy: { order: "asc" }
});
// Find the current index of the moved block
const currentIndex = allLinkBlocks.findIndex(block => block.uuid === data.data.linkBlockUuid);
// Create a new array with the block moved to its new position
const reorderedBlocks = [...allLinkBlocks];
const [movedBlock] = reorderedBlocks.splice(currentIndex, 1);
reorderedBlocks.splice(data.data.newOrder - 1, 0, movedBlock);
// Update orders based on the new positions
const updates = reorderedBlocks.map((block, index) => {
return prisma.linkBlock.update({
where: { uuid: block.uuid },
data: { order: index + 1 }
});
});
// Execute all updates in a transaction
await prisma.$transaction(updates);
} catch (e: any) {
return {
message: "Error updating link order",
error: e.message
};
}
revalidatePath("/~/dash");
revalidatePath(`/~/dash/${data.data.linkBlockUuid}/page`);
return {
message: "Link order updated"
};
}
+14 -1
View File
@@ -67,6 +67,19 @@ export default async function DetailedStats({ params }: PageProps) {
const linkPages = customPage ? await prisma.redirectPage.findMany({ include: { page: true } }) : undefined const linkPages = customPage ? await prisma.redirectPage.findMany({ include: { page: true } }) : undefined
const shortcodes = linkPages ? linkPages.map((p) => p.page.shortcode) : undefined const shortcodes = linkPages ? linkPages.map((p) => p.page.shortcode) : undefined
// get link blocks if the page is a custom page
const linkBlocks = customPage ? await prisma.linkBlock.findMany({
where: {
customPageUuid: customPage.uuid
},
orderBy: {
order: "asc"
},
include: {
redirectPage: { include: { page: true } }
}
}) : undefined;
return ( return (
<div> <div>
<div className="flex justify-between max-sm:flex-col mb-10"> <div className="flex justify-between max-sm:flex-col mb-10">
@@ -112,7 +125,7 @@ export default async function DetailedStats({ params }: PageProps) {
<QRCode url={page.shortcode} /> <QRCode url={page.shortcode} />
</div> </div>
{customPage ? <CustomPageDashboard customPage={customPage} /> : ""} {customPage ? <CustomPageDashboard customPage={customPage} linkBlocks={linkBlocks || []} shortcodes={shortcodes || []} /> : ""}
<h2 className="mt-10">Visitors</h2> <h2 className="mt-10">Visitors</h2>
<p className="my-2">All visits (not unique): {page._count.stat}</p> <p className="my-2">All visits (not unique): {page._count.stat}</p>
+66 -38
View File
@@ -1,51 +1,79 @@
"use client"
import { CustomPage } from "@prisma/client" import { CustomPage } from "@prisma/client"
import prisma from "../../prisma/prisma" import prisma from "../../prisma/prisma"
import CreateLinkBlockForm from "./forms/createLinkBlockForm" import CreateLinkBlockForm from "./forms/createLinkBlockForm"
import DeleteLinkBlockForm from "./forms/deleteLinkBlockForm" import DeleteLinkBlockForm from "./forms/deleteLinkBlockForm"
import { ArrowTopRightOnSquareIcon, ArrowTrendingUpIcon, ArrowUpCircleIcon, ArrowUpRightIcon } from "@heroicons/react/24/solid" import { ArrowTopRightOnSquareIcon, ArrowTrendingUpIcon } from "@heroicons/react/24/solid"
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd"
import { updateLinkBlockOrder } from "@/actions/block_actions"
import { useRouter } from "next/navigation"
import { useState } from "react"
export default async function CustomPageDashboard(params: { customPage: CustomPage }) { export default function CustomPageDashboard({ customPage, linkBlocks, shortcodes }: {
customPage: CustomPage,
linkBlocks: any[],
shortcodes: string[]
}) {
const router = useRouter();
const [localLinkBlocks, setLocalLinkBlocks] = useState(linkBlocks);
const customPage = params.customPage const handleDragEnd = async (result: any) => {
const redirectPages = await prisma.redirectPage.findMany({ include: { page: true } }) if (!result.destination) return;
const shortcodes = redirectPages.map((p) => p.page.shortcode)
const linkBlocks = await prisma.linkBlock.findMany({ const items = Array.from(localLinkBlocks);
where: { const [reorderedItem] = items.splice(result.source.index, 1);
customPageUuid: customPage.uuid items.splice(result.destination.index, 0, reorderedItem);
},
orderBy: { // Update local state immediately
order: "asc" setLocalLinkBlocks(items);
},
include: { // Update the database in the background
redirectPage: { include: { page: true } } const formData = new FormData();
} formData.append("linkBlockUuid", reorderedItem.uuid);
}); formData.append("newOrder", result.destination.index + 1);
await updateLinkBlockOrder(null, formData);
};
return (<> return (<>
<h2 className="mb-5">Links on Page</h2> <h2 className="mb-5">Links on Page</h2>
{linkBlocks.map((block) => ( <DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="links">
<div key={block.uuid} className="flex items-center justify-between zebra max-sm:flex-col max-sm:items-start"> {(provided) => (
<div className="flex"> <div {...provided.droppableProps} ref={provided.innerRef}>
<div className="mr-5">order: {block.order}</div> {localLinkBlocks.map((block, index) => (
<div className="mr-5">title: <span className="font-bold">{block.title}</span></div> <Draggable key={block.uuid} draggableId={block.uuid} index={index}>
<div>link page: <span className="font-bold">{block.redirectPage.page.shortcode}</span></div> {(provided) => (
</div> <div
<div className="flex max-sm:mt-3 max-sm:w-full max-sm:justify-between"> ref={provided.innerRef}
<button> {...provided.draggableProps}
<a href={`/${block.redirectPage.page.shortcode}`} className="btn btn-primary"><ArrowTopRightOnSquareIcon className="button-icon" /></a> {...provided.dragHandleProps}
</button> className="flex items-center justify-between zebra max-sm:flex-col max-sm:items-start"
<button className="ml-3"> >
<a href={`/~/dash/${block.redirectPage.page.uuid}`} className="btn btn-primary"><ArrowTrendingUpIcon className="button-icon" /></a> <div className="flex">
</button> <div className="mr-5">title: <span className="font-bold">{block.title}</span></div>
<DeleteLinkBlockForm linkBlockUuid={block.uuid} /> <div>link page: <span className="font-bold">{block.redirectPage.page.shortcode}</span></div>
</div> </div>
</div> <div className="flex max-sm:mt-3 max-sm:w-full max-sm:justify-between">
))} <button>
<a href={`/${block.redirectPage.page.shortcode}`} className="btn btn-primary"><ArrowTopRightOnSquareIcon className="button-icon" /></a>
</button>
<button className="ml-3">
<a href={`/~/dash/${block.redirectPage.page.uuid}`} className="btn btn-primary"><ArrowTrendingUpIcon className="button-icon" /></a>
</button>
<DeleteLinkBlockForm linkBlockUuid={block.uuid} />
</div>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
<h2 className="mt-10">Add new link page connection</h2> <h2 className="mt-10">Add new link page connection</h2>
<CreateLinkBlockForm customPage={customPage.uuid} shortcodes={shortcodes || []} /> <CreateLinkBlockForm customPage={customPage.uuid} shortcodes={shortcodes || []} />
</>)
</>
)
} }
+1 -5
View File
@@ -31,11 +31,7 @@ export default function CreateLinkBlockForm({ customPage, shortcodes }: { custom
<input type="text" name="title" id="title" className={state.error?.title ? "border-red-400" : ""} /> <input type="text" name="title" id="title" className={state.error?.title ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.title}</p> <p className="form-label-error">{state.error?.title}</p>
</div> </div>
<div className="form-group"> <input type="hidden" name="order" value="1" />
<label htmlFor="order">Order</label>
<input defaultValue={1} type="number" name="order" id="order" className={state.error?.order ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.order}</p>
</div>
<input type="hidden" name="customPageUuid" value={customPage} /> <input type="hidden" name="customPageUuid" value={customPage} />
<SubmitButton>add to page <LinkIcon className="ml-2 button-icon" /></SubmitButton> <SubmitButton>add to page <LinkIcon className="ml-2 button-icon" /></SubmitButton>