Skip to content

Commit

Permalink
Merge pull request #333 from Roshan-Horo/feat/tag_edit_functionality
Browse files Browse the repository at this point in the history
Feat/tag edit functionality
  • Loading branch information
DonKoko authored Sep 4, 2023
2 parents 73be018 + e246c7d commit a271b29
Show file tree
Hide file tree
Showing 5 changed files with 185 additions and 9 deletions.
25 changes: 25 additions & 0 deletions app/modules/tag/service.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,28 @@ export const buildTagsSet = (tags: string | undefined) =>
set: tags?.split(",").map((t) => ({ id: t })) || [],
}
: { set: [] };

export async function getTag({ id }: Pick<Tag, "id">){
return db.tag.findUnique({
where: {
id
}
})
}

export async function updateTag({
id,
name,
description
}: Pick<Tag, "id" | "name" | "description" >
) {
return db.tag.update({
where: {
id
},
data: {
name,
description
},
});
}
12 changes: 4 additions & 8 deletions app/routes/_layout+/categories.$categoryId_.edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { Button } from "~/components/shared/button";

import { requireAuthSession, commitAuthSession } from "~/modules/auth";
import { getCategory, updateCategory } from "~/modules/category";
import { assertIsPost, isFormProcessing, getRequiredParam } from "~/utils";
import { assertIsPost, isFormProcessing, getRequiredParam, handleInputChange } from "~/utils";
import { appendToMetaTitle } from "~/utils/append-to-meta-title";
import { sendNotification } from "~/utils/emitter/send-notification.server";

Expand Down Expand Up @@ -85,15 +85,11 @@ export default function EditCategory() {
const disabled = isFormProcessing(navigation.state);
const { colorFromServer, category } = useLoaderData();

const [formData, setFormData] = useState({
const [formData, setFormData] = useState<{ [key: string]: any }>({
name: category.name,
description: category.description,
})

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, field: string) => {
setFormData(form => ({ ...form, [field]: event.target.value }))
}

return (
<>
<Form
Expand All @@ -112,7 +108,7 @@ export default function EditCategory() {
hideErrorText
autoFocus
value={formData.name}
onChange={e => handleInputChange(e, 'name')}
onChange={e => handleInputChange(e, setFormData, 'name')}
/>
<Input
label="Description"
Expand All @@ -122,7 +118,7 @@ export default function EditCategory() {
data-test-id="categoryDescription"
className="mb-4 lg:mb-0"
value={formData.description}
onChange={e => handleInputChange(e, 'description')}
onChange={e => handleInputChange(e, setFormData, 'description')}
/>
<div className="mb-6 lg:mb-0">
<ColorInput
Expand Down
131 changes: 131 additions & 0 deletions app/routes/_layout+/tags.$tagId_.edit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { useState } from 'react'
import type { LoaderArgs, V2_MetaFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useLoaderData, useNavigation } from "@remix-run/react";
import { parseFormAny, useZorm } from "react-zorm";
import { z } from "zod";
import Input from "~/components/forms/input";

import { Button } from "~/components/shared/button";

import { requireAuthSession, commitAuthSession } from "~/modules/auth";
import { getTag, updateTag } from "~/modules/tag";
import { assertIsPost, getRequiredParam, isFormProcessing, handleInputChange } from "~/utils";
import { appendToMetaTitle } from "~/utils/append-to-meta-title";
import { sendNotification } from "~/utils/emitter/send-notification.server";

export const UpdateTagFormSchema = z.object({
name: z.string().min(3, "Name is required"),
description: z.string(),
});

const title = "Edit Tag";

export async function loader({ request, params }: LoaderArgs) {
await requireAuthSession(request);

const id = getRequiredParam(params, "tagId");
const tag = await getTag({ id })

const header = {
title,
};

return json({ header, tag });
}

export const meta: V2_MetaFunction<typeof loader> = ({ data }) => [
{ title: data ? appendToMetaTitle(data.header.title) : "" },
];

export async function action({ request, params }: LoaderArgs) {
const authSession = await requireAuthSession(request);
assertIsPost(request);
const formData = await request.formData();
const result = await UpdateTagFormSchema.safeParseAsync(parseFormAny(formData));

const id = getRequiredParam(params, "tagId");

if (!result.success) {
return json(
{
errors: result.error,
},
{ status: 400 }
);
}

await updateTag({
...result.data,
id
});

sendNotification({
title: "Tag Updated",
message: "Your tag has been updated successfully",
icon: { name: "success", variant: "success" },
senderId: authSession.userId,
});

return redirect(`/tags`, {
headers: {
"Set-Cookie": await commitAuthSession(request, { authSession }),
},
});
}

export default function EditTag() {
const zo = useZorm("NewQuestionWizardScreen", UpdateTagFormSchema);
const navigation = useNavigation();
const disabled = isFormProcessing(navigation.state);
const { tag } = useLoaderData();

const [formData, setFormData] = useState<{ [key: string]: any}>({
name: tag.name,
description: tag.description,
})

return (
<>
<Form
method="post"
className="block rounded-[12px] border border-gray-200 bg-white px-6 py-5 lg:flex lg:items-end lg:justify-between lg:gap-3"
ref={zo.ref}
>
<div className="gap-3 lg:flex lg:items-end">
<Input
label="Name"
placeholder="Tag name"
className="mb-4 lg:mb-0 lg:max-w-[180px]"
name={zo.fields.name()}
disabled={disabled}
error={zo.errors.name()?.message}
hideErrorText
autoFocus
value={formData.name}
onChange={e => handleInputChange(e, setFormData, 'name')}
/>
<Input
label="Description"
placeholder="Description (optional)"
name={zo.fields.description()}
disabled={disabled}
data-test-id="tagDescription"
className="mb-4 lg:mb-0"
value={formData.description}
onChange={e => handleInputChange(e, setFormData, 'description')}
/>
</div>

<div className="flex gap-1">
<Button variant="secondary" to="/tags" size="sm">
Cancel
</Button>
<Button type="submit" size="sm">
Update
</Button>
</div>
</Form>
</>
);
}
17 changes: 16 additions & 1 deletion app/routes/_layout+/tags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export default function CategoriesPage() {
ItemComponent={TagItem}
headerChildren={
<>
<Th>Description</Th>
<Th>Actions</Th>
</>
}
Expand All @@ -118,10 +119,24 @@ const TagItem = ({
item: Pick<Tag, "id" | "description" | "name">;
}) => (
<>
<Td className="w-full text-left" title={`Tag: ${item.name}`}>
<Td className="w-1/4 text-left" title={`Tag: ${item.name}`}>
<TagBadge>{item.name}</TagBadge>
</Td>
<Td className="w-3/4 text-gray-500" title="Description">
{item.description}
</Td>
<Td className="text-left">
<Button
to={`${item.id}/edit`}
role="link"
aria-label={`edit tags`}
variant="secondary"
size="sm"
className=" mx-2 text-[12px]"
icon={"write"}
title={"Edit"}
data-test-id="editTagsButton"
/>
<DeleteTag tag={item} />
</Td>
</>
Expand Down
9 changes: 9 additions & 0 deletions app/utils/form.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
export function isFormProcessing(state: "idle" | "submitting" | "loading") {
return state === "submitting" || state === "loading";
}

export function handleInputChange(
event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> ,
setState: React.Dispatch<React.SetStateAction<{
[key: string]: any;
}>>,
field: string){
setState(currentState => ({...currentState, [field]: event.target.value}))
}

0 comments on commit a271b29

Please sign in to comment.