style: my profile page (#608)

This commit is contained in:
Aaryan Khandelwal 2023-03-30 17:04:41 +05:30 committed by GitHub
parent 5feaed3961
commit ed4aae47a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 477 additions and 351 deletions

View File

@ -94,8 +94,7 @@ export const STATE_LIST = (projectId: string) => `STATE_LIST_${projectId.toUpper
export const STATE_DETAIL = "STATE_DETAILS";
export const USER_ISSUE = (workspaceSlug: string) => `USER_ISSUE_${workspaceSlug.toUpperCase()}`;
export const USER_ACTIVITY = (workspaceSlug: string) =>
`USER_ACTIVITY_${workspaceSlug.toUpperCase()}`;
export const USER_ACTIVITY = "USER_ACTIVITY";
export const USER_WORKSPACE_DASHBOARD = (workspaceSlug: string) =>
`USER_WORKSPACE_DASHBOARD_${workspaceSlug.toUpperCase()}`;
export const USER_PROJECT_VIEW = (projectId: string) =>

View File

@ -42,6 +42,7 @@ type AppLayoutProps = {
left?: JSX.Element;
right?: JSX.Element;
settingsLayout?: boolean;
profilePage?: boolean;
memberType?: UserAuth;
};
@ -55,6 +56,7 @@ const AppLayout: FC<AppLayoutProps> = ({
left,
right,
settingsLayout = false,
profilePage = false,
memberType,
}) => {
// states
@ -152,13 +154,17 @@ const AppLayout: FC<AppLayoutProps> = ({
<div className="mb-12 space-y-6">
<div>
<h3 className="text-3xl font-semibold">
{projectId ? "Project" : "Workspace"} Settings
{profilePage ? "Profile" : projectId ? "Project" : "Workspace"} Settings
</h3>
<p className="mt-1 text-gray-600">
This information will be displayed to every member of the project.
{profilePage
? "This information will be visible to only you."
: projectId
? "This information will be displayed to every member of the project."
: "This information will be displayed to every member of the workspace."}
</p>
</div>
<SettingsNavbar />
<SettingsNavbar profilePage={profilePage} />
</div>
)}
{children}

View File

@ -1,7 +1,11 @@
import Link from "next/link";
import { useRouter } from "next/router";
const SettingsNavbar: React.FC = () => {
type Props = {
profilePage: boolean;
};
const SettingsNavbar: React.FC<Props> = ({ profilePage = false }) => {
const router = useRouter();
const { workspaceSlug, projectId } = router.query;
@ -65,9 +69,23 @@ const SettingsNavbar: React.FC = () => {
},
];
const profileLinks: Array<{
label: string;
href: string;
}> = [
{
label: "General",
href: `/${workspaceSlug}/me/profile`,
},
{
label: "Activity",
href: `/${workspaceSlug}/me/profile/activity`,
},
];
return (
<div className="flex flex-wrap gap-4">
{(projectId ? projectLinks : workspaceLinks).map((link) => (
{(profilePage ? profileLinks : projectId ? projectLinks : workspaceLinks).map((link) => (
<Link key={link.href} href={link.href}>
<a>
<div

View File

@ -1,338 +0,0 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
// react-hook-form
import { useForm } from "react-hook-form";
// lib
import { requiredAuth } from "lib/auth";
// services
import fileService from "services/file.service";
import userService from "services/user.service";
// hooks
import useUser from "hooks/use-user";
import useToast from "hooks/use-toast";
// layouts
import AppLayout from "layouts/app-layout";
// components
import { ImageUploadModal } from "components/core";
// ui
import { DangerButton, Input, SecondaryButton, Spinner } from "components/ui";
import { BreadcrumbItem, Breadcrumbs } from "components/breadcrumbs";
// icons
import {
ChevronRightIcon,
PencilIcon,
RectangleStackIcon,
UserIcon,
UserPlusIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
// types
import type { NextPage, GetServerSidePropsContext } from "next";
import type { IUser } from "types";
import { useRouter } from "next/dist/client/router";
const defaultValues: Partial<IUser> = {
avatar: "",
first_name: "",
last_name: "",
email: "",
};
const Profile: NextPage = () => {
const [isEditing, setIsEditing] = useState(false);
const [isRemoving, setIsRemoving] = useState(false);
const [isImageUploadModalOpen, setIsImageUploadModalOpen] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const {
register,
handleSubmit,
reset,
watch,
setValue,
formState: { errors, isSubmitting },
} = useForm<IUser>({ defaultValues });
const { setToastAlert } = useToast();
const { user: myProfile, mutateUser, assignedIssuesLength, workspaceInvitesLength } = useUser();
useEffect(() => {
reset({ ...defaultValues, ...myProfile });
}, [myProfile, reset]);
const onSubmit = (formData: IUser) => {
const payload: Partial<IUser> = {
first_name: formData.first_name,
last_name: formData.last_name,
avatar: formData.avatar,
};
userService
.updateUser(payload)
.then((res) => {
mutateUser((prevData) => {
if (!prevData) return prevData;
return { ...prevData, user: { ...payload, ...res } };
}, false);
setIsEditing(false);
setToastAlert({
type: "success",
title: "Success!",
message: "Profile updated successfully.",
});
})
.catch(() => {
setToastAlert({
type: "error",
title: "Error!",
message: "There was some error in updating your profile. Please try again.",
});
});
};
const handleDelete = (url: string | null | undefined, updateUser: boolean = false) => {
if (!url) return;
setIsRemoving(true);
const index = url.indexOf(".com");
const asset = url.substring(index + 5);
fileService.deleteUserFile(asset).then(() => {
if (updateUser)
userService
.updateUser({ avatar: "" })
.then((res) => {
setIsRemoving(false);
setToastAlert({
type: "success",
title: "Success!",
message: "Profile picture removed successfully.",
});
mutateUser((prevData) => {
if (!prevData) return prevData;
return { ...prevData, user: res };
}, false);
})
.catch(() => {
setIsRemoving(false);
setToastAlert({
type: "error",
title: "Error!",
message: "There was some error in deleting your profile picture. Please try again.",
});
});
});
};
const quickLinks = [
{
icon: RectangleStackIcon,
title: "Assigned Issues",
number: assignedIssuesLength,
description: "View issues assigned to you.",
href: `/${workspaceSlug}/me/my-issues`,
},
{
icon: UserPlusIcon,
title: "Workspace Invitations",
number: workspaceInvitesLength,
description: "View your workspace invitations.",
href: "/invitations",
},
];
return (
<AppLayout
meta={{
title: "Plane - My Profile",
}}
breadcrumbs={
<Breadcrumbs>
<BreadcrumbItem title="My Profile" />
</Breadcrumbs>
}
>
<ImageUploadModal
isOpen={isImageUploadModalOpen}
onClose={() => setIsImageUploadModalOpen(false)}
onSuccess={(url) => {
handleDelete(myProfile?.avatar);
setValue("avatar", url);
handleSubmit(onSubmit)();
setIsImageUploadModalOpen(false);
}}
value={watch("avatar") !== "" ? watch("avatar") : undefined}
userImage
/>
<div className="w-full space-y-5">
{myProfile ? (
<>
<div className="space-y-5">
<section className="relative flex flex-col gap-y-6 gap-x-10 rounded-xl bg-secondary p-5 md:flex-row">
<button
type="button"
className="absolute top-4 right-4 cursor-pointer rounded bg-indigo-100 p-1 duration-300 hover:bg-theme hover:text-white"
onClick={() => setIsEditing((prevData) => !prevData)}
>
{isEditing ? (
<XMarkIcon className="h-4 w-4" />
) : (
<PencilIcon className="h-4 w-4" />
)}
</button>
<div className="flex-shrink-0">
<div className="space-y-4">
<div className="relative">
<div className="inline-block h-40 w-40 overflow-hidden rounded bg-gray-100">
{!watch("avatar") || watch("avatar") === "" ? (
<UserIcon className="h-full w-full text-gray-300" />
) : (
<div className="relative h-40 w-40 overflow-hidden">
<Image
src={watch("avatar")}
alt={myProfile.first_name}
layout="fill"
objectFit="cover"
priority
onClick={() => setIsImageUploadModalOpen(true)}
/>
</div>
)}
</div>
</div>
<p className="text-sm text-gray-500">
Max file size is 5MB.
<br />
Supported file types are .jpg and .png.
</p>
<div className="mt-4 flex items-center gap-2">
<SecondaryButton onClick={() => setIsImageUploadModalOpen(true)}>
Upload new
</SecondaryButton>
{myProfile.avatar && myProfile.avatar !== "" && (
<DangerButton
onClick={() => handleDelete(myProfile.avatar, true)}
loading={isRemoving}
>
{isRemoving ? "Removing..." : "Remove"}
</DangerButton>
)}
</div>
</div>
</div>
<form className="space-y-5" onSubmit={handleSubmit(onSubmit)}>
<div className="mt-2 grid grid-cols-2 gap-x-10 gap-y-5">
<div>
<h4 className="text-sm text-gray-500">First Name</h4>
{isEditing ? (
<Input
name="first_name"
id="first_name"
register={register}
error={errors.first_name}
placeholder="Enter your first name"
autoComplete="off"
validations={{
required: "This field is required.",
}}
/>
) : (
<h2>{myProfile.first_name}</h2>
)}
</div>
<div>
<h4 className="text-sm text-gray-500">Last Name</h4>
{isEditing ? (
<Input
name="last_name"
register={register}
error={errors.last_name}
id="last_name"
placeholder="Enter your last name"
autoComplete="off"
/>
) : (
<h2>{myProfile.last_name}</h2>
)}
</div>
<div>
<h4 className="text-sm text-gray-500">Email ID</h4>
<h2>{myProfile.email}</h2>
</div>
</div>
{isEditing && (
<div>
<SecondaryButton type="submit" loading={isSubmitting}>
{isSubmitting ? "Updating Profile..." : "Update Profile"}
</SecondaryButton>
</div>
)}
</form>
</section>
<section>
<h2 className="mb-3 text-xl font-medium">Quick Links</h2>
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
{quickLinks.map((item, index) => (
<Link key={index} href={item.href}>
<a className="group rounded-lg bg-secondary p-5 duration-300 hover:bg-theme">
<h4 className="flex items-center gap-2 duration-300 group-hover:text-white">
{item.title}
<ChevronRightIcon className="h-3 w-3" />
</h4>
<div className="flex items-center justify-between gap-3">
<div>
<h2 className="mt-3 mb-2 text-3xl font-bold duration-300 group-hover:text-white">
{item.number}
</h2>
<p className="text-sm text-gray-500 duration-300 group-hover:text-white">
{item.description}
</p>
</div>
<div>
<item.icon className="h-12 w-12 duration-300 group-hover:text-white" />
</div>
</div>
</a>
</Link>
))}
</div>
</section>
</div>
</>
) : (
<div className="mx-auto flex h-full w-full items-center justify-center">
<Spinner />
</div>
)}
</div>
</AppLayout>
);
};
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const user = await requiredAuth(ctx.req?.headers.cookie);
const redirectAfterSignIn = ctx.resolvedUrl;
if (!user) {
return {
redirect: {
destination: `/signin?next=${redirectAfterSignIn}`,
permanent: false,
},
};
}
return {
props: {
user,
},
};
};
export default Profile;

View File

@ -0,0 +1,84 @@
import { GetServerSidePropsContext } from "next";
import useSWR from "swr";
// services
import userService from "services/user.service";
// lib
import { requiredAuth } from "lib/auth";
// layouts
import AppLayout from "layouts/app-layout";
// ui
import { Loader } from "components/ui";
import { BreadcrumbItem, Breadcrumbs } from "components/breadcrumbs";
// helpers
import { timeAgo } from "helpers/date-time.helper";
// fetch-keys
import { USER_ACTIVITY } from "constants/fetch-keys";
const ProfileActivity = () => {
const { data: userActivity } = useSWR(USER_ACTIVITY, () => userService.getUserActivity());
return (
<AppLayout
meta={{
title: "Plane - My Profile",
}}
breadcrumbs={
<Breadcrumbs>
<BreadcrumbItem title="My Profile Activity" />
</Breadcrumbs>
}
settingsLayout
profilePage
>
{userActivity ? (
<div className="divide-y rounded-[10px] border border-gray-200 bg-white px-6 -mt-4">
{userActivity.results.length > 0
? userActivity.results.map((activity) => (
<div
key={activity.id}
className="flex items-center gap-2 justify-between py-4 text-sm text-gray-500"
>
<h4>
<span className="font-medium text-black">{activity.comment}</span>
</h4>
<div className="text-xs">{timeAgo(activity.created_at)}</div>
</div>
))
: null}
</div>
) : (
<Loader className="space-y-5">
<Loader.Item height="40px" />
<Loader.Item height="40px" />
<Loader.Item height="40px" />
<Loader.Item height="40px" />
</Loader>
)}
</AppLayout>
);
};
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const user = await requiredAuth(ctx.req?.headers.cookie);
const redirectAfterSignIn = ctx.resolvedUrl;
if (!user) {
return {
redirect: {
destination: `/signin?next=${redirectAfterSignIn}`,
permanent: false,
},
};
}
return {
props: {
user,
},
};
};
export default ProfileActivity;

View File

@ -0,0 +1,324 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
// react-hook-form
import { useForm } from "react-hook-form";
// lib
import { requiredAuth } from "lib/auth";
// services
import fileService from "services/file.service";
import userService from "services/user.service";
// hooks
import useUser from "hooks/use-user";
import useToast from "hooks/use-toast";
// layouts
import AppLayout from "layouts/app-layout";
// components
import { ImageUploadModal } from "components/core";
// ui
import { DangerButton, Input, SecondaryButton, Spinner } from "components/ui";
import { BreadcrumbItem, Breadcrumbs } from "components/breadcrumbs";
// icons
import {
ChevronRightIcon,
PencilIcon,
RectangleStackIcon,
UserIcon,
UserPlusIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
// types
import type { NextPage, GetServerSidePropsContext } from "next";
import type { IUser } from "types";
import { useRouter } from "next/dist/client/router";
const defaultValues: Partial<IUser> = {
avatar: "",
first_name: "",
last_name: "",
email: "",
};
const Profile: NextPage = () => {
const [isEditing, setIsEditing] = useState(false);
const [isRemoving, setIsRemoving] = useState(false);
const [isImageUploadModalOpen, setIsImageUploadModalOpen] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const {
register,
handleSubmit,
reset,
watch,
setValue,
formState: { errors, isSubmitting },
} = useForm<IUser>({ defaultValues });
const { setToastAlert } = useToast();
const { user: myProfile, mutateUser, assignedIssuesLength, workspaceInvitesLength } = useUser();
useEffect(() => {
reset({ ...defaultValues, ...myProfile });
}, [myProfile, reset]);
const onSubmit = async (formData: IUser) => {
const payload: Partial<IUser> = {
first_name: formData.first_name,
last_name: formData.last_name,
avatar: formData.avatar,
};
await userService
.updateUser(payload)
.then((res) => {
mutateUser((prevData) => {
if (!prevData) return prevData;
return { ...prevData, user: { ...payload, ...res } };
}, false);
setIsEditing(false);
setToastAlert({
type: "success",
title: "Success!",
message: "Profile updated successfully.",
});
})
.catch(() => {
setToastAlert({
type: "error",
title: "Error!",
message: "There was some error in updating your profile. Please try again.",
});
});
};
const handleDelete = (url: string | null | undefined, updateUser: boolean = false) => {
if (!url) return;
setIsRemoving(true);
const index = url.indexOf(".com");
const asset = url.substring(index + 5);
fileService.deleteUserFile(asset).then(() => {
if (updateUser)
userService
.updateUser({ avatar: "" })
.then((res) => {
setIsRemoving(false);
setToastAlert({
type: "success",
title: "Success!",
message: "Profile picture removed successfully.",
});
mutateUser((prevData) => {
if (!prevData) return prevData;
return { ...prevData, user: res };
}, false);
})
.catch(() => {
setIsRemoving(false);
setToastAlert({
type: "error",
title: "Error!",
message: "There was some error in deleting your profile picture. Please try again.",
});
});
});
};
const quickLinks = [
{
icon: RectangleStackIcon,
title: "Assigned Issues",
number: assignedIssuesLength,
description: "View issues assigned to you.",
href: `/${workspaceSlug}/me/my-issues`,
},
{
icon: UserPlusIcon,
title: "Workspace Invitations",
number: workspaceInvitesLength,
description: "View your workspace invitations.",
href: "/invitations",
},
];
return (
<AppLayout
meta={{
title: "Plane - My Profile",
}}
breadcrumbs={
<Breadcrumbs>
<BreadcrumbItem title="My Profile" />
</Breadcrumbs>
}
settingsLayout
profilePage
>
<ImageUploadModal
isOpen={isImageUploadModalOpen}
onClose={() => setIsImageUploadModalOpen(false)}
onSuccess={(url) => {
handleDelete(myProfile?.avatar);
setValue("avatar", url);
handleSubmit(onSubmit)();
setIsImageUploadModalOpen(false);
}}
value={watch("avatar") !== "" ? watch("avatar") : undefined}
userImage
/>
{myProfile ? (
<div className="space-y-8 sm:space-y-12">
<div className="grid grid-cols-12 gap-4 sm:gap-16">
<div className="col-span-12 sm:col-span-6">
<h4 className="text-xl font-semibold">Profile Picture</h4>
<p className="text-gray-500">
Max file size is 5MB. Supported file types are .jpg and .png.
</p>
</div>
<div className="col-span-12 sm:col-span-6">
<div className="flex items-center gap-4">
<button type="button" onClick={() => setIsImageUploadModalOpen(true)}>
{!watch("avatar") || watch("avatar") === "" ? (
<div className="bg-gray-100 h-12 w-12 p-2 rounded-md">
<UserIcon className="h-full w-full text-gray-300" />
</div>
) : (
<div className="relative h-12 w-12 overflow-hidden">
<Image
src={watch("avatar")}
alt={myProfile.first_name}
layout="fill"
objectFit="cover"
className="rounded-md"
onClick={() => setIsImageUploadModalOpen(true)}
priority
/>
</div>
)}
</button>
<div className="flex items-center gap-2">
<SecondaryButton
onClick={() => {
setIsImageUploadModalOpen(true);
}}
>
Upload
</SecondaryButton>
{myProfile.avatar && myProfile.avatar !== "" && (
<DangerButton
onClick={() => handleDelete(myProfile.avatar, true)}
loading={isRemoving}
>
{isRemoving ? "Removing..." : "Remove"}
</DangerButton>
)}
</div>
</div>
</div>
</div>
<div className="grid grid-cols-12 gap-4 sm:gap-16">
<div className="col-span-12 sm:col-span-6">
<h4 className="text-xl font-semibold">Full Name</h4>
<p className="text-gray-500">
This name will be reflected on all the projects you are working on.
</p>
</div>
<div className="col-span-12 sm:col-span-6 flex items-center gap-2">
<Input
name="first_name"
id="first_name"
register={register}
error={errors.first_name}
placeholder="Enter your first name"
autoComplete="off"
validations={{
required: "This field is required.",
}}
/>
<Input
name="last_name"
register={register}
error={errors.last_name}
id="last_name"
placeholder="Enter your last name"
autoComplete="off"
/>
</div>
</div>
<div className="grid grid-cols-12 gap-4 sm:gap-16">
<div className="col-span-12 sm:col-span-6">
<h4 className="text-xl font-semibold">Email</h4>
<p className="text-gray-500">The email address that you are using.</p>
</div>
<div className="col-span-12 sm:col-span-6">
<Input
id="email"
name="email"
autoComplete="off"
register={register}
error={errors.name}
className="w-full"
disabled
/>
</div>
</div>
<div className="grid grid-cols-12 gap-4 sm:gap-16">
<div className="col-span-12 sm:col-span-6">
<h4 className="text-xl font-semibold">Role</h4>
<p className="text-gray-500">The email address that you are using.</p>
</div>
<div className="col-span-12 sm:col-span-6">
<Input
id="role"
name="role"
autoComplete="off"
register={register}
error={errors.name}
className="w-full"
disabled
/>
</div>
</div>
<div className="sm:text-right">
<SecondaryButton onClick={handleSubmit(onSubmit)} loading={isSubmitting}>
{isSubmitting ? "Updating..." : "Update profile"}
</SecondaryButton>
</div>
</div>
) : (
<div className="grid h-full w-full place-items-center px-4 sm:px-0">
<Spinner />
</div>
)}
</AppLayout>
);
};
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const user = await requiredAuth(ctx.req?.headers.cookie);
const redirectAfterSignIn = ctx.resolvedUrl;
if (!user) {
return {
redirect: {
destination: `/signin?next=${redirectAfterSignIn}`,
permanent: false,
},
};
}
return {
props: {
user,
},
};
};
export default Profile;

View File

@ -47,9 +47,9 @@ const WorkspaceSettings: NextPage<UserAuth> = (props) => {
const [isImageUploading, setIsImageUploading] = useState(false);
const [isImageUploadModalOpen, setIsImageUploadModalOpen] = useState(false);
const {
query: { workspaceSlug },
} = useRouter();
const router = useRouter();
const { workspaceSlug } = router.query;
const { setToastAlert } = useToast();
const { data: activeWorkspace } = useSWR(

View File

@ -2,7 +2,7 @@
import APIService from "services/api.service";
import trackEventServices from "services/track-event.service";
import type { IUser, IUserActivity, IUserWorkspaceDashboard } from "types";
import type { IUser, IUserActivityResponse, IUserWorkspaceDashboard } from "types";
const { NEXT_PUBLIC_API_BASE_URL } = process.env;
@ -58,8 +58,8 @@ class UserService extends APIService {
});
}
async userActivity(workspaceSlug: string): Promise<IUserActivity[]> {
return this.get(`/api/users/me/workspaces/${workspaceSlug}/activity-graph/`)
async getUserActivity(): Promise<IUserActivityResponse> {
return this.get("/api/users/activities/")
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;

View File

@ -61,6 +61,39 @@ export interface IUserWorkspaceDashboard {
upcoming_issues: IIssueLite[];
}
export interface IUserDetailedActivity {
actor: string;
actor_detail: IUserLite;
attachments: any[];
comment: string;
created_at: string;
created_by: string | null;
field: string;
id: string;
issue: string;
issue_comment: string | null;
new_identifier: string | null;
new_value: string | null;
old_identifier: string | null;
old_value: string | null;
project: string;
updated_at: string;
updated_by: string | null;
verb: string;
workspace: string;
}
export interface IUserActivityResponse {
count: number;
extra_stats: null;
next_cursor: string;
next_page_results: boolean;
prev_cursor: string;
prev_page_results: boolean;
results: IUserDetailedActivity[];
total_pages: number;
}
export type UserAuth = {
isMember: boolean;
isOwner: boolean;