plane/apps/app/pages/[workspaceSlug]/projects/[projectId]/issues/[issueId].tsx
Vamsi Kurama bef166a65f
dev: promote stage release to production (#155)
* refractor: removed modules from user.context

* refractor: removed cycles from user context

* refractor: removed state from user context

* feat: implement channel protocol for tracking issue-activites

* refactor: remove blocking code and add todo

* refactor: refactor the consumer with function modules

* feat: add columns for identifiers for easier redirection

* style: minor padding, coloring and consistency changes

* feat: track blocker issues

* feat: track issue after creation

* feat: add runworker in procfile

* refractor: moved all context provider to _app for more clarity

* dev: added our icons

* refractor: removed issues from user context

* refactor: rename db names to plural and remove admin register file

* refactor: integrate permission layer in endpoints

* feat: create product email html templates

* refractor: changed to getServerSide from getInitialProps, removed unused component imports and minor refractoring

* feat: remirror added

* feat: workspace member user details endpoint

* fix: resolved build issue

* refactor:  remove www

* feat: workspace details on user endpoint

* feat: added authorization in project settings

refractor: improved code readability

* fix: removed hard-coded workspace slug value, and added workspace in user interface

* refactor: invitation workflow for already existing users

* feat: modified remirror, fix: issue details sidebar

* fix: merge conflicts

* fix: merge conflicts

* fix: added missing dependencies

* refactor: remove user dependency from invitations

* refactor: issue description context is updated with manager

* dev: redis instance rewrite for ssl settings and remove REDIS_TLS env variable

* chore: upgrade python package requirements

* dev: added new migrations for changes

* dev: ssl config for django channels redis connection

* chore: upgrade channels requirements

* refactor: better function for connecting with redis ssl django channels

* chore: cleanup on manifest file

* revert: user endpoint changes

* build: setup asgi

* refactor: update invitation endpoint to do bulk operations

* style: cycles page, custom listbox, issue details page

* refractor: removed folder that were moved to workspaceSlug

* dev: uvicorn in requirements

* Update index.tsx

* refactor: get workspace slug on user endpoint

* fix: workspace slug redirections and slug value in user context

* fix: user context bugs, drag and drop in cycles and modules

* fix: merge conflicts

* fix: user context and create issue modal

* refactor: add extra columns for json and html description and script for back migrating old issues

* refactor: move all 500 errors to 400

* refractor: removed active project, active workspace, projects, and workspaces from user context

* refractor: change from /home to /, added home page redirection logic

added explict GET method on fetch request, and fixed invitation page not fetching all invitations

* fix: passing project id in command palette

* style: home page, feat: image in remirror

* fix: bugs

* chore: remove test_runner workflow from github actions

* dev: update Procfile worker count and python runtime upgrade

* refactor: update response from 404 to 403

* feat: filtering using both name and issue identifier in command palette

showing my issues instead of project issue in command palette, hiding again according to route in command palette

* fix: mutation on different CRUD operations

* fix: redirection in my issues pages

* feat: added authorization in workspace settings, moved command palette to app-layout

* feat: endpoint and column to store my issue props

* style: authorization new design,

fix: made whole button on authorization page clickable, lib/auth on unsuccessful api call redirecting to error page

* feat: return project details on modules and cycles

* fix: create cycle and state coming below issue modal, showing loader for rich text editor

refractor: changed from sprint to cycle in issue type

* fix: issue delete mustation

and some code refractor

* fix: mutation bugs, remirror bugs, style: consistent droopdowns and buttons

* feat: user role in model

* dev: added new migrations

* fix: add url for workspace availability check

* feat: onboarding screens

* fix: update url for workspace name check and add authentication layer and
fix invitation endpoint

* refactor: bulk invitations message

* refactor: response on workspace invitarions

* refactor: update identifier endpoint

* refactor: invitations endpoint

* feat: onboarding logic and validations

* fix: email striep

* dev: added workspace space member unique_together

* chore: back populate neccesary data for description field

* feat: emoji-picker gets close on select, public will be default option in create project

* fix: update error in project creation

* fix: mutation error on issue count in kanban view

some minor code refractoring

* fix: module bugs

* fix: issue activities and issue comments mutation handled at issue detail

* fix: error message for creating updates without permissions

* fix: showing no user left to invite in project invite

fix: - mutation in project settings control, style: - showing loader in project settings controller, - showing request pending for user that hasn't accepted invitation

* refactor: file asset upload directory

* fix: update last workspace id on user invitation accept

* style: onboarding screens

* style: cycles, issue activity

* feat: add json and html column in issue comments

* fix: submitting create issue modal on enter click, project not getting deselected

* feat: file size validator

* fix: emoji picker not closing on all emoji select

* feat: added validation in identifier such that it only accept uppercase text

* dev: commenting is now richer

* fix: shortcuts not getting opened in settings layouts

* style: showing sidebar on unauthorized pages

* fix: error code on exception

* fix: add issue button is working on my issues pages

* feat: new way of assets

* fix: updated activity content for description field

* fix: mutation on project settings control

style: blocker and blocked changed to outline button

* fix: description activity logging

* refactor: check for workspace slug on workspace creation

* fix: typo on workspace url check

* fix: workspace name uniqueness

* fix: remove workspace from read only field

* fix: file upload endpoint, workspace slug check

* chore: drop unique_together constraint for name and workspace

* chore: settings files cleanup and use PubSub backend on django channels

* chore: change in channels backend

* refactor: issue activity api to combine comments

* fix: instance created at key

* fix: result list

* style: create project, cycle modal, view dropdown

* feat: merged issue activities and issue comments into a single section

* fix: remirror dynamic update of issue description

* fix: removed commented code

* fix: issue acitivties mutation

* fix: empty comments cant be submitted

* fix: workspace avatar has been updated while loading

* refactor: update docker-compose to run redis and database in heroku and docker environment

* refactor: removesingle docker file configuration

* refactor: update take off script to run in asgi

* docs: added workspace, quickstart documentation

* fix: reading editor values on focus out

* refactor: cleanup environment variables and create .env.example

* refactor: add extra variables in example env

* fix: warning and erros on console

lazy loading images with low priority, added validation on onboarding for user to either join or create workspace, on onboarding user can't click button while form is getting submitted, profile page going into loading state when updated, refractor: made some state local, removed unnecessary console logs and comments, changed some variable and function name to make more sence

* feat: env examples

* fix: workspace member does not exist

* fi: remove pagination from issue list api

* refactor: remove env example from root

* feat: documentation for projects on plane

* feat: create code of conduct and contributing guidelines

* fix: update docker setup to check handle redis

* revert: bring back pagination to avoid breaking

* feat: made image uploader modal, used it in profile page and workspace page,

delete project from project settings page, join project modal in project list page

* feat: create workspace page, style: made ui consistent

* style: updated onboarding and create workspace page design

* style: responsive sidebar

* fix: updated ui imports
2023-01-10 23:55:47 +05:30

520 lines
19 KiB
TypeScript

import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import type { NextPage, NextPageContext } from "next";
import { useRouter } from "next/router";
import useSWR, { mutate } from "swr";
import { Controller, useForm } from "react-hook-form";
import { Disclosure, Transition } from "@headlessui/react";
// services
import issuesServices from "lib/services/issues.service";
import projectService from "lib/services/project.service";
// lib
import { requiredAuth } from "lib/auth";
// layouts
import AppLayout from "layouts/app-layout";
// components
import AddAsSubIssue from "components/project/issues/issue-detail/add-as-sub-issue";
import CreateUpdateIssuesModal from "components/project/issues/create-update-issue-modal";
import IssueDetailSidebar from "components/project/issues/issue-detail/issue-detail-sidebar";
import AddIssueComment from "components/project/issues/issue-detail/comment/issue-comment-section";
import IssueActivitySection from "components/project/issues/issue-detail/activity";
// ui
import { Loader, TextArea, HeaderButton, Breadcrumbs, CustomMenu } from "ui";
// icons
import { ChevronLeftIcon, ChevronRightIcon, PlusIcon } from "@heroicons/react/24/outline";
// types
import { IIssue, IssueResponse } from "types";
// fetch-keys
import {
PROJECT_DETAILS,
PROJECT_ISSUES_LIST,
PROJECT_ISSUES_ACTIVITY,
} from "constants/fetch-keys";
// common
import { debounce } from "constants/common";
const RemirrorRichTextEditor = dynamic(() => import("components/rich-text-editor"), {
ssr: false,
loading: () => (
<Loader>
<Loader.Item height="12rem" width="100%" />
</Loader>
),
});
const defaultValues = {
name: "",
description: "",
description_html: "",
state: "",
assignees_list: [],
priority: "low",
blockers_list: [],
blocked_list: [],
target_date: new Date().toString(),
issue_cycle: null,
labels_list: [],
};
const IssueDetail: NextPage = () => {
const [isOpen, setIsOpen] = useState(false);
const [isAddAsSubIssueOpen, setIsAddAsSubIssueOpen] = useState(false);
const [preloadedData, setPreloadedData] = useState<
(Partial<IIssue> & { actionType: "createIssue" | "edit" | "delete" }) | undefined
>(undefined);
const router = useRouter();
const { workspaceSlug, projectId, issueId } = router.query;
const { data: activeProject } = useSWR(
workspaceSlug && projectId ? PROJECT_DETAILS(projectId as string) : null,
workspaceSlug && projectId
? () => projectService.getProject(workspaceSlug as string, projectId as string)
: null
);
const { data: issues, mutate: mutateIssues } = useSWR(
workspaceSlug && projectId
? PROJECT_ISSUES_LIST(workspaceSlug as string, projectId as string)
: null,
workspaceSlug && projectId
? () => issuesServices.getIssues(workspaceSlug as string, projectId as string)
: null
);
const { data: issueActivities, mutate: mutateIssueActivities } = useSWR(
workspaceSlug && projectId && issueId ? PROJECT_ISSUES_ACTIVITY : null,
workspaceSlug && projectId && issueId
? () =>
issuesServices.getIssueActivities(
workspaceSlug as string,
projectId as string,
issueId as string
)
: null
);
const { register, handleSubmit, reset, control, watch, setValue } = useForm<IIssue>({
defaultValues,
});
const issueDetail = issues?.results?.find((issue) => issue.id === issueId);
const prevIssue = issues?.results[issues?.results.findIndex((issue) => issue.id === issueId) - 1];
const nextIssue = issues?.results[issues?.results.findIndex((issue) => issue.id === issueId) + 1];
const subIssues = (issues && issues.results.filter((i) => i.parent === issueId)) ?? [];
const siblingIssues =
issueDetail &&
issues?.results.filter((i) => i.parent === issueDetail.parent && i.id !== issueId);
useEffect(() => {
if (issueDetail) {
mutateIssueActivities();
reset({
...issueDetail,
blockers_list:
issueDetail.blockers_list ??
issueDetail.blocker_issues?.map((issue) => issue.blocker_issue_detail?.id),
blocked_list:
issueDetail.blocked_list ??
issueDetail.blocked_issues?.map((issue) => issue.blocked_issue_detail?.id),
assignees_list:
issueDetail.assignees_list ?? issueDetail.assignee_details?.map((user) => user.id),
labels_list: issueDetail.labels_list ?? issueDetail.labels,
labels: issueDetail.labels_list ?? issueDetail.labels,
});
}
}, [issueDetail, reset, mutateIssueActivities]);
const submitChanges = useCallback(
(formData: Partial<IIssue>) => {
if (!workspaceSlug || !activeProject || !issueId) return;
mutateIssues(
(prevData) => ({
...(prevData as IssueResponse),
results: (prevData?.results ?? []).map((issue) => {
if (issue.id === issueId) return { ...issue, ...formData };
return issue;
}),
}),
false
);
const payload = {
...formData,
};
issuesServices
.patchIssue(workspaceSlug as string, projectId as string, issueId as string, payload)
.then((response) => {
mutateIssues((prevData) => ({
...(prevData as IssueResponse),
results: (prevData?.results ?? []).map((issue) => {
if (issue.id === issueId) {
return { ...issue, ...response };
}
return issue;
}),
}));
mutateIssueActivities();
})
.catch((error) => {
console.error(error);
});
},
[activeProject, workspaceSlug, issueId, projectId, mutateIssues, mutateIssueActivities]
);
const handleSubIssueRemove = (issueId: string) => {
if (workspaceSlug && activeProject) {
issuesServices
.patchIssue(workspaceSlug as string, activeProject.id, issueId, { parent: null })
.then((res) => {
mutate<IssueResponse>(
PROJECT_ISSUES_LIST(workspaceSlug as string, activeProject.id),
(prevData) => ({
...(prevData as IssueResponse),
results: (prevData?.results ?? []).map((p) =>
p.id === issueId ? { ...p, ...res } : p
),
}),
false
);
mutateIssueActivities();
})
.catch((e) => {
console.error(e);
});
}
};
return (
<AppLayout
noPadding={true}
bg="secondary"
breadcrumbs={
<Breadcrumbs>
<Breadcrumbs.BreadcrumbItem
title={`${activeProject?.name ?? "Project"} Issues`}
link={`/${workspaceSlug}/projects/${activeProject?.id}/issues`}
/>
<Breadcrumbs.BreadcrumbItem
title={`Issue ${activeProject?.identifier ?? "Project"}-${
issueDetail?.sequence_id ?? "..."
} Details`}
/>
</Breadcrumbs>
}
right={
<div className="flex items-center gap-2">
<HeaderButton
Icon={ChevronLeftIcon}
label="Previous"
className={!prevIssue ? "cursor-not-allowed opacity-70" : ""}
onClick={() => {
if (!prevIssue) return;
router.push(`/${workspaceSlug}/projects/${prevIssue.project}/issues/${prevIssue.id}`);
}}
/>
<HeaderButton
Icon={ChevronRightIcon}
disabled={!nextIssue}
label="Next"
className={!nextIssue ? "cursor-not-allowed opacity-70" : ""}
onClick={() => {
if (!nextIssue) return;
router.push(
`/${workspaceSlug}/projects/${nextIssue.project}/issues/${nextIssue?.id}`
);
}}
position="reverse"
/>
</div>
}
>
{isOpen && (
<CreateUpdateIssuesModal
isOpen={isOpen}
setIsOpen={setIsOpen}
projectId={projectId as string}
prePopulateData={{
...preloadedData,
}}
/>
)}
{isAddAsSubIssueOpen && (
<AddAsSubIssue
isOpen={isAddAsSubIssueOpen}
setIsOpen={setIsAddAsSubIssueOpen}
parent={issueDetail}
/>
)}
{issueDetail && activeProject ? (
<div className="flex h-full">
<div className="basis-2/3 space-y-5 divide-y-2 p-5">
<div className="rounded-lg">
{issueDetail.parent !== null && issueDetail.parent !== "" ? (
<div className="mb-5 flex w-min items-center gap-2 whitespace-nowrap rounded bg-gray-100 p-2 text-xs">
<Link
href={`/${workspaceSlug}/projects/${activeProject.id}/issues/${issueDetail.parent}`}
>
<a className="flex items-center gap-2">
<span
className="block h-1.5 w-1.5 rounded-full"
style={{
backgroundColor: issueDetail.state_detail.color,
}}
/>
<span className="flex-shrink-0 text-gray-600">
{activeProject.identifier}-
{issues?.results.find((i) => i.id === issueDetail.parent)?.sequence_id}
</span>
<span className="truncate font-medium">
{issues?.results
.find((i) => i.id === issueDetail.parent)
?.name.substring(0, 50)}
</span>
</a>
</Link>
<CustomMenu ellipsis optionsPosition="left">
{siblingIssues && siblingIssues.length > 0 ? (
siblingIssues.map((issue) => (
<CustomMenu.MenuItem key={issue.id}>
<Link
href={`/${workspaceSlug}/projects/${activeProject.id}/issues/${issue.id}`}
>
<a>
{activeProject.identifier}-{issue.sequence_id}
</a>
</Link>
</CustomMenu.MenuItem>
))
) : (
<CustomMenu.MenuItem className="flex items-center gap-2 whitespace-nowrap p-2 text-left text-xs text-gray-900">
No other sibling issues
</CustomMenu.MenuItem>
)}
</CustomMenu>
</div>
) : null}
<div>
<TextArea
id="name"
placeholder="Enter issue name"
name="name"
autoComplete="off"
validations={{ required: true }}
register={register}
onChange={debounce(() => {
handleSubmit(submitChanges)();
}, 5000)}
mode="transparent"
className="text-xl font-medium"
/>
<Controller
name="description"
control={control}
render={({ field: { value } }) => (
<RemirrorRichTextEditor
value={value}
placeholder="Enter Your Text..."
onBlur={(jsonValue, htmlValue) => {
setValue("description", jsonValue);
setValue("description_html", htmlValue);
handleSubmit(submitChanges)();
}}
/>
)}
/>
</div>
<div className="mt-2">
{subIssues && subIssues.length > 0 ? (
<Disclosure defaultOpen={true}>
{({ open }) => (
<>
<div className="flex items-center justify-between">
<Disclosure.Button className="flex items-center gap-1 rounded px-2 py-1 text-xs font-medium hover:bg-gray-100">
<ChevronRightIcon className={`h-3 w-3 ${open ? "rotate-90" : ""}`} />
Sub-issues{" "}
<span className="ml-1 text-gray-600">{subIssues.length}</span>
</Disclosure.Button>
{open ? (
<div className="flex items-center">
<button
type="button"
className="flex items-center gap-1 rounded px-2 py-1 text-xs font-medium hover:bg-gray-100"
onClick={() => {
setIsOpen(true);
setPreloadedData({
parent: issueDetail.id,
actionType: "createIssue",
});
}}
>
<PlusIcon className="h-3 w-3" />
Create new
</button>
<CustomMenu ellipsis>
<CustomMenu.MenuItem onClick={() => setIsAddAsSubIssueOpen(true)}>
Add an existing issue
</CustomMenu.MenuItem>
</CustomMenu>
</div>
) : null}
</div>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Disclosure.Panel className="mt-3 flex flex-col gap-y-1">
{subIssues.map((subIssue) => (
<div
key={subIssue.id}
className="group flex items-center justify-between gap-2 rounded p-2 hover:bg-gray-100"
>
<Link
href={`/${workspaceSlug}/projects/${activeProject.id}/issues/${subIssue.id}`}
>
<a className="flex items-center gap-2 rounded text-xs">
<span
className={`block h-1.5 w-1.5 rounded-full`}
style={{
backgroundColor: subIssue.state_detail.color,
}}
/>
<span className="flex-shrink-0 text-gray-600">
{activeProject.identifier}-{subIssue.sequence_id}
</span>
<span className="max-w-sm break-all font-medium">
{subIssue.name}
</span>
</a>
</Link>
<div className="opacity-0 group-hover:opacity-100">
<CustomMenu ellipsis>
<CustomMenu.MenuItem
onClick={() => handleSubIssueRemove(subIssue.id)}
>
Remove as sub-issue
</CustomMenu.MenuItem>
</CustomMenu>
</div>
</div>
))}
</Disclosure.Panel>
</Transition>
</>
)}
</Disclosure>
) : (
<CustomMenu
label={
<>
<PlusIcon className="h-3 w-3" />
Add sub-issue
</>
}
optionsPosition="left"
noBorder
>
<CustomMenu.MenuItem
onClick={() => {
setIsOpen(true);
setPreloadedData({
parent: issueDetail.id,
actionType: "createIssue",
});
}}
>
Create new
</CustomMenu.MenuItem>
<CustomMenu.MenuItem
onClick={() => {
setIsAddAsSubIssueOpen(true);
setPreloadedData({
parent: issueDetail.id,
actionType: "createIssue",
});
}}
>
Add an existing issue
</CustomMenu.MenuItem>
</CustomMenu>
)}
</div>
</div>
<div className="space-y-5 bg-secondary pt-3">
<h3 className="text-lg">Comments/Activity</h3>
<IssueActivitySection
issueActivities={issueActivities || []}
mutate={mutateIssueActivities}
/>
<AddIssueComment mutate={mutateIssueActivities} />
</div>
</div>
<div className="h-full basis-1/3 space-y-5 border-l p-5">
{/* TODO add flex-grow, if needed */}
<IssueDetailSidebar
control={control}
issueDetail={issueDetail}
submitChanges={submitChanges}
watch={watch}
/>
</div>
</div>
) : (
<Loader className="flex h-full gap-5 p-5">
<div className="basis-2/3 space-y-2">
<Loader.Item height="30px" width="40%"></Loader.Item>
<Loader.Item height="15px" width="60%" light></Loader.Item>
<Loader.Item height="15px" width="60%" light></Loader.Item>
<Loader.Item height="15px" width="40%" light></Loader.Item>
</div>
<div className="basis-1/3 space-y-3">
<Loader.Item height="30px"></Loader.Item>
<Loader.Item height="30px"></Loader.Item>
<Loader.Item height="30px"></Loader.Item>
<Loader.Item height="30px"></Loader.Item>
</div>
</Loader>
)}
</AppLayout>
);
};
export const getServerSideProps = async (ctx: NextPageContext) => {
const user = await requiredAuth(ctx.req?.headers.cookie);
const redirectAfterSignIn = ctx.req?.url;
if (!user) {
return {
redirect: {
destination: `/signin?next=${redirectAfterSignIn}`,
permanent: false,
},
};
}
return {
props: {
user,
},
};
};
export default IssueDetail;