chore: update in sub-issues component and property validation and issue loaders (#3375)

* fix: handled undefined issue_id in list layout

* chore: refactor peek overview and user role validation.

* chore: sub issues

* fix: sub issues state distribution changed

* chore: sub_issues implementation in issue detail page

* chore: fixes in cycle/ module layout.
* Fix progress chart
* Module issues's update/ delete.
* Peek Overview for Modules/ Cycle.
* Fix Cycle Filters not applying bug.

---------

Co-authored-by: Prateek Shourya <prateekshourya29@gmail.com>
Co-authored-by: NarayanBavisetti <narayan3119@gmail.com>
This commit is contained in:
guru_sainath 2024-01-16 12:46:03 +05:30 committed by sriram veeraghanta
parent 11f84a986c
commit 6a16a98b03
32 changed files with 1136 additions and 1174 deletions

View File

@ -82,7 +82,7 @@ from plane.db.models import (
from plane.bgtasks.issue_activites_task import issue_activity from plane.bgtasks.issue_activites_task import issue_activity
from plane.utils.grouper import group_results from plane.utils.grouper import group_results
from plane.utils.issue_filters import issue_filters from plane.utils.issue_filters import issue_filters
from collections import defaultdict
class IssueViewSet(WebhookMixin, BaseViewSet): class IssueViewSet(WebhookMixin, BaseViewSet):
def get_serializer_class(self): def get_serializer_class(self):
@ -784,22 +784,13 @@ class SubIssuesEndpoint(BaseAPIView):
queryset=IssueReaction.objects.select_related("actor"), queryset=IssueReaction.objects.select_related("actor"),
) )
) )
.annotate(state_group=F("state__group"))
) )
state_distribution = ( # create's a dict with state group name with their respective issue id's
State.objects.filter( result = defaultdict(list)
workspace__slug=slug, state_issue__parent_id=issue_id for sub_issue in sub_issues:
) result[sub_issue.state_group].append(str(sub_issue.id))
.annotate(state_group=F("group"))
.values("state_group")
.annotate(state_count=Count("state_group"))
.order_by("state_group")
)
result = {
item["state_group"]: item["state_count"]
for item in state_distribution
}
serializer = IssueSerializer( serializer = IssueSerializer(
sub_issues, sub_issues,
@ -831,7 +822,7 @@ class SubIssuesEndpoint(BaseAPIView):
_ = Issue.objects.bulk_update(sub_issues, ["parent"], batch_size=10) _ = Issue.objects.bulk_update(sub_issues, ["parent"], batch_size=10)
updated_sub_issues = Issue.issue_objects.filter(id__in=sub_issue_ids) updated_sub_issues = Issue.issue_objects.filter(id__in=sub_issue_ids).annotate(state_group=F("state__group"))
# Track the issue # Track the issue
_ = [ _ = [
@ -847,12 +838,25 @@ class SubIssuesEndpoint(BaseAPIView):
for sub_issue_id in sub_issue_ids for sub_issue_id in sub_issue_ids
] ]
# create's a dict with state group name with their respective issue id's
result = defaultdict(list)
for sub_issue in updated_sub_issues:
result[sub_issue.state_group].append(str(sub_issue.id))
serializer = IssueSerializer(
updated_sub_issues,
many=True,
)
return Response( return Response(
IssueSerializer(updated_sub_issues, many=True).data, {
"sub_issues": serializer.data,
"state_distribution": result,
},
status=status.HTTP_200_OK, status=status.HTTP_200_OK,
) )
class IssueLinkViewSet(BaseViewSet): class IssueLinkViewSet(BaseViewSet):
permission_classes = [ permission_classes = [
ProjectEntityPermission, ProjectEntityPermission,

View File

@ -1,11 +1,11 @@
import { TIssue } from "./issue"; import { TIssue } from "./issue";
export type TSubIssuesStateDistribution = { export type TSubIssuesStateDistribution = {
backlog: number; backlog: string[];
unstarted: number; unstarted: string[];
started: number; started: string[];
completed: number; completed: string[];
cancelled: number; cancelled: string[];
}; };
export type TIssueSubIssues = { export type TIssueSubIssues = {

View File

@ -41,7 +41,7 @@ const DashedLine = ({ series, lineGenerator, xScale, yScale }: any) =>
)); ));
const ProgressChart: React.FC<Props> = ({ distribution, startDate, endDate, totalIssues }) => { const ProgressChart: React.FC<Props> = ({ distribution, startDate, endDate, totalIssues }) => {
const chartData = Object.keys(distribution).map((key) => ({ const chartData = Object.keys(distribution ?? []).map((key) => ({
currentDate: renderFormattedDateWithoutYear(key), currentDate: renderFormattedDateWithoutYear(key),
pending: distribution[key], pending: distribution[key],
})); }));

View File

@ -183,7 +183,7 @@ export const SidebarProgressStats: React.FC<Props> = ({
)} )}
</Tab.Panel> </Tab.Panel>
<Tab.Panel as="div" className="flex h-44 w-full flex-col gap-1.5 overflow-y-auto pt-3.5"> <Tab.Panel as="div" className="flex h-44 w-full flex-col gap-1.5 overflow-y-auto pt-3.5">
{distribution.labels.length > 0 ? ( {distribution?.labels.length > 0 ? (
distribution.labels.map((label, index) => ( distribution.labels.map((label, index) => (
<SingleProgressStats <SingleProgressStats
key={label.label_id ?? `no-label-${index}`} key={label.label_id ?? `no-label-${index}`}

View File

@ -78,10 +78,16 @@ export const IssueDescriptionForm: FC<IssueDetailsProps> = (props) => {
async (formData: Partial<TIssue>) => { async (formData: Partial<TIssue>) => {
if (!formData?.name || formData?.name.length === 0 || formData?.name.length > 255) return; if (!formData?.name || formData?.name.length === 0 || formData?.name.length > 255) return;
await issueOperations.update(workspaceSlug, projectId, issueId, { await issueOperations.update(
workspaceSlug,
projectId,
issueId,
{
name: formData.name ?? "", name: formData.name ?? "",
description_html: formData.description_html ?? "<p></p>", description_html: formData.description_html ?? "<p></p>",
}); },
false
);
}, },
[workspaceSlug, projectId, issueId, issueOperations] [workspaceSlug, projectId, issueId, issueOperations]
); );

View File

@ -25,7 +25,7 @@ export const LabelListItem: FC<TLabelListItem> = (props) => {
const label = getLabelById(labelId); const label = getLabelById(labelId);
const handleLabel = async () => { const handleLabel = async () => {
if (issue) { if (issue && !disabled) {
const currentLabels = issue.label_ids.filter((_labelId) => _labelId !== labelId); const currentLabels = issue.label_ids.filter((_labelId) => _labelId !== labelId);
await labelOperations.updateIssue(workspaceSlug, projectId, issueId, { label_ids: currentLabels }); await labelOperations.updateIssue(workspaceSlug, projectId, issueId, { label_ids: currentLabels });
} }

View File

@ -107,7 +107,7 @@ export const IssueLinkRoot: FC<TIssueLinkRoot> = (props) => {
linkOperations={handleLinkOperations} linkOperations={handleLinkOperations}
/> />
<div className={`py-1 text-xs ${disabled ? "opacity-60" : ""}`}> <div className="py-1 text-xs">
<div className="flex items-center justify-between gap-2"> <div className="flex items-center justify-between gap-2">
<h4>Links</h4> <h4>Links</h4>
{!disabled && ( {!disabled && (

View File

@ -87,10 +87,9 @@ export const IssueMainContent: React.FC<Props> = observer((props) => {
<SubIssuesRoot <SubIssuesRoot
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
projectId={projectId} projectId={projectId}
issueId={issueId} parentIssueId={issueId}
currentUser={currentUser} currentUser={currentUser}
is_archived={is_archived} disabled={!is_editable}
is_editable={is_editable}
/> />
)} )}
</div> </div>

View File

@ -23,10 +23,10 @@ export const IssueParentSiblings: FC<TIssueParentSiblings> = (props) => {
} = useIssueDetail(); } = useIssueDetail();
const { isLoading } = useSWR( const { isLoading } = useSWR(
peekIssue && parentIssue peekIssue && parentIssue && parentIssue.project_id
? `ISSUE_PARENT_CHILD_ISSUES_${peekIssue?.workspaceSlug}_${parentIssue.project_id}_${parentIssue.id}` ? `ISSUE_PARENT_CHILD_ISSUES_${peekIssue?.workspaceSlug}_${parentIssue.project_id}_${parentIssue.id}`
: null, : null,
peekIssue && parentIssue peekIssue && parentIssue && parentIssue.project_id
? () => fetchSubIssues(peekIssue?.workspaceSlug, parentIssue.project_id, parentIssue.id) ? () => fetchSubIssues(peekIssue?.workspaceSlug, parentIssue.project_id, parentIssue.id)
: null : null
); );

View File

@ -1,6 +1,7 @@
import { FC, useMemo } from "react"; import { FC, useMemo } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
// components // components
import { IssuePeekOverview } from "components/issues";
import { IssueMainContent } from "./main-content"; import { IssueMainContent } from "./main-content";
import { IssueDetailsSidebar } from "./sidebar"; import { IssueDetailsSidebar } from "./sidebar";
// ui // ui
@ -8,16 +9,23 @@ import { EmptyState } from "components/common";
// images // images
import emptyIssue from "public/empty-state/issue.svg"; import emptyIssue from "public/empty-state/issue.svg";
// hooks // hooks
import { useIssueDetail, useUser } from "hooks/store"; import { useIssueDetail, useIssues, useUser } from "hooks/store";
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
// types // types
import { TIssue } from "@plane/types"; import { TIssue } from "@plane/types";
// constants // constants
import { EUserProjectRoles } from "constants/project"; import { EUserProjectRoles } from "constants/project";
import { EIssuesStoreType } from "constants/issue";
export type TIssueOperations = { export type TIssueOperations = {
fetch: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>; fetch: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>;
update: (workspaceSlug: string, projectId: string, issueId: string, data: Partial<TIssue>) => Promise<void>; update: (
workspaceSlug: string,
projectId: string,
issueId: string,
data: Partial<TIssue>,
showToast?: boolean
) => Promise<void>;
remove: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>; remove: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>;
addIssueToCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => Promise<void>; addIssueToCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => Promise<void>;
removeIssueFromCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueId: string) => Promise<void>; removeIssueFromCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueId: string) => Promise<void>;
@ -47,6 +55,9 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
addIssueToModule, addIssueToModule,
removeIssueFromModule, removeIssueFromModule,
} = useIssueDetail(); } = useIssueDetail();
const {
issues: { removeIssue: removeArchivedIssue },
} = useIssues(EIssuesStoreType.ARCHIVED);
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
const { const {
membership: { currentProjectRole }, membership: { currentProjectRole },
@ -61,14 +72,22 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
console.error("Error fetching the parent issue"); console.error("Error fetching the parent issue");
} }
}, },
update: async (workspaceSlug: string, projectId: string, issueId: string, data: Partial<TIssue>) => { update: async (
workspaceSlug: string,
projectId: string,
issueId: string,
data: Partial<TIssue>,
showToast: boolean = true
) => {
try { try {
await updateIssue(workspaceSlug, projectId, issueId, data); await updateIssue(workspaceSlug, projectId, issueId, data);
if (showToast) {
setToastAlert({ setToastAlert({
title: "Issue updated successfully", title: "Issue updated successfully",
type: "success", type: "success",
message: "Issue updated successfully", message: "Issue updated successfully",
}); });
}
} catch (error) { } catch (error) {
setToastAlert({ setToastAlert({
title: "Issue update failed", title: "Issue update failed",
@ -79,7 +98,8 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
}, },
remove: async (workspaceSlug: string, projectId: string, issueId: string) => { remove: async (workspaceSlug: string, projectId: string, issueId: string) => {
try { try {
await removeIssue(workspaceSlug, projectId, issueId); if (is_archived) await removeArchivedIssue(workspaceSlug, projectId, issueId);
else await removeIssue(workspaceSlug, projectId, issueId);
setToastAlert({ setToastAlert({
title: "Issue deleted successfully", title: "Issue deleted successfully",
type: "success", type: "success",
@ -159,9 +179,11 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
}, },
}), }),
[ [
is_archived,
fetchIssue, fetchIssue,
updateIssue, updateIssue,
removeIssue, removeIssue,
removeArchivedIssue,
addIssueToCycle, addIssueToCycle,
removeIssueFromCycle, removeIssueFromCycle,
addIssueToModule, addIssueToModule,
@ -170,9 +192,9 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
] ]
); );
// Issue details // issue details
const issue = getIssueById(issueId); const issue = getIssueById(issueId);
// Check if issue is editable, based on user role // checking if issue is editable, based on user role
const is_editable = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER; const is_editable = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
return ( return (
@ -211,6 +233,9 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = (props) => {
</div> </div>
</div> </div>
)} )}
{/* peek overview */}
<IssuePeekOverview />
</> </>
); );
}; };

View File

@ -162,7 +162,7 @@ export const IssueDetailsSidebar: React.FC<Props> = observer((props) => {
/> />
)} )}
{/* {(fieldsToShow.includes("all") || fieldsToShow.includes("link")) && ( {(fieldsToShow.includes("all") || fieldsToShow.includes("link")) && (
<button <button
type="button" type="button"
className="rounded-md border border-custom-border-200 p-2 shadow-sm duration-300 hover:bg-custom-background-90 focus:border-custom-primary focus:outline-none focus:ring-1 focus:ring-custom-primary" className="rounded-md border border-custom-border-200 p-2 shadow-sm duration-300 hover:bg-custom-background-90 focus:border-custom-primary focus:outline-none focus:ring-1 focus:ring-custom-primary"
@ -170,9 +170,9 @@ export const IssueDetailsSidebar: React.FC<Props> = observer((props) => {
> >
<LinkIcon className="h-3.5 w-3.5" /> <LinkIcon className="h-3.5 w-3.5" />
</button> </button>
)} */} )}
{/* {isAllowed && (fieldsToShow.includes("all") || fieldsToShow.includes("delete")) && ( {is_editable && (fieldsToShow.includes("all") || fieldsToShow.includes("delete")) && (
<button <button
type="button" type="button"
className="rounded-md border border-red-500 p-2 text-red-500 shadow-sm duration-300 hover:bg-red-500/20 focus:outline-none" className="rounded-md border border-red-500 p-2 text-red-500 shadow-sm duration-300 hover:bg-red-500/20 focus:outline-none"
@ -180,7 +180,7 @@ export const IssueDetailsSidebar: React.FC<Props> = observer((props) => {
> >
<Trash2 className="h-3.5 w-3.5" /> <Trash2 className="h-3.5 w-3.5" />
</button> </button>
)} */} )}
</div> </div>
</div> </div>

View File

@ -25,12 +25,12 @@ export const ModuleListLayout: React.FC = observer(() => {
[EIssueActions.UPDATE]: async (issue: TIssue) => { [EIssueActions.UPDATE]: async (issue: TIssue) => {
if (!workspaceSlug || !moduleId) return; if (!workspaceSlug || !moduleId) return;
await issues.updateIssue(workspaceSlug.toString(), issue.project_id, issue.id, issue); await issues.updateIssue(workspaceSlug.toString(), issue.project_id, issue.id, issue, moduleId.toString());
}, },
[EIssueActions.DELETE]: async (issue: TIssue) => { [EIssueActions.DELETE]: async (issue: TIssue) => {
if (!workspaceSlug || !moduleId) return; if (!workspaceSlug || !moduleId) return;
await issues.removeIssue(workspaceSlug.toString(), issue.project_id, issue.id); await issues.removeIssue(workspaceSlug.toString(), issue.project_id, issue.id, moduleId.toString());
}, },
[EIssueActions.REMOVE]: async (issue: TIssue) => { [EIssueActions.REMOVE]: async (issue: TIssue) => {
if (!workspaceSlug || !moduleId) return; if (!workspaceSlug || !moduleId) return;

View File

@ -13,6 +13,7 @@ import {
CycleKanBanLayout, CycleKanBanLayout,
CycleListLayout, CycleListLayout,
CycleSpreadsheetLayout, CycleSpreadsheetLayout,
IssuePeekOverview,
} from "components/issues"; } from "components/issues";
import { TransferIssues, TransferIssuesModal } from "components/cycles"; import { TransferIssues, TransferIssuesModal } from "components/cycles";
// ui // ui
@ -73,6 +74,7 @@ export const CycleLayoutRoot: React.FC = observer(() => {
cycleId={cycleId.toString()} cycleId={cycleId.toString()}
/> />
) : ( ) : (
<>
<div className="h-full w-full overflow-auto"> <div className="h-full w-full overflow-auto">
{activeLayout === "list" ? ( {activeLayout === "list" ? (
<CycleListLayout /> <CycleListLayout />
@ -86,6 +88,9 @@ export const CycleLayoutRoot: React.FC = observer(() => {
<CycleSpreadsheetLayout /> <CycleSpreadsheetLayout />
) : null} ) : null}
</div> </div>
{/* peek overview */}
<IssuePeekOverview />
</>
)} )}
</> </>
)} )}

View File

@ -6,6 +6,7 @@ import useSWR from "swr";
import { useIssues } from "hooks/store"; import { useIssues } from "hooks/store";
// components // components
import { import {
IssuePeekOverview,
ModuleAppliedFiltersRoot, ModuleAppliedFiltersRoot,
ModuleCalendarLayout, ModuleCalendarLayout,
ModuleEmptyState, ModuleEmptyState,
@ -16,6 +17,7 @@ import {
} from "components/issues"; } from "components/issues";
// ui // ui
import { Spinner } from "@plane/ui"; import { Spinner } from "@plane/ui";
// constants
import { EIssuesStoreType } from "constants/issue"; import { EIssuesStoreType } from "constants/issue";
export const ModuleLayoutRoot: React.FC = observer(() => { export const ModuleLayoutRoot: React.FC = observer(() => {
@ -62,6 +64,7 @@ export const ModuleLayoutRoot: React.FC = observer(() => {
moduleId={moduleId.toString()} moduleId={moduleId.toString()}
/> />
) : ( ) : (
<>
<div className="h-full w-full overflow-auto"> <div className="h-full w-full overflow-auto">
{activeLayout === "list" ? ( {activeLayout === "list" ? (
<ModuleListLayout /> <ModuleListLayout />
@ -75,6 +78,9 @@ export const ModuleLayoutRoot: React.FC = observer(() => {
<ModuleSpreadsheetLayout /> <ModuleSpreadsheetLayout />
) : null} ) : null}
</div> </div>
{/* peek overview */}
<IssuePeekOverview />
</>
)} )}
</> </>
)} )}

View File

@ -30,7 +30,11 @@ export const ProjectLayoutRoot: FC = observer(() => {
useSWR(workspaceSlug && projectId ? `PROJECT_ISSUES_${workspaceSlug}_${projectId}` : null, async () => { useSWR(workspaceSlug && projectId ? `PROJECT_ISSUES_${workspaceSlug}_${projectId}` : null, async () => {
if (workspaceSlug && projectId) { if (workspaceSlug && projectId) {
await issuesFilter?.fetchFilters(workspaceSlug.toString(), projectId.toString()); await issuesFilter?.fetchFilters(workspaceSlug.toString(), projectId.toString());
await issues?.fetchIssues(workspaceSlug.toString(), projectId.toString(), issues?.groupedIssueIds ? "mutation" : "init-loader"); await issues?.fetchIssues(
workspaceSlug.toString(),
projectId.toString(),
issues?.groupedIssueIds ? "mutation" : "init-loader"
);
} }
}); });

View File

@ -1,4 +1,4 @@
import React, { FC, useState, useRef } from "react"; import React, { FC, useState, useRef, useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
@ -6,7 +6,7 @@ import { LayoutPanelTop, Sparkle, X } from "lucide-react";
// editor // editor
import { RichTextEditorWithRef } from "@plane/rich-text-editor"; import { RichTextEditorWithRef } from "@plane/rich-text-editor";
// hooks // hooks
import { useApplication, useEstimate, useMention, useProject } from "hooks/store"; import { useApplication, useEstimate, useIssueDetail, useMention, useProject } from "hooks/store";
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
// services // services
import { AIService } from "services/ai.service"; import { AIService } from "services/ai.service";
@ -85,6 +85,9 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
const { getProjectById } = useProject(); const { getProjectById } = useProject();
const { areEstimatesEnabledForProject } = useEstimate(); const { areEstimatesEnabledForProject } = useEstimate();
const { mentionHighlights, mentionSuggestions } = useMention(); const { mentionHighlights, mentionSuggestions } = useMention();
const {
issue: { getIssueById },
} = useIssueDetail();
// toast alert // toast alert
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
// form info // form info
@ -179,6 +182,28 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
const projectDetails = getProjectById(projectId); const projectDetails = getProjectById(projectId);
// executing this useEffect when the parent_id coming from the component prop
useEffect(() => {
const parentId = watch("parent_id") || undefined;
if (!parentId) return;
if (parentId === selectedParentIssue?.id || selectedParentIssue) return;
const issue = getIssueById(parentId);
if (!issue) return;
const projectDetails = getProjectById(issue.project_id);
if (!projectDetails) return;
setSelectedParentIssue({
id: issue.id,
name: issue.name,
project_id: issue.project_id,
project__identifier: projectDetails.identifier,
project__name: projectDetails.name,
sequence_id: issue.sequence_id,
} as ISearchIssueResponse);
}, [watch, getIssueById, getProjectById, selectedParentIssue]);
return ( return (
<> <>
{projectId && ( {projectId && (

View File

@ -18,7 +18,7 @@ export interface IssuesModalProps {
data?: Partial<TIssue>; data?: Partial<TIssue>;
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onSubmit?: (res: Partial<TIssue>) => Promise<void>; onSubmit?: (res: TIssue) => Promise<void>;
withDraftIssueWrapper?: boolean; withDraftIssueWrapper?: boolean;
} }
@ -58,52 +58,46 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer((prop
onClose(); onClose();
}; };
const handleCreateIssue = async (payload: Partial<TIssue>): Promise<TIssue | null> => { const handleCreateIssue = async (payload: Partial<TIssue>): Promise<TIssue | undefined> => {
if (!workspaceSlug || !payload.project_id) return null; if (!workspaceSlug || !payload.project_id) return undefined;
await createIssue(workspaceSlug.toString(), payload.project_id, payload) try {
.then(async (res) => { const response = await createIssue(workspaceSlug.toString(), payload.project_id, payload);
setToastAlert({ setToastAlert({
type: "success", type: "success",
title: "Success!", title: "Success!",
message: "Issue created successfully.", message: "Issue created successfully.",
}); });
!createMore && handleClose(); !createMore && handleClose();
return res; return response;
}) } catch (error) {
.catch(() => {
setToastAlert({ setToastAlert({
type: "error", type: "error",
title: "Error!", title: "Error!",
message: "Issue could not be created. Please try again.", message: "Issue could not be created. Please try again.",
}); });
}); }
return null;
}; };
const handleUpdateIssue = async (payload: Partial<TIssue>): Promise<TIssue | null> => { const handleUpdateIssue = async (payload: Partial<TIssue>): Promise<TIssue | undefined> => {
if (!workspaceSlug || !payload.project_id || !data?.id) return null; if (!workspaceSlug || !payload.project_id || !data?.id) return undefined;
await updateIssue(workspaceSlug.toString(), payload.project_id, data.id, payload) try {
.then((res) => { const response = await updateIssue(workspaceSlug.toString(), payload.project_id, data.id, payload);
setToastAlert({ setToastAlert({
type: "success", type: "success",
title: "Success!", title: "Success!",
message: "Issue updated successfully.", message: "Issue updated successfully.",
}); });
handleClose(); handleClose();
return { ...payload, ...res }; return response;
}) } catch (error) {
.catch(() => {
setToastAlert({ setToastAlert({
type: "error", type: "error",
title: "Error!", title: "Error!",
message: "Issue could not be updated. Please try again.", message: "Issue could not be created. Please try again.",
}); });
}); }
return null;
}; };
const handleFormSubmit = async (formData: Partial<TIssue>) => { const handleFormSubmit = async (formData: Partial<TIssue>) => {
@ -114,7 +108,7 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer((prop
description_html: formData.description_html ?? "<p></p>", description_html: formData.description_html ?? "<p></p>",
}; };
let res: TIssue | null = null; let res: TIssue | undefined = undefined;
if (!data?.id) res = await handleCreateIssue(payload); if (!data?.id) res = await handleCreateIssue(payload);
else res = await handleUpdateIssue(payload); else res = await handleUpdateIssue(payload);
@ -126,7 +120,7 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer((prop
if (formData.module_id && res && (!data?.id || formData.module_id !== data?.module_id)) if (formData.module_id && res && (!data?.id || formData.module_id !== data?.module_id))
await addIssueToModule(workspaceSlug.toString(), formData.project_id, formData.module_id, [res.id]); await addIssueToModule(workspaceSlug.toString(), formData.project_id, formData.module_id, [res.id]);
if (res && onSubmit) await onSubmit(res); if (res != undefined && onSubmit) await onSubmit(res);
}; };
const handleFormChange = (formData: Partial<TIssue> | null) => setChangesMade(formData); const handleFormChange = (formData: Partial<TIssue> | null) => setChangesMade(formData);

View File

@ -1,133 +1,32 @@
import { ChangeEvent, FC, useCallback, useEffect, useState } from "react"; import { FC } from "react";
import { Controller, useForm } from "react-hook-form";
import debounce from "lodash/debounce";
// packages
import { RichTextEditor } from "@plane/rich-text-editor";
// hooks // hooks
import { useMention, useProject, useUser } from "hooks/store"; import { useIssueDetail, useProject, useUser } from "hooks/store";
import useReloadConfirmations from "hooks/use-reload-confirmation";
// components // components
import { IssuePeekOverviewReactions } from "components/issues"; import { IssueDescriptionForm, TIssueOperations } from "components/issues";
// ui import { IssueReaction } from "../issue-detail/reactions";
import { TextArea } from "@plane/ui";
// types
import { TIssue, IUser } from "@plane/types";
// services
import { FileService } from "services/file.service";
// constants
import { EUserProjectRoles } from "constants/project";
const fileService = new FileService();
interface IPeekOverviewIssueDetails { interface IPeekOverviewIssueDetails {
workspaceSlug: string; workspaceSlug: string;
issue: TIssue; projectId: string;
issueReactions: any; issueId: string;
user: IUser | null; issueOperations: TIssueOperations;
issueUpdate: (issue: Partial<TIssue>) => void; is_archived: boolean;
issueReactionCreate: (reaction: string) => void; disabled: boolean;
issueReactionRemove: (reaction: string) => void;
isSubmitting: "submitting" | "submitted" | "saved"; isSubmitting: "submitting" | "submitted" | "saved";
setIsSubmitting: (value: "submitting" | "submitted" | "saved") => void; setIsSubmitting: (value: "submitting" | "submitted" | "saved") => void;
} }
export const PeekOverviewIssueDetails: FC<IPeekOverviewIssueDetails> = (props) => { export const PeekOverviewIssueDetails: FC<IPeekOverviewIssueDetails> = (props) => {
const { const { workspaceSlug, projectId, issueId, issueOperations, disabled, isSubmitting, setIsSubmitting } = props;
workspaceSlug,
issue,
issueReactions,
user,
issueUpdate,
issueReactionCreate,
issueReactionRemove,
isSubmitting,
setIsSubmitting,
} = props;
// states
const [characterLimit, setCharacterLimit] = useState(false);
// store hooks // store hooks
const {
membership: { currentProjectRole },
} = useUser();
const { mentionHighlights, mentionSuggestions } = useMention();
const { getProjectById } = useProject(); const { getProjectById } = useProject();
// derived values const { currentUser } = useUser();
const isAllowed = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
// toast alert
const { setShowAlert } = useReloadConfirmations();
// form info
const { const {
handleSubmit, issue: { getIssueById },
watch, } = useIssueDetail();
reset, // derived values
control, const issue = getIssueById(issueId);
formState: { errors }, if (!issue) return <></>;
} = useForm<TIssue>({
defaultValues: {
name: issue.name,
description_html: issue.description_html,
},
});
const handleDescriptionFormSubmit = useCallback(
async (formData: Partial<TIssue>) => {
if (!formData?.name || formData?.name.length === 0 || formData?.name.length > 255) return;
await issueUpdate({
...issue,
name: formData.name ?? "",
description_html: formData.description_html ?? "<p></p>",
});
},
[issue, issueUpdate]
);
const [localTitleValue, setLocalTitleValue] = useState("");
const [localIssueDescription, setLocalIssueDescription] = useState({
id: issue.id,
description_html: issue.description_html,
});
// adding issue.description_html or issue.name to dependency array causes
// editor rerendering on every save
useEffect(() => {
if (issue.id) {
setLocalIssueDescription({ id: issue.id, description_html: issue.description_html });
setLocalTitleValue(issue.name);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [issue.id]); // TODO: Verify the exhaustive-deps warning
// ADDING handleDescriptionFormSubmit TO DEPENDENCY ARRAY PRODUCES ADVERSE EFFECTS
// TODO: Verify the exhaustive-deps warning
// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedFormSave = useCallback(
debounce(async () => {
handleSubmit(handleDescriptionFormSubmit)().finally(() => setIsSubmitting("submitted"));
}, 1500),
[handleSubmit]
);
useEffect(() => {
if (isSubmitting === "submitted") {
setShowAlert(false);
setTimeout(async () => {
setIsSubmitting("saved");
}, 2000);
} else if (isSubmitting === "submitting") {
setShowAlert(true);
}
}, [isSubmitting, setShowAlert, setIsSubmitting]);
// reset form values
useEffect(() => {
if (!issue) return;
reset({
...issue,
});
}, [issue, reset]);
const projectDetails = getProjectById(issue?.project_id); const projectDetails = getProjectById(issue?.project_id);
return ( return (
@ -135,82 +34,24 @@ export const PeekOverviewIssueDetails: FC<IPeekOverviewIssueDetails> = (props) =
<span className="text-base font-medium text-custom-text-400"> <span className="text-base font-medium text-custom-text-400">
{projectDetails?.identifier}-{issue?.sequence_id} {projectDetails?.identifier}-{issue?.sequence_id}
</span> </span>
<IssueDescriptionForm
<div className="relative"> workspaceSlug={workspaceSlug}
{isAllowed ? ( projectId={projectId}
<Controller issueId={issueId}
name="name" setIsSubmitting={(value) => setIsSubmitting(value)}
control={control} isSubmitting={isSubmitting}
render={({ field: { onChange } }) => ( issue={issue}
<TextArea issueOperations={issueOperations}
id="name" disabled={disabled}
name="name" />
value={localTitleValue} {currentUser && (
placeholder="Enter issue name" <IssueReaction
onFocus={() => setCharacterLimit(true)} workspaceSlug={workspaceSlug}
onChange={(e: ChangeEvent<HTMLTextAreaElement>) => { projectId={projectId}
setCharacterLimit(false); issueId={issueId}
setIsSubmitting("submitting"); currentUser={currentUser}
setLocalTitleValue(e.target.value);
onChange(e.target.value);
debouncedFormSave();
}}
required={true}
className="min-h-10 block w-full resize-none overflow-hidden rounded border-none bg-transparent !p-0 text-xl outline-none ring-0 focus:!px-3 focus:!py-2 focus:ring-1 focus:ring-custom-primary"
hasError={Boolean(errors?.name)}
role="textbox"
disabled={!true}
/> />
)} )}
/>
) : (
<h4 className="break-words text-2xl font-semibold">{issue.name}</h4>
)}
{characterLimit && true && (
<div className="pointer-events-none absolute bottom-1 right-1 z-[2] rounded bg-custom-background-100 p-0.5 text-xs text-custom-text-200">
<span className={`${watch("name").length === 0 || watch("name").length > 255 ? "text-red-500" : ""}`}>
{watch("name").length}
</span>
/255
</div>
)}
</div>
<span>{errors.name ? errors.name.message : null}</span>
<div className="relative">
<Controller
name="description_html"
control={control}
render={({ field: { onChange } }) => (
<RichTextEditor
cancelUploadImage={fileService.cancelUpload}
uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
deleteFile={fileService.deleteImage}
restoreFile={fileService.restoreImage}
value={localIssueDescription.description_html}
rerenderOnPropsChange={localIssueDescription}
setShouldShowAlert={setShowAlert}
setIsSubmitting={setIsSubmitting}
dragDropEnabled
customClassName={isAllowed ? "min-h-[150px] shadow-sm" : "!p-0 !pt-2 text-custom-text-200"}
noBorder={!isAllowed}
onChange={(description: Object, description_html: string) => {
setShowAlert(true);
setIsSubmitting("submitting");
onChange(description_html);
debouncedFormSave();
}}
mentionSuggestions={mentionSuggestions}
mentionHighlights={mentionHighlights}
/>
)}
/>
</div>
<IssuePeekOverviewReactions
issueReactions={issueReactions}
user={user}
issueReactionCreate={issueReactionCreate}
issueReactionRemove={issueReactionRemove}
/>
</> </>
); );
}; };

View File

@ -1,61 +1,40 @@
import { FC } from "react"; import { FC } from "react";
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { CalendarDays, Signal, Tag, Triangle, LayoutPanelTop } from "lucide-react"; import { CalendarDays, Signal, Tag, Triangle, LayoutPanelTop } from "lucide-react";
// hooks // hooks
import { useProject, useUser } from "hooks/store"; import { useIssueDetail, useProject } from "hooks/store";
// ui icons // ui icons
import { DiceIcon, DoubleCircleIcon, UserGroupIcon, ContrastIcon } from "@plane/ui"; import { DiceIcon, DoubleCircleIcon, UserGroupIcon, ContrastIcon } from "@plane/ui";
import { IssueLinkRoot, IssueCycleSelect, IssueModuleSelect, IssueParentSelect, IssueLabel } from "components/issues"; import {
IssueLinkRoot,
IssueCycleSelect,
IssueModuleSelect,
IssueParentSelect,
IssueLabel,
TIssueOperations,
} from "components/issues";
import { EstimateDropdown, PriorityDropdown, ProjectMemberDropdown, StateDropdown } from "components/dropdowns"; import { EstimateDropdown, PriorityDropdown, ProjectMemberDropdown, StateDropdown } from "components/dropdowns";
// components // components
import { CustomDatePicker } from "components/ui"; import { CustomDatePicker } from "components/ui";
// types
import { TIssue, TIssuePriorities } from "@plane/types";
// constants
// import { EUserProjectRoles } from "constants/project";
interface IPeekOverviewProperties { interface IPeekOverviewProperties {
issue: TIssue; workspaceSlug: string;
issueUpdate: (issue: Partial<TIssue>) => void; projectId: string;
disableUserActions: boolean; issueId: string;
issueOperations: any; disabled: boolean;
issueOperations: TIssueOperations;
} }
export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((props) => { export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((props) => {
const { issue, issueUpdate, disableUserActions, issueOperations } = props; const { workspaceSlug, projectId, issueId, issueOperations, disabled } = props;
// store hooks // store hooks
const {
membership: { currentProjectRole },
} = useUser();
const { getProjectById } = useProject(); const { getProjectById } = useProject();
// router const {
const router = useRouter(); issue: { getIssueById },
const { workspaceSlug, projectId } = router.query; } = useIssueDetail();
// derived values
const uneditable = currentProjectRole ? [5, 10].includes(currentProjectRole) : false; const issue = getIssueById(issueId);
// const isAllowed = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER; if (!issue) return <></>;
const handleState = (_state: string) => {
issueUpdate({ ...issue, state_id: _state });
};
const handlePriority = (_priority: TIssuePriorities) => {
issueUpdate({ ...issue, priority: _priority });
};
const handleAssignee = (_assignees: string[]) => {
issueUpdate({ ...issue, assignee_ids: _assignees });
};
const handleEstimate = (_estimate: number | null) => {
issueUpdate({ ...issue, estimate_point: _estimate });
};
const handleStartDate = (_startDate: string | null) => {
issueUpdate({ ...issue, start_date: _startDate || undefined });
};
const handleTargetDate = (_targetDate: string | null) => {
issueUpdate({ ...issue, target_date: _targetDate || undefined });
};
const projectDetails = getProjectById(issue.project_id); const projectDetails = getProjectById(issue.project_id);
const isEstimateEnabled = projectDetails?.estimate; const isEstimateEnabled = projectDetails?.estimate;
@ -68,7 +47,7 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
return ( return (
<> <>
<div className="flex flex-col"> <div className="flex flex-col">
<div className="flex w-full flex-col gap-5 py-5"> <div className={`flex w-full flex-col gap-5 py-5 ${disabled ? "opacity-60" : ""}`}>
{/* state */} {/* state */}
<div className="flex w-full items-center gap-2"> <div className="flex w-full items-center gap-2">
<div className="flex w-40 flex-shrink-0 items-center gap-2 text-sm"> <div className="flex w-40 flex-shrink-0 items-center gap-2 text-sm">
@ -77,10 +56,10 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div> <div>
<StateDropdown <StateDropdown
value={issue?.state_id || ""} value={issue?.state_id ?? undefined}
onChange={handleState} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { state_id: val })}
projectId={issue.project_id} projectId={projectId?.toString() ?? ""}
disabled={disableUserActions} disabled={disabled}
buttonVariant="background-with-text" buttonVariant="background-with-text"
/> />
</div> </div>
@ -94,14 +73,14 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div className="h-5 sm:w-1/2"> <div className="h-5 sm:w-1/2">
<ProjectMemberDropdown <ProjectMemberDropdown
value={issue.assignee_ids} value={issue?.assignee_ids ?? undefined}
onChange={handleAssignee} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { assignee_ids: val })}
disabled={disableUserActions} disabled={disabled}
projectId={projectId?.toString() ?? ""} projectId={projectId?.toString() ?? ""}
placeholder="Assignees" placeholder="Assignees"
multiple multiple
buttonVariant={issue.assignee_ids?.length > 0 ? "transparent-without-text" : "background-with-text"} buttonVariant={issue?.assignee_ids?.length > 0 ? "transparent-without-text" : "background-with-text"}
buttonClassName={issue.assignee_ids?.length > 0 ? "hover:bg-transparent px-0" : ""} buttonClassName={issue?.assignee_ids?.length > 0 ? "hover:bg-transparent px-0" : ""}
/> />
</div> </div>
</div> </div>
@ -114,9 +93,9 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div className="h-5"> <div className="h-5">
<PriorityDropdown <PriorityDropdown
value={issue.priority || ""} value={issue?.priority || undefined}
onChange={handlePriority} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { priority: val })}
disabled={disableUserActions} disabled={disabled}
buttonVariant="background-with-text" buttonVariant="background-with-text"
/> />
</div> </div>
@ -131,10 +110,10 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div> <div>
<EstimateDropdown <EstimateDropdown
value={issue.estimate_point} value={issue?.estimate_point || null}
onChange={handleEstimate} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { estimate_point: val })}
projectId={issue.project_id} projectId={projectId}
disabled={disableUserActions} disabled={disabled}
buttonVariant="background-with-text" buttonVariant="background-with-text"
/> />
</div> </div>
@ -150,11 +129,11 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
<div> <div>
<CustomDatePicker <CustomDatePicker
placeholder="Start date" placeholder="Start date"
value={issue.start_date} value={issue.start_date || undefined}
onChange={handleStartDate} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { start_date: val })}
className="!rounded border-none bg-custom-background-80 !px-2.5 !py-0.5" className="border-none bg-custom-background-80"
maxDate={maxDate ?? undefined} maxDate={maxDate ?? undefined}
disabled={disableUserActions} disabled={disabled}
/> />
</div> </div>
</div> </div>
@ -168,11 +147,11 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
<div> <div>
<CustomDatePicker <CustomDatePicker
placeholder="Due date" placeholder="Due date"
value={issue.target_date} value={issue.target_date || undefined}
onChange={handleTargetDate} onChange={(val) => issueOperations.update(workspaceSlug, projectId, issueId, { target_date: val })}
className="!rounded border-none bg-custom-background-80 !px-2.5 !py-0.5" className="border-none bg-custom-background-80"
minDate={minDate ?? undefined} minDate={minDate ?? undefined}
disabled={disableUserActions} disabled={disabled}
/> />
</div> </div>
</div> </div>
@ -185,11 +164,11 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div> <div>
<IssueParentSelect <IssueParentSelect
workspaceSlug={workspaceSlug?.toString() ?? ""} workspaceSlug={workspaceSlug}
projectId={projectId?.toString() ?? ""} projectId={projectId}
issueId={issue?.id} issueId={issueId}
issueOperations={issueOperations} issueOperations={issueOperations}
disabled={disableUserActions} disabled={disabled}
/> />
</div> </div>
</div> </div>
@ -197,7 +176,7 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
<span className="border-t border-custom-border-200" /> <span className="border-t border-custom-border-200" />
<div className="flex w-full flex-col gap-5 py-5"> <div className={`flex w-full flex-col gap-5 py-5 ${disabled ? "opacity-60" : ""}`}>
{projectDetails?.cycle_view && ( {projectDetails?.cycle_view && (
<div className="flex w-full items-center gap-2"> <div className="flex w-full items-center gap-2">
<div className="flex w-40 flex-shrink-0 items-center gap-2 text-sm"> <div className="flex w-40 flex-shrink-0 items-center gap-2 text-sm">
@ -206,11 +185,11 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div> <div>
<IssueCycleSelect <IssueCycleSelect
workspaceSlug={workspaceSlug?.toString() ?? ""} workspaceSlug={workspaceSlug}
projectId={projectId?.toString() ?? ""} projectId={projectId}
issueId={issue?.id} issueId={issueId}
issueOperations={issueOperations} issueOperations={issueOperations}
disabled={disableUserActions} disabled={disabled}
/> />
</div> </div>
</div> </div>
@ -224,11 +203,11 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
</div> </div>
<div> <div>
<IssueModuleSelect <IssueModuleSelect
workspaceSlug={workspaceSlug?.toString() ?? ""} workspaceSlug={workspaceSlug}
projectId={projectId?.toString() ?? ""} projectId={projectId}
issueId={issue?.id} issueId={issueId}
issueOperations={issueOperations} issueOperations={issueOperations}
disabled={disableUserActions} disabled={disabled}
/> />
</div> </div>
</div> </div>
@ -240,12 +219,7 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
<p>Label</p> <p>Label</p>
</div> </div>
<div className="flex w-full flex-col gap-3"> <div className="flex w-full flex-col gap-3">
<IssueLabel <IssueLabel workspaceSlug={workspaceSlug} projectId={projectId} issueId={issueId} disabled={disabled} />
workspaceSlug={workspaceSlug?.toString() ?? ""}
projectId={projectId?.toString() ?? ""}
issueId={issue?.id}
disabled={uneditable}
/>
</div> </div>
</div> </div>
</div> </div>
@ -253,11 +227,7 @@ export const PeekOverviewProperties: FC<IPeekOverviewProperties> = observer((pro
<span className="border-t border-custom-border-200" /> <span className="border-t border-custom-border-200" />
<div className="w-full pt-3"> <div className="w-full pt-3">
<IssueLinkRoot <IssueLinkRoot workspaceSlug={workspaceSlug} projectId={projectId} issueId={issueId} disabled={disabled} />
workspaceSlug={workspaceSlug?.toString() ?? ""}
projectId={projectId?.toString() ?? ""}
issueId={issue?.id}
/>
</div> </div>
</div> </div>
</> </>

View File

@ -1,14 +1,10 @@
import { FC, Fragment, useEffect, useState, useMemo } from "react"; import { FC, Fragment, useEffect, useState, useMemo } from "react";
// router
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
// hooks // hooks
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
import { useIssueDetail, useIssues, useMember, useProject, useUser } from "hooks/store"; import { useIssueDetail, useIssues, useMember, useUser } from "hooks/store";
// components // components
import { IssueView } from "components/issues"; import { IssueView } from "components/issues";
// helpers
import { copyUrlToClipboard } from "helpers/string.helper";
// types // types
import { TIssue } from "@plane/types"; import { TIssue } from "@plane/types";
// constants // constants
@ -16,10 +12,20 @@ import { EUserProjectRoles } from "constants/project";
import { EIssuesStoreType } from "constants/issue"; import { EIssuesStoreType } from "constants/issue";
interface IIssuePeekOverview { interface IIssuePeekOverview {
isArchived?: boolean; is_archived?: boolean;
onIssueUpdate?: (issue: Partial<TIssue>) => Promise<void>;
} }
export type TIssuePeekOperations = { export type TIssuePeekOperations = {
fetch: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>;
update: (
workspaceSlug: string,
projectId: string,
issueId: string,
data: Partial<TIssue>,
showToast?: boolean
) => Promise<void>;
remove: (workspaceSlug: string, projectId: string, issueId: string) => Promise<void>;
addIssueToCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => Promise<void>; addIssueToCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => Promise<void>;
removeIssueFromCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueId: string) => Promise<void>; removeIssueFromCycle: (workspaceSlug: string, projectId: string, cycleId: string, issueId: string) => Promise<void>;
addIssueToModule: (workspaceSlug: string, projectId: string, moduleId: string, issueIds: string[]) => Promise<void>; addIssueToModule: (workspaceSlug: string, projectId: string, moduleId: string, issueIds: string[]) => Promise<void>;
@ -27,17 +33,13 @@ export type TIssuePeekOperations = {
}; };
export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => { export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => {
const { isArchived = false } = props; const { is_archived = false, onIssueUpdate } = props;
// router
const router = useRouter();
// hooks // hooks
const { const {
project: {}, project: {},
} = useMember(); } = useMember();
const { currentProjectDetails } = useProject();
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
const { const {
currentUser,
membership: { currentProjectRole }, membership: { currentProjectRole },
} = useUser(); } = useUser();
const { const {
@ -47,17 +49,7 @@ export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => {
peekIssue, peekIssue,
updateIssue, updateIssue,
removeIssue, removeIssue,
createComment,
updateComment,
removeComment,
createCommentReaction,
removeCommentReaction,
createReaction,
removeReaction,
createSubscription,
removeSubscription,
issue: { getIssueById, fetchIssue }, issue: { getIssueById, fetchIssue },
fetchActivities,
} = useIssueDetail(); } = useIssueDetail();
const { addIssueToCycle, removeIssueFromCycle, addIssueToModule, removeIssueFromModule } = useIssueDetail(); const { addIssueToCycle, removeIssueFromCycle, addIssueToModule, removeIssueFromModule } = useIssueDetail();
// state // state
@ -74,6 +66,54 @@ export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => {
const issueOperations: TIssuePeekOperations = useMemo( const issueOperations: TIssuePeekOperations = useMemo(
() => ({ () => ({
fetch: async (workspaceSlug: string, projectId: string, issueId: string) => {
try {
await fetchIssue(workspaceSlug, projectId, issueId);
} catch (error) {
console.error("Error fetching the parent issue");
}
},
update: async (
workspaceSlug: string,
projectId: string,
issueId: string,
data: Partial<TIssue>,
showToast: boolean = true
) => {
try {
const response = await updateIssue(workspaceSlug, projectId, issueId, data);
if (onIssueUpdate) await onIssueUpdate(response);
if (showToast)
setToastAlert({
title: "Issue updated successfully",
type: "success",
message: "Issue updated successfully",
});
} catch (error) {
setToastAlert({
title: "Issue update failed",
type: "error",
message: "Issue update failed",
});
}
},
remove: async (workspaceSlug: string, projectId: string, issueId: string) => {
try {
if (is_archived) await removeArchivedIssue(workspaceSlug, projectId, issueId);
else await removeIssue(workspaceSlug, projectId, issueId);
setToastAlert({
title: "Issue deleted successfully",
type: "success",
message: "Issue deleted successfully",
});
} catch (error) {
setToastAlert({
title: "Issue delete failed",
type: "error",
message: "Issue delete failed",
});
}
},
addIssueToCycle: async (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => { addIssueToCycle: async (workspaceSlug: string, projectId: string, cycleId: string, issueIds: string[]) => {
try { try {
await addIssueToCycle(workspaceSlug, projectId, cycleId, issueIds); await addIssueToCycle(workspaceSlug, projectId, cycleId, issueIds);
@ -139,73 +179,27 @@ export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => {
} }
}, },
}), }),
[addIssueToCycle, removeIssueFromCycle, addIssueToModule, removeIssueFromModule, setToastAlert] [
is_archived,
fetchIssue,
updateIssue,
removeIssue,
removeArchivedIssue,
addIssueToCycle,
removeIssueFromCycle,
addIssueToModule,
removeIssueFromModule,
setToastAlert,
onIssueUpdate,
]
); );
if (!peekIssue?.workspaceSlug || !peekIssue?.projectId || !peekIssue?.issueId) return <></>; if (!peekIssue?.workspaceSlug || !peekIssue?.projectId || !peekIssue?.issueId) return <></>;
const issue = getIssueById(peekIssue.issueId) || undefined; const issue = getIssueById(peekIssue.issueId) || undefined;
const redirectToIssueDetail = () => { // Check if issue is editable, based on user role
router.push({ const is_editable = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
pathname: `/${peekIssue.workspaceSlug}/projects/${peekIssue.projectId}/${
isArchived ? "archived-issues" : "issues"
}/${peekIssue.issueId}`,
});
};
const handleCopyText = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
e.preventDefault();
copyUrlToClipboard(
`${peekIssue.workspaceSlug}/projects/${peekIssue.projectId}/${isArchived ? "archived-issues" : "issues"}/${
peekIssue.issueId
}`
).then(() => {
setToastAlert({
type: "success",
title: "Link Copied!",
message: "Issue link copied to clipboard.",
});
});
};
const issueUpdate = async (_data: Partial<TIssue>) => {
if (!issue) return;
await updateIssue(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, _data);
fetchActivities(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId);
};
const issueDelete = async () => {
if (!issue) return;
if (isArchived) await removeArchivedIssue(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId);
else await removeIssue(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId);
};
const issueReactionCreate = (reaction: string) =>
createReaction(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, reaction);
const issueReactionRemove = (reaction: string) =>
currentUser &&
currentUser.id &&
removeReaction(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, reaction, currentUser.id);
const issueCommentCreate = (comment: any) =>
createComment(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, comment);
const issueCommentUpdate = (comment: any) =>
updateComment(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, comment?.id, comment);
const issueCommentRemove = (commentId: string) =>
removeComment(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId, commentId);
const issueCommentReactionCreate = (commentId: string, reaction: string) =>
createCommentReaction(peekIssue.workspaceSlug, peekIssue.projectId, commentId, reaction);
const issueCommentReactionRemove = (commentId: string, reaction: string) =>
removeCommentReaction(peekIssue.workspaceSlug, peekIssue.projectId, commentId, reaction);
const issueSubscriptionCreate = () =>
createSubscription(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId);
const issueSubscriptionRemove = () =>
removeSubscription(peekIssue.workspaceSlug, peekIssue.projectId, peekIssue.issueId);
const userRole = currentProjectRole ?? EUserProjectRoles.GUEST;
const isLoading = !issue || loader ? true : false; const isLoading = !issue || loader ? true : false;
return ( return (
@ -215,23 +209,8 @@ export const IssuePeekOverview: FC<IIssuePeekOverview> = observer((props) => {
projectId={peekIssue.projectId} projectId={peekIssue.projectId}
issueId={peekIssue.issueId} issueId={peekIssue.issueId}
isLoading={isLoading} isLoading={isLoading}
isArchived={isArchived} is_archived={is_archived}
issue={issue} disabled={!is_editable}
handleCopyText={handleCopyText}
redirectToIssueDetail={redirectToIssueDetail}
issueUpdate={issueUpdate}
issueDelete={issueDelete}
issueReactionCreate={issueReactionCreate}
issueReactionRemove={issueReactionRemove}
issueCommentCreate={issueCommentCreate}
issueCommentUpdate={issueCommentUpdate}
issueCommentRemove={issueCommentRemove}
issueCommentReactionCreate={issueCommentReactionCreate}
issueCommentReactionRemove={issueCommentReactionRemove}
issueSubscriptionCreate={issueSubscriptionCreate}
issueSubscriptionRemove={issueSubscriptionRemove}
disableUserActions={[5, 10].includes(userRole)}
showCommentAccessSpecifier={currentProjectDetails?.is_deployed}
issueOperations={issueOperations} issueOperations={issueOperations}
/> />
</Fragment> </Fragment>

View File

@ -1,54 +1,36 @@
import { FC, useRef, useState } from "react"; import { FC, useRef, useState } from "react";
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { MoveRight, MoveDiagonal, Bell, Link2, Trash2 } from "lucide-react"; import { MoveRight, MoveDiagonal, Link2, Trash2 } from "lucide-react";
// hooks // hooks
import useOutsideClickDetector from "hooks/use-outside-click-detector"; import useOutsideClickDetector from "hooks/use-outside-click-detector";
// store hooks // store hooks
import { useIssueDetail, useUser } from "hooks/store"; import { useIssueDetail, useUser } from "hooks/store";
import useToast from "hooks/use-toast";
// components // components
import { import {
DeleteArchivedIssueModal, DeleteArchivedIssueModal,
DeleteIssueModal, DeleteIssueModal,
IssueActivity, IssueActivity,
IssueSubscription,
IssueUpdateStatus, IssueUpdateStatus,
PeekOverviewIssueDetails, PeekOverviewIssueDetails,
PeekOverviewProperties, PeekOverviewProperties,
TIssueOperations,
} from "components/issues"; } from "components/issues";
// ui // ui
import { Button, CenterPanelIcon, CustomSelect, FullScreenPanelIcon, SidePanelIcon, Spinner } from "@plane/ui"; import { CenterPanelIcon, CustomSelect, FullScreenPanelIcon, SidePanelIcon, Spinner } from "@plane/ui";
// types // helpers
import { TIssue } from "@plane/types"; import { copyUrlToClipboard } from "helpers/string.helper";
interface IIssueView { interface IIssueView {
workspaceSlug: string; workspaceSlug: string;
projectId: string; projectId: string;
issueId: string; issueId: string;
isLoading?: boolean; isLoading?: boolean;
isArchived?: boolean; is_archived: boolean;
disabled?: boolean;
issue: TIssue | undefined; issueOperations: TIssueOperations;
handleCopyText: (e: React.MouseEvent<HTMLButtonElement>) => void;
redirectToIssueDetail: () => void;
issueUpdate: (issue: Partial<TIssue>) => void;
issueDelete: () => Promise<void>;
issueReactionCreate: (reaction: string) => void;
issueReactionRemove: (reaction: string) => void;
issueCommentCreate: (comment: any) => void;
issueCommentUpdate: (comment: any) => void;
issueCommentRemove: (commentId: string) => void;
issueCommentReactionCreate: (commentId: string, reaction: string) => void;
issueCommentReactionRemove: (commentId: string, reaction: string) => void;
issueSubscriptionCreate: () => void;
issueSubscriptionRemove: () => void;
disableUserActions?: boolean;
showCommentAccessSpecifier?: boolean;
issueOperations: any;
} }
type TPeekModes = "side-peek" | "modal" | "full-screen"; type TPeekModes = "side-peek" | "modal" | "full-screen";
@ -72,79 +54,68 @@ const PEEK_OPTIONS: { key: TPeekModes; icon: any; title: string }[] = [
]; ];
export const IssueView: FC<IIssueView> = observer((props) => { export const IssueView: FC<IIssueView> = observer((props) => {
const { const { workspaceSlug, projectId, issueId, isLoading, is_archived, disabled = false, issueOperations } = props;
workspaceSlug, // router
projectId, const router = useRouter();
issueId,
issue,
isLoading,
isArchived,
handleCopyText,
redirectToIssueDetail,
issueUpdate,
issueReactionCreate,
issueReactionRemove,
issueCommentCreate,
issueCommentUpdate,
issueCommentRemove,
issueCommentReactionCreate,
issueCommentReactionRemove,
issueSubscriptionCreate,
issueSubscriptionRemove,
issueDelete,
disableUserActions = false,
showCommentAccessSpecifier = false,
issueOperations,
} = props;
// states // states
const [peekMode, setPeekMode] = useState<TPeekModes>("side-peek"); const [peekMode, setPeekMode] = useState<TPeekModes>("side-peek");
const [isSubmitting, setIsSubmitting] = useState<"submitting" | "submitted" | "saved">("saved"); const [isSubmitting, setIsSubmitting] = useState<"submitting" | "submitted" | "saved">("saved");
// ref // ref
const issuePeekOverviewRef = useRef<HTMLDivElement>(null); const issuePeekOverviewRef = useRef<HTMLDivElement>(null);
// store hooks // store hooks
const { const { activity, setPeekIssue, isAnyModalOpen, isDeleteIssueModalOpen, toggleDeleteIssueModal } = useIssueDetail();
activity,
reaction,
subscription,
setPeekIssue,
isAnyModalOpen,
isDeleteIssueModalOpen,
toggleDeleteIssueModal,
} = useIssueDetail();
const { currentUser } = useUser(); const { currentUser } = useUser();
const {
issue: { getIssueById },
} = useIssueDetail();
const { setToastAlert } = useToast();
// derived values
const issueActivity = activity.getActivitiesByIssueId(issueId);
const currentMode = PEEK_OPTIONS.find((m) => m.key === peekMode);
const issue = getIssueById(issueId);
const removeRoutePeekId = () => { const removeRoutePeekId = () => {
setPeekIssue(undefined); setPeekIssue(undefined);
}; };
const issueReactions = reaction.getReactionsByIssueId(issueId) || [];
const issueActivity = activity.getActivitiesByIssueId(issueId);
const issueSubscription = subscription.getSubscriptionByIssueId(issueId) || {};
const currentMode = PEEK_OPTIONS.find((m) => m.key === peekMode);
useOutsideClickDetector(issuePeekOverviewRef, () => !isAnyModalOpen && removeRoutePeekId()); useOutsideClickDetector(issuePeekOverviewRef, () => !isAnyModalOpen && removeRoutePeekId());
const redirectToIssueDetail = () => {
router.push({
pathname: `/${workspaceSlug}/projects/${projectId}/${is_archived ? "archived-issues" : "issues"}/${issueId}`,
});
};
const handleCopyText = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
e.preventDefault();
copyUrlToClipboard(
`${workspaceSlug}/projects/${projectId}/${is_archived ? "archived-issues" : "issues"}/${issueId}`
).then(() => {
setToastAlert({
type: "success",
title: "Link Copied!",
message: "Issue link copied to clipboard.",
});
});
};
return ( return (
<> <>
{issue && !isArchived && ( {issue && !is_archived && (
<DeleteIssueModal <DeleteIssueModal
isOpen={isDeleteIssueModalOpen} isOpen={isDeleteIssueModalOpen}
handleClose={() => toggleDeleteIssueModal(false)} handleClose={() => toggleDeleteIssueModal(false)}
data={issue} data={issue}
onSubmit={issueDelete} onSubmit={() => issueOperations.remove(workspaceSlug, projectId, issueId)}
/> />
)} )}
{issue && isArchived && ( {issue && is_archived && (
<DeleteArchivedIssueModal <DeleteArchivedIssueModal
data={issue} data={issue}
isOpen={isDeleteIssueModalOpen} isOpen={isDeleteIssueModalOpen}
handleClose={() => toggleDeleteIssueModal(false)} handleClose={() => toggleDeleteIssueModal(false)}
onSubmit={issueDelete} onSubmit={() => issueOperations.remove(workspaceSlug, projectId, issueId)}
/> />
)} )}
@ -208,27 +179,18 @@ export const IssueView: FC<IIssueView> = observer((props) => {
<div className="flex items-center gap-x-4"> <div className="flex items-center gap-x-4">
<IssueUpdateStatus isSubmitting={isSubmitting} /> <IssueUpdateStatus isSubmitting={isSubmitting} />
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
{issue?.created_by !== currentUser?.id && {currentUser && !is_archived && (
!issue?.assignee_ids.includes(currentUser?.id ?? "") && <IssueSubscription
!issue?.archived_at && ( workspaceSlug={workspaceSlug}
<Button projectId={projectId}
size="sm" issueId={issueId}
prependIcon={<Bell className="h-3 w-3" />} currentUserId={currentUser?.id}
variant="outline-primary" />
className="hover:!bg-custom-primary-100/20"
onClick={() =>
issueSubscription && issueSubscription.subscribed
? issueSubscriptionRemove()
: issueSubscriptionCreate()
}
>
{issueSubscription && issueSubscription.subscribed ? "Unsubscribe" : "Subscribe"}
</Button>
)} )}
<button onClick={handleCopyText}> <button onClick={handleCopyText}>
<Link2 className="h-4 w-4 -rotate-45 text-custom-text-300 hover:text-custom-text-200" /> <Link2 className="h-4 w-4 -rotate-45 text-custom-text-300 hover:text-custom-text-200" />
</button> </button>
{!disableUserActions && ( {!disabled && (
<button onClick={() => toggleDeleteIssueModal(true)}> <button onClick={() => toggleDeleteIssueModal(true)}>
<Trash2 className="h-4 w-4 text-custom-text-300 hover:text-custom-text-200" /> <Trash2 className="h-4 w-4 text-custom-text-300 hover:text-custom-text-200" />
</button> </button>
@ -248,29 +210,29 @@ export const IssueView: FC<IIssueView> = observer((props) => {
<> <>
{["side-peek", "modal"].includes(peekMode) ? ( {["side-peek", "modal"].includes(peekMode) ? (
<div className="relative flex flex-col gap-3 px-8 py-5"> <div className="relative flex flex-col gap-3 px-8 py-5">
{isArchived && ( {is_archived && (
<div className="absolute left-0 top-0 z-[9] flex h-full min-h-full w-full items-center justify-center bg-custom-background-100 opacity-60" /> <div className="absolute left-0 top-0 z-[9] flex h-full min-h-full w-full items-center justify-center bg-custom-background-100 opacity-60" />
)} )}
<PeekOverviewIssueDetails <PeekOverviewIssueDetails
setIsSubmitting={(value) => setIsSubmitting(value)}
isSubmitting={isSubmitting}
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
issue={issue} projectId={projectId}
issueUpdate={issueUpdate} issueId={issueId}
issueReactions={issueReactions} issueOperations={issueOperations}
user={currentUser} is_archived={is_archived}
issueReactionCreate={issueReactionCreate} disabled={disabled}
issueReactionRemove={issueReactionRemove} isSubmitting={isSubmitting}
setIsSubmitting={(value) => setIsSubmitting(value)}
/> />
<PeekOverviewProperties <PeekOverviewProperties
issue={issue} workspaceSlug={workspaceSlug}
issueUpdate={issueUpdate} projectId={projectId}
disableUserActions={disableUserActions} issueId={issueId}
issueOperations={issueOperations} issueOperations={issueOperations}
disabled={disabled}
/> />
<IssueActivity {/* <IssueActivity
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
projectId={projectId} projectId={projectId}
issueId={issueId} issueId={issueId}
@ -282,25 +244,24 @@ export const IssueView: FC<IIssueView> = observer((props) => {
issueCommentReactionCreate={issueCommentReactionCreate} issueCommentReactionCreate={issueCommentReactionCreate}
issueCommentReactionRemove={issueCommentReactionRemove} issueCommentReactionRemove={issueCommentReactionRemove}
showCommentAccessSpecifier={showCommentAccessSpecifier} showCommentAccessSpecifier={showCommentAccessSpecifier}
/> /> */}
</div> </div>
) : ( ) : (
<div className={`flex h-full w-full overflow-auto ${isArchived ? "opacity-60" : ""}`}> <div className={`flex h-full w-full overflow-auto ${is_archived ? "opacity-60" : ""}`}>
<div className="relative h-full w-full space-y-6 overflow-auto p-4 py-5"> <div className="relative h-full w-full space-y-6 overflow-auto p-4 py-5">
<div className={isArchived ? "pointer-events-none" : ""}> <div className={is_archived ? "pointer-events-none" : ""}>
<PeekOverviewIssueDetails <PeekOverviewIssueDetails
setIsSubmitting={(value) => setIsSubmitting(value)}
isSubmitting={isSubmitting}
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
issue={issue} projectId={projectId}
issueReactions={issueReactions} issueId={issueId}
issueUpdate={issueUpdate} issueOperations={issueOperations}
user={currentUser} is_archived={is_archived}
issueReactionCreate={issueReactionCreate} disabled={disabled}
issueReactionRemove={issueReactionRemove} isSubmitting={isSubmitting}
setIsSubmitting={(value) => setIsSubmitting(value)}
/> />
<IssueActivity {/* <IssueActivity
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
projectId={projectId} projectId={projectId}
issueId={issueId} issueId={issueId}
@ -312,19 +273,20 @@ export const IssueView: FC<IIssueView> = observer((props) => {
issueCommentReactionCreate={issueCommentReactionCreate} issueCommentReactionCreate={issueCommentReactionCreate}
issueCommentReactionRemove={issueCommentReactionRemove} issueCommentReactionRemove={issueCommentReactionRemove}
showCommentAccessSpecifier={showCommentAccessSpecifier} showCommentAccessSpecifier={showCommentAccessSpecifier}
/> /> */}
</div> </div>
</div> </div>
<div <div
className={`h-full !w-[400px] flex-shrink-0 border-l border-custom-border-200 p-4 py-5 ${ className={`h-full !w-[400px] flex-shrink-0 border-l border-custom-border-200 p-4 py-5 ${
isArchived ? "pointer-events-none" : "" is_archived ? "pointer-events-none" : ""
}`} }`}
> >
<PeekOverviewProperties <PeekOverviewProperties
issue={issue} workspaceSlug={workspaceSlug}
issueUpdate={issueUpdate} projectId={projectId}
disableUserActions={disableUserActions} issueId={issueId}
issueOperations={issueOperations} issueOperations={issueOperations}
disabled={disabled}
/> />
</div> </div>
</div> </div>

View File

@ -0,0 +1,199 @@
import React from "react";
import { ChevronDown, ChevronRight, X, Pencil, Trash, Link as LinkIcon, Loader } from "lucide-react";
// components
import { IssueList } from "./issues-list";
import { IssueProperty } from "./properties";
// ui
import { ControlLink, CustomMenu, Tooltip } from "@plane/ui";
// types
import { TIssue } from "@plane/types";
import { TSubIssueOperations } from "./root";
// import { ISubIssuesRootLoaders, ISubIssuesRootLoadersHandler } from "./root";
import { useIssueDetail, useProject, useProjectState } from "hooks/store";
import { observer } from "mobx-react-lite";
export interface ISubIssues {
workspaceSlug: string;
projectId: string;
parentIssueId: string;
spacingLeft: number;
disabled: boolean;
handleIssueCrudState: (
key: "create" | "existing" | "update" | "delete",
issueId: string,
issue?: TIssue | null
) => void;
subIssueOperations: TSubIssueOperations;
issueId: string;
}
export const IssueListItem: React.FC<ISubIssues> = observer((props) => {
const {
workspaceSlug,
projectId,
parentIssueId,
spacingLeft = 10,
disabled,
handleIssueCrudState,
subIssueOperations,
issueId,
} = props;
const {
setPeekIssue,
issue: { getIssueById },
subIssues: { subIssueHelpersByIssueId, setSubIssueHelpers },
} = useIssueDetail();
const project = useProject();
const { getProjectStates } = useProjectState();
const issue = getIssueById(issueId);
const projectDetail = (issue && issue.project_id && project.getProjectById(issue.project_id)) || undefined;
const currentIssueStateDetail =
(issue?.project_id && getProjectStates(issue?.project_id)?.find((state) => issue?.state_id == state.id)) ||
undefined;
const subIssueHelpers = subIssueHelpersByIssueId(parentIssueId);
const handleIssuePeekOverview = (issue: TIssue) =>
workspaceSlug &&
issue &&
issue.project_id &&
issue.id &&
setPeekIssue({ workspaceSlug, projectId: issue.project_id, issueId: issue.id });
if (!issue) return <></>;
return (
<div key={issueId}>
{issue && (
<div
className="group relative flex h-full w-full items-center gap-2 border-b border-custom-border-100 px-2 py-1 transition-all hover:bg-custom-background-90"
style={{ paddingLeft: `${spacingLeft}px` }}
>
<div className="h-[22px] w-[22px] flex-shrink-0">
{issue?.sub_issues_count > 0 && (
<>
{subIssueHelpers.preview_loader.includes(issue.id) ? (
<div className="flex h-full w-full cursor-not-allowed items-center justify-center rounded-sm bg-custom-background-80 transition-all">
<Loader width={14} strokeWidth={2} className="animate-spin" />
</div>
) : (
<div
className="flex h-full w-full cursor-pointer items-center justify-center rounded-sm transition-all hover:bg-custom-background-80"
onClick={() => {
setSubIssueHelpers(parentIssueId, "preview_loader", issue.id);
setSubIssueHelpers(parentIssueId, "issue_visibility", issue.id);
}}
>
{subIssueHelpers.issue_visibility.includes(issue.id) ? (
<ChevronDown width={14} strokeWidth={2} />
) : (
<ChevronRight width={14} strokeWidth={2} />
)}
</div>
)}
</>
)}
</div>
<div className="flex w-full cursor-pointer items-center gap-2">
<div
className="h-[6px] w-[6px] flex-shrink-0 rounded-full"
style={{
backgroundColor: currentIssueStateDetail?.color,
}}
/>
<div className="flex-shrink-0 text-xs text-custom-text-200">
{projectDetail?.identifier}-{issue?.sequence_id}
</div>
<ControlLink
href={`/${workspaceSlug}/projects/${issue.project_id}/issues/${issue.id}`}
target="_blank"
onClick={() => handleIssuePeekOverview(issue)}
className="w-full line-clamp-1 cursor-pointer text-sm text-custom-text-100"
>
<Tooltip tooltipHeading="Title" tooltipContent={issue.name}>
<span>{issue.name}</span>
</Tooltip>
</ControlLink>
</div>
<div className="flex-shrink-0 text-sm">
<IssueProperty
workspaceSlug={workspaceSlug}
parentIssueId={parentIssueId}
issueId={issueId}
disabled={disabled}
subIssueOperations={subIssueOperations}
/>
</div>
<div className="flex-shrink-0 text-sm">
<CustomMenu width="auto" placement="bottom-end" ellipsis>
{disabled && (
<CustomMenu.MenuItem onClick={() => handleIssueCrudState("update", parentIssueId, issue)}>
<div className="flex items-center gap-2">
<Pencil className="h-3.5 w-3.5" strokeWidth={2} />
<span>Edit issue</span>
</div>
</CustomMenu.MenuItem>
)}
{disabled && (
<CustomMenu.MenuItem onClick={() => handleIssueCrudState("delete", parentIssueId, issue)}>
<div className="flex items-center gap-2">
<Trash className="h-3.5 w-3.5" strokeWidth={2} />
<span>Delete issue</span>
</div>
</CustomMenu.MenuItem>
)}
<CustomMenu.MenuItem
onClick={() =>
subIssueOperations.copyText(`${workspaceSlug}/projects/${issue.project_id}/issues/${issue.id}`)
}
>
<div className="flex items-center gap-2">
<LinkIcon className="h-3.5 w-3.5" strokeWidth={2} />
<span>Copy issue link</span>
</div>
</CustomMenu.MenuItem>
</CustomMenu>
</div>
{disabled && (
<>
{subIssueHelpers.issue_loader.includes(issue.id) ? (
<div className="flex h-[22px] w-[22px] flex-shrink-0 cursor-not-allowed items-center justify-center overflow-hidden rounded-sm transition-all">
<Loader width={14} strokeWidth={2} className="animate-spin" />
</div>
) : (
<div
className="invisible flex h-[22px] w-[22px] flex-shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-sm transition-all hover:bg-custom-background-80 group-hover:visible"
onClick={() => {
subIssueOperations.removeSubIssue(workspaceSlug, issue.project_id, parentIssueId, issue.id);
}}
>
<X width={14} strokeWidth={2} />
</div>
)}
</>
)}
</div>
)}
{subIssueHelpers.issue_visibility.includes(issueId) && issue.sub_issues_count && issue.sub_issues_count > 0 && (
<IssueList
workspaceSlug={workspaceSlug}
projectId={issue.project_id}
parentIssueId={issue.id}
spacingLeft={spacingLeft + 22}
disabled={disabled}
handleIssueCrudState={handleIssueCrudState}
subIssueOperations={subIssueOperations}
/>
)}
</div>
);
});

View File

@ -1,192 +0,0 @@
import React from "react";
import { ChevronDown, ChevronRight, X, Pencil, Trash, Link as LinkIcon, Loader } from "lucide-react";
// components
import { SubIssuesRootList } from "./issues-list";
import { IssueProperty } from "./properties";
// ui
import { CustomMenu, Tooltip } from "@plane/ui";
// types
import { IUser, TIssue, TIssueSubIssues } from "@plane/types";
// import { ISubIssuesRootLoaders, ISubIssuesRootLoadersHandler } from "./root";
import { useIssueDetail, useProject, useProjectState } from "hooks/store";
export interface ISubIssues {
workspaceSlug: string;
projectId: string;
parentIssue: TIssue;
issueId: string;
handleIssue: {
fetchIssues: (issueId: string) => Promise<TIssueSubIssues>;
updateIssue: (issueId: string, data: Partial<TIssue>) => Promise<TIssue>;
removeIssue: (issueId: string) => Promise<any>;
};
spacingLeft?: number;
user: IUser | undefined;
editable: boolean;
removeIssueFromSubIssues: (parentIssueId: string, issue: TIssue) => void;
issuesLoader: any; // FIXME: ISubIssuesRootLoaders replace with any
handleIssuesLoader: ({ key, issueId }: any) => void; // FIXME: ISubIssuesRootLoadersHandler replace with any
copyText: (text: string) => void;
handleIssueCrudOperation: (
key: "create" | "existing" | "edit" | "delete",
issueId: string,
issue?: TIssue | null
) => void;
handleUpdateIssue: (issue: TIssue, data: Partial<TIssue>) => void;
}
export const SubIssues: React.FC<ISubIssues> = ({
workspaceSlug,
projectId,
parentIssue,
issueId,
spacingLeft = 0,
user,
editable,
removeIssueFromSubIssues,
issuesLoader,
handleIssuesLoader,
copyText,
handleIssueCrudOperation,
handleUpdateIssue,
}) => {
const {
issue: { getIssueById },
} = useIssueDetail();
const project = useProject();
const { getProjectStates } = useProjectState();
const issue = getIssueById(issueId);
const projectDetail = project.getProjectById(projectId);
const currentIssueStateDetail =
(issue?.project_id && getProjectStates(issue?.project_id)?.find((state) => issue?.state_id == state.id)) ||
undefined;
return (
<>
<div>
{issue && (
<div
className="group relative flex h-full w-full items-center gap-2 border-b border-custom-border-100 px-2 py-1 transition-all hover:bg-custom-background-90"
style={{ paddingLeft: `${spacingLeft}px` }}
>
<div className="h-[22px] w-[22px] flex-shrink-0">
{issue?.sub_issues_count > 0 && (
<>
{issuesLoader.sub_issues.includes(issue?.id) ? (
<div className="flex h-full w-full cursor-not-allowed items-center justify-center rounded-sm bg-custom-background-80 transition-all">
<Loader width={14} strokeWidth={2} className="animate-spin" />
</div>
) : (
<div
className="flex h-full w-full cursor-pointer items-center justify-center rounded-sm transition-all hover:bg-custom-background-80"
onClick={() => handleIssuesLoader({ key: "visibility", issueId: issue?.id })}
>
{issuesLoader && issuesLoader.visibility.includes(issue?.id) ? (
<ChevronDown width={14} strokeWidth={2} />
) : (
<ChevronRight width={14} strokeWidth={2} />
)}
</div>
)}
</>
)}
</div>
<div className="flex w-full cursor-pointer items-center gap-2">
<div
className="h-[6px] w-[6px] flex-shrink-0 rounded-full"
style={{
backgroundColor: currentIssueStateDetail?.color,
}}
/>
<div className="flex-shrink-0 text-xs text-custom-text-200">
{projectDetail?.identifier}-{issue?.sequence_id}
</div>
<Tooltip tooltipHeading="Title" tooltipContent={`${issue?.name}`}>
<div className="line-clamp-1 pr-2 text-xs text-custom-text-100">{issue?.name}</div>
</Tooltip>
</div>
<div className="flex-shrink-0 text-sm">
<IssueProperty
workspaceSlug={workspaceSlug}
parentIssue={parentIssue}
issue={issue}
editable={editable}
/>
</div>
<div className="flex-shrink-0 text-sm">
<CustomMenu width="auto" placement="bottom-end" ellipsis>
{editable && (
<CustomMenu.MenuItem onClick={() => handleIssueCrudOperation("edit", parentIssue?.id, issue)}>
<div className="flex items-center gap-2">
<Pencil className="h-3.5 w-3.5" strokeWidth={2} />
<span>Edit issue</span>
</div>
</CustomMenu.MenuItem>
)}
{editable && (
<CustomMenu.MenuItem onClick={() => handleIssueCrudOperation("delete", parentIssue?.id, issue)}>
<div className="flex items-center gap-2">
<Trash className="h-3.5 w-3.5" strokeWidth={2} />
<span>Delete issue</span>
</div>
</CustomMenu.MenuItem>
)}
<CustomMenu.MenuItem
onClick={() => copyText(`${workspaceSlug}/projects/${issue.project_id}/issues/${issue.id}`)}
>
<div className="flex items-center gap-2">
<LinkIcon className="h-3.5 w-3.5" strokeWidth={2} />
<span>Copy issue link</span>
</div>
</CustomMenu.MenuItem>
</CustomMenu>
</div>
{editable && (
<>
{issuesLoader.delete.includes(issue?.id) ? (
<div className="flex h-[22px] w-[22px] flex-shrink-0 cursor-not-allowed items-center justify-center overflow-hidden rounded-sm bg-red-200/10 text-red-500 transition-all">
<Loader width={14} strokeWidth={2} className="animate-spin" />
</div>
) : (
<div
className="invisible flex h-[22px] w-[22px] flex-shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-sm transition-all hover:bg-custom-background-80 group-hover:visible"
onClick={() => {
handleIssuesLoader({ key: "delete", issueId: issue?.id });
removeIssueFromSubIssues(parentIssue?.id, issue);
}}
>
<X width={14} strokeWidth={2} />
</div>
)}
</>
)}
</div>
)}
{issuesLoader.visibility.includes(issueId) && issue?.sub_issues_count && issue?.sub_issues_count > 0 && (
<SubIssuesRootList
workspaceSlug={workspaceSlug}
projectId={projectId}
parentIssue={issue}
spacingLeft={spacingLeft + 22}
user={user}
editable={editable}
removeIssueFromSubIssues={removeIssueFromSubIssues}
issuesLoader={issuesLoader}
handleIssuesLoader={handleIssuesLoader}
copyText={copyText}
handleIssueCrudOperation={handleIssueCrudOperation}
handleUpdateIssue={handleUpdateIssue}
/>
)}
</div>
</>
);
};

View File

@ -1,84 +1,78 @@
import { useMemo } from "react"; import { FC } from "react";
// components import { observer } from "mobx-react-lite";
import { SubIssues } from "./issue"; // hooks
// types
import { IUser, TIssue } from "@plane/types";
// import { ISubIssuesRootLoaders, ISubIssuesRootLoadersHandler } from "./root";
// fetch keys
import { useIssueDetail } from "hooks/store"; import { useIssueDetail } from "hooks/store";
// components
import { IssueListItem } from "./issue-list-item";
// types
import { TIssue } from "@plane/types";
import { TSubIssueOperations } from "./root";
import useSWR from "swr";
export interface ISubIssuesRootList { export interface IIssueList {
workspaceSlug: string; workspaceSlug: string;
projectId: string; projectId: string;
parentIssue: TIssue; parentIssueId: string;
spacingLeft?: number; spacingLeft: number;
user: IUser | undefined; disabled: boolean;
editable: boolean; handleIssueCrudState: (
removeIssueFromSubIssues: (parentIssueId: string, issue: TIssue) => void; key: "create" | "existing" | "update" | "delete",
issuesLoader: any; // FIXME: replace ISubIssuesRootLoaders with any
handleIssuesLoader: ({ key, issueId }: any) => void; // FIXME: replace ISubIssuesRootLoadersHandler with any
copyText: (text: string) => void;
handleIssueCrudOperation: (
key: "create" | "existing" | "edit" | "delete",
issueId: string, issueId: string,
issue?: TIssue | null issue?: TIssue | null
) => void; ) => void;
handleUpdateIssue: (issue: TIssue, data: Partial<TIssue>) => void; subIssueOperations: TSubIssueOperations;
} }
export const SubIssuesRootList: React.FC<ISubIssuesRootList> = ({ export const IssueList: FC<IIssueList> = observer((props) => {
const {
workspaceSlug, workspaceSlug,
projectId, projectId,
parentIssue, parentIssueId,
spacingLeft = 10, spacingLeft = 10,
user, disabled,
editable, handleIssueCrudState,
removeIssueFromSubIssues, subIssueOperations,
issuesLoader, } = props;
handleIssuesLoader, // hooks
copyText, const {
handleIssueCrudOperation, subIssues: { subIssuesByIssueId, subIssueHelpersByIssueId },
handleUpdateIssue, } = useIssueDetail();
}) => {
const issueDetail = useIssueDetail();
issueDetail.subIssues.fetchSubIssues(workspaceSlug, projectId, parentIssue?.id);
const subIssues = issueDetail.subIssues.subIssuesByIssueId(parentIssue?.id); useSWR(
workspaceSlug && projectId && parentIssueId
const handleIssue = useMemo( ? `ISSUE_DETAIL_SUB_ISSUES_${workspaceSlug}_${projectId}_${parentIssueId}`
() => ({ : null,
fetchIssues: async (issueId: string) => issueDetail.subIssues.fetchSubIssues(workspaceSlug, projectId, issueId), async () => {
updateIssue: async (issueId: string, data: Partial<TIssue>) => workspaceSlug &&
issueDetail.updateIssue(workspaceSlug, projectId, issueId, data), projectId &&
removeIssue: (issueId: string) => issueDetail.removeIssue(workspaceSlug, projectId, issueId), parentIssueId &&
}), (await subIssueOperations.fetchSubIssues(workspaceSlug, projectId, parentIssueId));
[issueDetail, workspaceSlug, projectId] }
); );
const subIssueIds = subIssuesByIssueId(parentIssueId);
const subIssueHelpers = subIssueHelpersByIssueId(parentIssueId);
return ( return (
<> <>
{subIssueHelpers.preview_loader.includes(parentIssueId) ? "Loading..." : "Hello"}
<div className="relative"> <div className="relative">
{subIssues && {subIssueIds &&
subIssues.length > 0 && subIssueIds.length > 0 &&
subIssues.map((issueId: string) => ( subIssueIds.map((issueId) => (
<SubIssues <>
key={`${issueId}`} <IssueListItem
workspaceSlug={workspaceSlug} workspaceSlug={workspaceSlug}
projectId={projectId} projectId={projectId}
parentIssue={parentIssue} parentIssueId={parentIssueId}
issueId={issueId}
handleIssue={handleIssue}
spacingLeft={spacingLeft} spacingLeft={spacingLeft}
user={user} disabled={disabled}
editable={editable} handleIssueCrudState={handleIssueCrudState}
removeIssueFromSubIssues={removeIssueFromSubIssues} subIssueOperations={subIssueOperations}
issuesLoader={issuesLoader} issueId={issueId}
handleIssuesLoader={handleIssuesLoader}
copyText={copyText}
handleIssueCrudOperation={handleIssueCrudOperation}
handleUpdateIssue={handleUpdateIssue}
/> />
</>
))} ))}
<div <div
@ -88,4 +82,4 @@ export const SubIssuesRootList: React.FC<ISubIssuesRootList> = ({
</div> </div>
</> </>
); );
}; });

View File

@ -1,78 +1,41 @@
import React from "react"; import React from "react";
import { mutate } from "swr"; // hooks
// services import { useIssueDetail } from "hooks/store";
import { IssueService } from "services/issue";
// components // components
import { PriorityDropdown, ProjectMemberDropdown, StateDropdown } from "components/dropdowns"; import { PriorityDropdown, ProjectMemberDropdown, StateDropdown } from "components/dropdowns";
// types // types
import { TIssue } from "@plane/types"; import { TSubIssueOperations } from "./root";
// fetch-keys
import { SUB_ISSUES } from "constants/fetch-keys";
export interface IIssueProperty { export interface IIssueProperty {
workspaceSlug: string; workspaceSlug: string;
parentIssue: TIssue; parentIssueId: string;
issue: TIssue; issueId: string;
editable: boolean; disabled: boolean;
subIssueOperations: TSubIssueOperations;
} }
// services
const issueService = new IssueService();
export const IssueProperty: React.FC<IIssueProperty> = (props) => { export const IssueProperty: React.FC<IIssueProperty> = (props) => {
const { workspaceSlug, parentIssue, issue, editable } = props; const { workspaceSlug, parentIssueId, issueId, disabled, subIssueOperations } = props;
// hooks
const {
issue: { getIssueById },
} = useIssueDetail();
const handlePriorityChange = (data: any) => { const issue = getIssueById(issueId);
partialUpdateIssue({ priority: data });
};
const handleStateChange = (data: string) => {
partialUpdateIssue({
state_id: data,
});
};
const handleAssigneeChange = (data: string[]) => {
partialUpdateIssue({ assignee_ids: data });
};
const partialUpdateIssue = async (data: Partial<TIssue>) => {
mutate(
workspaceSlug && parentIssue ? SUB_ISSUES(parentIssue.id) : null,
(elements: any) => {
const _elements = { ...elements };
const _issues = _elements.sub_issues.map((element: TIssue) =>
element.id === issue.id ? { ...element, ...data } : element
);
_elements["sub_issues"] = [..._issues];
return _elements;
},
false
);
const issueResponse = await issueService.patchIssue(workspaceSlug as string, issue.project_id, issue.id, data);
mutate(
SUB_ISSUES(parentIssue.id),
(elements: any) => {
const _elements = elements.sub_issues.map((element: TIssue) =>
element.id === issue.id ? issueResponse : element
);
elements["sub_issues"] = _elements;
return elements;
},
true
);
};
if (!issue) return <></>;
return ( return (
<div className="relative flex items-center gap-2"> <div className="relative flex items-center gap-2">
<div className="h-5 flex-shrink-0"> <div className="h-5 flex-shrink-0">
<StateDropdown <StateDropdown
value={issue?.state_id} value={issue.state_id}
projectId={issue?.project_id} projectId={issue.project_id}
onChange={handleStateChange} onChange={(val) =>
disabled={!editable} subIssueOperations.updateSubIssue(workspaceSlug, issue.project_id, parentIssueId, issueId, {
state_id: val,
})
}
disabled={!disabled}
buttonVariant="border-with-text" buttonVariant="border-with-text"
/> />
</div> </div>
@ -80,8 +43,12 @@ export const IssueProperty: React.FC<IIssueProperty> = (props) => {
<div className="h-5 flex-shrink-0"> <div className="h-5 flex-shrink-0">
<PriorityDropdown <PriorityDropdown
value={issue.priority} value={issue.priority}
onChange={handlePriorityChange} onChange={(val) =>
disabled={!editable} subIssueOperations.updateSubIssue(workspaceSlug, issue.project_id, parentIssueId, issueId, {
priority: val,
})
}
disabled={!disabled}
buttonVariant="border-without-text" buttonVariant="border-without-text"
buttonClassName="border" buttonClassName="border"
/> />
@ -89,10 +56,14 @@ export const IssueProperty: React.FC<IIssueProperty> = (props) => {
<div className="h-5 flex-shrink-0"> <div className="h-5 flex-shrink-0">
<ProjectMemberDropdown <ProjectMemberDropdown
projectId={issue?.project_id} value={issue.assignee_ids}
value={issue?.assignee_ids} projectId={issue.project_id}
onChange={handleAssigneeChange} onChange={(val) =>
disabled={!editable} subIssueOperations.updateSubIssue(workspaceSlug, issue.project_id, parentIssueId, issueId, {
assignee_ids: val,
})
}
disabled={!disabled}
multiple multiple
buttonVariant={issue.assignee_ids.length > 0 ? "transparent-without-text" : "border-without-text"} buttonVariant={issue.assignee_ids.length > 0 ? "transparent-without-text" : "border-without-text"}
buttonClassName={issue.assignee_ids.length > 0 ? "hover:bg-transparent px-0" : ""} buttonClassName={issue.assignee_ids.length > 0 ? "hover:bg-transparent px-0" : ""}

View File

@ -1,57 +1,108 @@
import React, { useCallback, useMemo, useState } from "react"; import { FC, useMemo, useState } from "react";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { Plus, ChevronRight, ChevronDown } from "lucide-react"; import { Plus, ChevronRight, ChevronDown, Loader } from "lucide-react";
// hooks // hooks
import { useIssueDetail, useIssues, useUser } from "hooks/store"; import { useIssueDetail } from "hooks/store";
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
// components // components
import { ExistingIssuesListModal } from "components/core"; import { ExistingIssuesListModal } from "components/core";
import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues";
import { SubIssuesRootList } from "./issues-list"; import { IssueList } from "./issues-list";
import { ProgressBar } from "./progressbar"; import { ProgressBar } from "./progressbar";
// ui // ui
import { CustomMenu } from "@plane/ui"; import { CustomMenu } from "@plane/ui";
// helpers // helpers
import { copyTextToClipboard } from "helpers/string.helper"; import { copyTextToClipboard } from "helpers/string.helper";
// types // types
import { IUser, TIssue, ISearchIssueResponse } from "@plane/types"; import { IUser, TIssue } from "@plane/types";
// services
import { IssueService } from "services/issue";
// fetch keys
import { SUB_ISSUES } from "constants/fetch-keys";
// constants
import { EUserProjectRoles } from "constants/project";
import { EIssuesStoreType } from "constants/issue";
export interface ISubIssuesRoot { export interface ISubIssuesRoot {
workspaceSlug: string; workspaceSlug: string;
projectId: string; projectId: string;
issueId: string; parentIssueId: string;
currentUser: IUser; currentUser: IUser;
is_archived: boolean; disabled: boolean;
is_editable: boolean;
} }
export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => { export type TSubIssueOperations = {
const { workspaceSlug, projectId, issueId, currentUser, is_archived, is_editable } = props; copyText: (text: string) => void;
fetchSubIssues: (workspaceSlug: string, projectId: string, parentIssueId: string) => Promise<void>;
addSubIssue: (workspaceSlug: string, projectId: string, parentIssueId: string, issueIds: string[]) => Promise<void>;
updateSubIssue: (
workspaceSlug: string,
projectId: string,
parentIssueId: string,
issueId: string,
currentIssue: Partial<TIssue>,
oldIssue?: Partial<TIssue> | undefined,
fromModal?: boolean
) => Promise<void>;
removeSubIssue: (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => Promise<void>;
deleteSubIssue: (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => Promise<void>;
};
export const SubIssuesRoot: FC<ISubIssuesRoot> = observer((props) => {
const { workspaceSlug, projectId, parentIssueId, disabled = false } = props;
// store hooks // store hooks
const {
membership: { currentProjectRole },
} = useUser();
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
const { const {
subIssues: { subIssuesByIssueId, subIssuesStateDistribution }, issue: { getIssueById },
updateIssue, subIssues: { subIssuesByIssueId, stateDistributionByIssueId, subIssueHelpersByIssueId, setSubIssueHelpers },
removeIssue,
fetchSubIssues, fetchSubIssues,
createSubIssues, createSubIssues,
updateSubIssue,
removeSubIssue,
deleteSubIssue,
} = useIssueDetail(); } = useIssueDetail();
// state // state
const [currentIssue, setCurrentIssue] = useState<TIssue>();
console.log("subIssuesByIssueId", subIssuesByIssueId(issueId)); type TIssueCrudState = { toggle: boolean; parentIssueId: string | undefined; issue: TIssue | undefined };
const [issueCrudState, setIssueCrudState] = useState<{
create: TIssueCrudState;
existing: TIssueCrudState;
update: TIssueCrudState;
delete: TIssueCrudState;
}>({
create: {
toggle: false,
parentIssueId: undefined,
issue: undefined,
},
existing: {
toggle: false,
parentIssueId: undefined,
issue: undefined,
},
update: {
toggle: false,
parentIssueId: undefined,
issue: undefined,
},
delete: {
toggle: false,
parentIssueId: undefined,
issue: undefined,
},
});
const copyText = (text: string) => { const handleIssueCrudState = (
key: "create" | "existing" | "update" | "delete",
_parentIssueId: string | null,
issue: TIssue | null = null
) => {
setIssueCrudState({
...issueCrudState,
[key]: {
toggle: !issueCrudState[key].toggle,
parentIssueId: _parentIssueId,
issue: issue,
},
});
};
const subIssueOperations: TSubIssueOperations = useMemo(
() => ({
copyText: (text: string) => {
const originURL = typeof window !== "undefined" && window.location.origin ? window.location.origin : ""; const originURL = typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
copyTextToClipboard(`${originURL}/${text}`).then(() => { copyTextToClipboard(`${originURL}/${text}`).then(() => {
setToastAlert({ setToastAlert({
@ -60,123 +111,153 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
message: "Issue link copied to clipboard.", message: "Issue link copied to clipboard.",
}); });
}); });
};
const subIssueOperations = useMemo(
() => ({
fetchSubIssues: async (workspaceSlug: string, projectId: string, issueId: string) => {
try {
await fetchSubIssues(workspaceSlug, projectId, issueId);
} catch (error) {}
}, },
update: async (workspaceSlug: string, projectId: string, issueId: string, data: Partial<TIssue>) => { fetchSubIssues: async (workspaceSlug: string, projectId: string, parentIssueId: string) => {
try { try {
await updateIssue(workspaceSlug, projectId, issueId, data); await fetchSubIssues(workspaceSlug, projectId, parentIssueId);
setToastAlert({
title: "Issue updated successfully",
type: "success",
message: "Issue updated successfully",
});
} catch (error) { } catch (error) {
setToastAlert({ setToastAlert({
title: "Issue update failed",
type: "error", type: "error",
message: "Issue update failed", title: "Error fetching sub-issues",
message: "Error fetching sub-issues",
}); });
} }
}, },
addSubIssue: async () => { addSubIssue: async (workspaceSlug: string, projectId: string, parentIssueId: string, issueIds: string[]) => {
try { try {
} catch (error) {} await createSubIssues(workspaceSlug, projectId, parentIssueId, issueIds);
setToastAlert({
type: "success",
title: "Sub-issues added successfully",
message: "Sub-issues added successfully",
});
} catch (error) {
setToastAlert({
type: "error",
title: "Error adding sub-issue",
message: "Error adding sub-issue",
});
}
}, },
removeSubIssue: async () => { updateSubIssue: async (
workspaceSlug: string,
projectId: string,
parentIssueId: string,
issueId: string,
currentIssue: Partial<TIssue>,
oldIssue: Partial<TIssue> | undefined = undefined,
fromModal: boolean = false
) => {
try { try {
} catch (error) {} setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
await updateSubIssue(workspaceSlug, projectId, parentIssueId, issueId, currentIssue, oldIssue, fromModal);
setToastAlert({
type: "success",
title: "Sub-issue updated successfully",
message: "Sub-issue updated successfully",
});
setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
} catch (error) {
setToastAlert({
type: "error",
title: "Error updating sub-issue",
message: "Error updating sub-issue",
});
}
}, },
updateIssue: async () => { removeSubIssue: async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => {
try { try {
} catch (error) {} setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
await removeSubIssue(workspaceSlug, projectId, parentIssueId, issueId);
setToastAlert({
type: "success",
title: "Sub-issue removed successfully",
message: "Sub-issue removed successfully",
});
setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
} catch (error) {
setToastAlert({
type: "error",
title: "Error removing sub-issue",
message: "Error removing sub-issue",
});
}
}, },
deleteIssue: async () => { deleteSubIssue: async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => {
try { try {
} catch (error) {} setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
await deleteSubIssue(workspaceSlug, projectId, parentIssueId, issueId);
setToastAlert({
type: "success",
title: "Issue deleted successfully",
message: "Issue deleted successfully",
});
setSubIssueHelpers(parentIssueId, "issue_loader", issueId);
} catch (error) {
setToastAlert({
type: "error",
title: "Error deleting issue",
message: "Error deleting issue",
});
}
}, },
}), }),
[] [fetchSubIssues, createSubIssues, updateSubIssue, removeSubIssue, deleteSubIssue, setToastAlert, setSubIssueHelpers]
); );
const [issueCrudOperation, setIssueCrudOperation] = React.useState<{ const issue = getIssueById(parentIssueId);
// type: "create" | "edit"; const subIssuesDistribution = stateDistributionByIssueId(parentIssueId);
create: { toggle: boolean; issueId: string | null }; const subIssues = subIssuesByIssueId(parentIssueId);
existing: { toggle: boolean; issueId: string | null }; const subIssueHelpers = subIssueHelpersByIssueId(`${parentIssueId}_root`);
}>({
create: {
toggle: false,
issueId: null,
},
existing: {
toggle: false,
issueId: null,
},
});
const handleIssueCrudOperation = (
key: "create" | "existing",
issueId: string | null,
issue: TIssue | null = null
) => {
setIssueCrudOperation({
...issueCrudOperation,
[key]: {
toggle: !issueCrudOperation[key].toggle,
issueId: issueId,
issue: issue,
},
});
};
if (!issue) return <></>;
return ( return (
<div className="h-full w-full space-y-2"> <div className="h-full w-full space-y-2">
{/* {!issues && isLoading ? ( {!subIssues ? (
<div className="py-3 text-center text-sm font-medium text-custom-text-300">Loading...</div> <div className="py-3 text-center text-sm font-medium text-custom-text-300">Loading...</div>
) : ( ) : (
<> <>
{issues && issues?.sub_issues && issues?.sub_issues?.length > 0 ? ( {subIssues && subIssues?.length > 0 ? (
<> <>
<div className="relative flex items-center gap-4 text-xs"> <div className="relative flex items-center gap-4 text-xs">
<div <div
className="flex cursor-pointer select-none items-center gap-1 rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80" className="flex cursor-pointer select-none items-center gap-1 rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80"
onClick={() => handleIssuesLoader({ key: "visibility", issueId: parentIssue?.id })} onClick={() => setSubIssueHelpers(`${parentIssueId}_root`, "issue_visibility", parentIssueId)}
> >
<div className="flex h-[16px] w-[16px] flex-shrink-0 items-center justify-center"> <div className="flex h-[16px] w-[16px] flex-shrink-0 items-center justify-center">
{issuesLoader.visibility.includes(parentIssue?.id) ? ( {subIssueHelpers.preview_loader.includes(parentIssueId) ? (
<Loader width={14} strokeWidth={2} className="animate-spin" />
) : subIssueHelpers.issue_visibility.includes(parentIssueId) ? (
<ChevronDown width={16} strokeWidth={2} /> <ChevronDown width={16} strokeWidth={2} />
) : ( ) : (
<ChevronRight width={14} strokeWidth={2} /> <ChevronRight width={14} strokeWidth={2} />
)} )}
</div> </div>
<div>Sub-issues</div> <div>Sub-issues</div>
<div>({issues?.sub_issues?.length || 0})</div> <div>({subIssues?.length || 0})</div>
</div> </div>
<div className="w-full max-w-[250px] select-none"> <div className="w-full max-w-[250px] select-none">
<ProgressBar <ProgressBar
total={issues?.sub_issues?.length || 0} total={subIssues?.length || 0}
done={(issues?.state_distribution?.cancelled || 0) + (issues?.state_distribution?.completed || 0)} done={
((subIssuesDistribution?.cancelled ?? []).length || 0) +
((subIssuesDistribution?.completed ?? []).length || 0)
}
/> />
</div> </div>
{is_editable && issuesLoader.visibility.includes(parentIssue?.id) && ( {!disabled && (
<div className="ml-auto flex flex-shrink-0 select-none items-center gap-2"> <div className="ml-auto flex flex-shrink-0 select-none items-center gap-2">
<div <div
className="cursor-pointer rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80" className="cursor-pointer rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80"
onClick={() => handleIssueCrudOperation("create", parentIssue?.id)} onClick={() => handleIssueCrudState("create", parentIssueId, null)}
> >
Add sub-issue Add sub-issue
</div> </div>
<div <div
className="cursor-pointer rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80" className="cursor-pointer rounded border border-custom-border-100 p-1.5 px-2 shadow transition-all hover:bg-custom-background-80"
onClick={() => handleIssueCrudOperation("existing", parentIssue?.id)} onClick={() => handleIssueCrudState("existing", parentIssueId, null)}
> >
Add an existing issue Add an existing issue
</div> </div>
@ -184,21 +265,16 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
)} )}
</div> </div>
{subIssueHelpers.issue_visibility.includes(parentIssueId) && (
{issuesLoader.visibility.includes(parentIssue?.id) && workspaceSlug && projectId && (
<div className="border border-b-0 border-custom-border-100"> <div className="border border-b-0 border-custom-border-100">
<SubIssuesRootList <IssueList
workspaceSlug={workspaceSlug.toString()} workspaceSlug={workspaceSlug}
projectId={projectId.toString()} projectId={projectId}
parentIssue={parentIssue} parentIssueId={parentIssueId}
user={undefined} spacingLeft={10}
editable={is_editable} disabled={!disabled}
removeIssueFromSubIssues={removeIssueFromSubIssues} handleIssueCrudState={handleIssueCrudState}
issuesLoader={issuesLoader} subIssueOperations={subIssueOperations}
handleIssuesLoader={handleIssuesLoader}
copyText={copyText}
handleIssueCrudOperation={handleIssueCrudOperation}
handleUpdateIssue={handleUpdateIssue}
/> />
</div> </div>
)} )}
@ -206,10 +282,10 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
<div> <div>
<CustomMenu <CustomMenu
label={ label={
<> <div className="flex items-center gap-1">
<Plus className="h-3 w-3" /> <Plus className="h-3 w-3" />
Add sub-issue Add sub-issue
</> </div>
} }
buttonClassName="whitespace-nowrap" buttonClassName="whitespace-nowrap"
placement="bottom-end" placement="bottom-end"
@ -218,14 +294,14 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
> >
<CustomMenu.MenuItem <CustomMenu.MenuItem
onClick={() => { onClick={() => {
handleIssueCrudOperation("create", parentIssue?.id); handleIssueCrudState("create", parentIssueId, null);
}} }}
> >
Create new Create new
</CustomMenu.MenuItem> </CustomMenu.MenuItem>
<CustomMenu.MenuItem <CustomMenu.MenuItem
onClick={() => { onClick={() => {
handleIssueCrudOperation("existing", parentIssue?.id); handleIssueCrudState("existing", parentIssueId, null);
}} }}
> >
Add an existing issue Add an existing issue
@ -234,7 +310,7 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
</div> </div>
</> </>
) : ( ) : (
is_editable && ( !disabled && (
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="py-2 text-xs italic text-custom-text-300">No Sub-Issues yet</div> <div className="py-2 text-xs italic text-custom-text-300">No Sub-Issues yet</div>
<div> <div>
@ -252,14 +328,14 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
> >
<CustomMenu.MenuItem <CustomMenu.MenuItem
onClick={() => { onClick={() => {
handleIssueCrudOperation("create", parentIssue?.id); handleIssueCrudState("create", parentIssueId, null);
}} }}
> >
Create new Create new
</CustomMenu.MenuItem> </CustomMenu.MenuItem>
<CustomMenu.MenuItem <CustomMenu.MenuItem
onClick={() => { onClick={() => {
handleIssueCrudOperation("existing", parentIssue?.id); handleIssueCrudState("existing", parentIssueId, null);
}} }}
> >
Add an existing issue Add an existing issue
@ -270,62 +346,82 @@ export const SubIssuesRoot: React.FC<ISubIssuesRoot> = observer((props) => {
) )
)} )}
{is_editable && issueCrudOperation?.create?.toggle && ( {/* issue create, add from existing , update and delete modals */}
{issueCrudState?.create?.toggle && issueCrudState?.create?.parentIssueId && (
<CreateUpdateIssueModal <CreateUpdateIssueModal
isOpen={issueCrudOperation?.create?.toggle} isOpen={issueCrudState?.create?.toggle}
data={{ data={{
parent_id: issueCrudOperation?.create?.issueId, parent_id: issueCrudState?.create?.parentIssueId,
}} }}
onClose={() => { onClose={() => handleIssueCrudState("create", null, null)}
handleIssueCrudOperation("create", null); onSubmit={async (_issue: TIssue) => {
await subIssueOperations.addSubIssue(workspaceSlug, projectId, parentIssueId, [_issue.id]);
}} }}
/> />
)} )}
{is_editable && issueCrudOperation?.existing?.toggle && issueCrudOperation?.existing?.issueId && ( {issueCrudState?.existing?.toggle && issueCrudState?.existing?.parentIssueId && (
<ExistingIssuesListModal <ExistingIssuesListModal
isOpen={issueCrudOperation?.existing?.toggle} isOpen={issueCrudState?.existing?.toggle}
handleClose={() => handleIssueCrudOperation("existing", null)} handleClose={() => handleIssueCrudState("existing", null, null)}
searchParams={{ sub_issue: true, issue_id: issueCrudOperation?.existing?.issueId }} searchParams={{ sub_issue: true, issue_id: issueCrudState?.existing?.parentIssueId }}
handleOnSubmit={addAsSubIssueFromExistingIssues} handleOnSubmit={(_issue) =>
subIssueOperations.addSubIssue(
workspaceSlug,
projectId,
parentIssueId,
_issue.map((issue) => issue.id)
)
}
workspaceLevelToggle workspaceLevelToggle
/> />
)} )}
{is_editable && issueCrudOperation?.edit?.toggle && issueCrudOperation?.edit?.issueId && ( {issueCrudState?.update?.toggle && issueCrudState?.update?.issue && (
<> <>
<CreateUpdateIssueModal <CreateUpdateIssueModal
isOpen={issueCrudOperation?.edit?.toggle} isOpen={issueCrudState?.update?.toggle}
onClose={() => { onClose={() => {
handleIssueCrudOperation("edit", null, null); handleIssueCrudState("update", null, null);
}}
data={issueCrudState?.update?.issue ?? undefined}
onSubmit={async (_issue: TIssue) => {
await subIssueOperations.updateSubIssue(
workspaceSlug,
projectId,
parentIssueId,
_issue.id,
_issue,
issueCrudState?.update?.issue,
true
);
}} }}
data={issueCrudOperation?.edit?.issue ?? undefined}
/> />
</> </>
)} )}
{is_editable && {issueCrudState?.delete?.toggle &&
workspaceSlug && issueCrudState?.delete?.issue &&
projectId && issueCrudState.delete.parentIssueId &&
issueCrudOperation?.delete?.issueId && issueCrudState.delete.issue.id && (
issueCrudOperation?.delete?.issue && (
<DeleteIssueModal <DeleteIssueModal
isOpen={issueCrudOperation?.delete?.toggle} isOpen={issueCrudState?.delete?.toggle}
handleClose={() => { handleClose={() => {
handleIssueCrudOperation("delete", null, null); handleIssueCrudState("delete", null, null);
}}
data={issueCrudOperation?.delete?.issue}
onSubmit={async () => {
await removeIssue(
workspaceSlug.toString(),
projectId.toString(),
issueCrudOperation?.delete?.issue?.id ?? ""
);
}} }}
data={issueCrudState?.delete?.issue as TIssue}
onSubmit={async () =>
await subIssueOperations.deleteSubIssue(
workspaceSlug,
projectId,
issueCrudState?.delete?.parentIssueId as string,
issueCrudState?.delete?.issue?.id as string
)
}
/> />
)} )}
</> </>
)} */} )}
</div> </div>
); );
}); });

View File

@ -577,7 +577,7 @@ export const ModuleDetailsSidebar: React.FC<Props> = observer((props) => {
</div> </div>
<div className="relative h-40 w-80"> <div className="relative h-40 w-80">
<ProgressChart <ProgressChart
distribution={moduleDetails.distribution.completion_chart} distribution={moduleDetails.distribution?.completion_chart}
startDate={moduleDetails.start_date ?? ""} startDate={moduleDetails.start_date ?? ""}
endDate={moduleDetails.target_date ?? ""} endDate={moduleDetails.target_date ?? ""}
totalIssues={moduleDetails.total_issues} totalIssues={moduleDetails.total_issues}

View File

@ -138,7 +138,7 @@ export class CycleIssuesFilter extends IssueFilterHelperStore implements ICycleI
) => { ) => {
try { try {
if (!cycleId) throw new Error("Cycle id is required"); if (!cycleId) throw new Error("Cycle id is required");
if (isEmpty(this.filters) || isEmpty(this.filters[projectId]) || isEmpty(filters)) return; if (isEmpty(this.filters) || isEmpty(this.filters[cycleId]) || isEmpty(filters)) return;
const _filters = { const _filters = {
filters: this.filters[cycleId].filters as IIssueFilterOptions, filters: this.filters[cycleId].filters as IIssueFilterOptions,

View File

@ -58,8 +58,12 @@ export class IssueStore implements IIssueStore {
this.rootIssueDetailStore.rootIssueStore.issues.addIssue([issue]); this.rootIssueDetailStore.rootIssueStore.issues.addIssue([issue]);
// store handlers from issue detail // store handlers from issue detail
// parent
if (issue && issue?.parent && issue?.parent?.id) if (issue && issue?.parent && issue?.parent?.id)
this.rootIssueDetailStore.rootIssueStore.issues.addIssue([issue?.parent]); this.rootIssueDetailStore.rootIssueStore.issues.addIssue([issue?.parent]);
// assignees
// labels
// state
// issue reactions // issue reactions
this.rootIssueDetailStore.reaction.fetchReactions(workspaceSlug, projectId, issueId); this.rootIssueDetailStore.reaction.fetchReactions(workspaceSlug, projectId, issueId);

View File

@ -201,17 +201,22 @@ export class IssueDetail implements IIssueDetail {
// sub issues // sub issues
fetchSubIssues = async (workspaceSlug: string, projectId: string, issueId: string) => fetchSubIssues = async (workspaceSlug: string, projectId: string, issueId: string) =>
this.subIssues.fetchSubIssues(workspaceSlug, projectId, issueId); this.subIssues.fetchSubIssues(workspaceSlug, projectId, issueId);
createSubIssues = async (workspaceSlug: string, projectId: string, issueId: string, data: string[]) => createSubIssues = async (workspaceSlug: string, projectId: string, parentIssueId: string, data: string[]) =>
this.subIssues.createSubIssues(workspaceSlug, projectId, issueId, data); this.subIssues.createSubIssues(workspaceSlug, projectId, parentIssueId, data);
updateSubIssue = async ( updateSubIssue = async (
workspaceSlug: string, workspaceSlug: string,
projectId: string, projectId: string,
parentIssueId: string, parentIssueId: string,
issueId: string, issueId: string,
data: { oldParentId: string; newParentId: string } oldIssue: Partial<TIssue>,
) => this.subIssues.updateSubIssue(workspaceSlug, projectId, parentIssueId, issueId, data); currentIssue?: Partial<TIssue>,
removeSubIssue = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueIds: string[]) => fromModal?: boolean
this.subIssues.removeSubIssue(workspaceSlug, projectId, parentIssueId, issueIds); ) =>
this.subIssues.updateSubIssue(workspaceSlug, projectId, parentIssueId, issueId, oldIssue, currentIssue, fromModal);
removeSubIssue = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) =>
this.subIssues.removeSubIssue(workspaceSlug, projectId, parentIssueId, issueId);
deleteSubIssue = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) =>
this.subIssues.deleteSubIssue(workspaceSlug, projectId, parentIssueId, issueId);
// subscription // subscription
fetchSubscriptions = async (workspaceSlug: string, projectId: string, issueId: string) => fetchSubscriptions = async (workspaceSlug: string, projectId: string, issueId: string) =>

View File

@ -1,5 +1,8 @@
import { action, makeObservable, observable, runInAction } from "mobx"; import { action, makeObservable, observable, runInAction } from "mobx";
import set from "lodash/set"; import set from "lodash/set";
import concat from "lodash/concat";
import update from "lodash/update";
import pull from "lodash/pull";
// services // services
import { IssueService } from "services/issue"; import { IssueService } from "services/issue";
// types // types
@ -13,41 +16,46 @@ import {
} from "@plane/types"; } from "@plane/types";
export interface IIssueSubIssuesStoreActions { export interface IIssueSubIssuesStoreActions {
fetchSubIssues: (workspaceSlug: string, projectId: string, issueId: string) => Promise<TIssueSubIssues>; fetchSubIssues: (workspaceSlug: string, projectId: string, parentIssueId: string) => Promise<TIssueSubIssues>;
createSubIssues: ( createSubIssues: (
workspaceSlug: string, workspaceSlug: string,
projectId: string, projectId: string,
issueId: string, parentIssueId: string,
data: string[] issueIds: string[]
) => Promise<TIssueSubIssues>; ) => Promise<void>;
updateSubIssue: ( updateSubIssue: (
workspaceSlug: string, workspaceSlug: string,
projectId: string, projectId: string,
parentIssueId: string, parentIssueId: string,
issueId: string, issueId: string,
data: { oldParentId: string; newParentId: string } currentIssue: Partial<TIssue>,
) => any; oldIssue?: Partial<TIssue> | undefined,
removeSubIssue: ( fromModal?: boolean
workspaceSlug: string, ) => Promise<void>;
projectId: string, removeSubIssue: (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => Promise<void>;
parentIssueId: string, deleteSubIssue: (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => Promise<void>;
issueIds: string[]
) => Promise<TIssueSubIssues>;
} }
type TSubIssueHelpersKeys = "issue_visibility" | "preview_loader" | "issue_loader";
type TSubIssueHelpers = Record<TSubIssueHelpersKeys, string[]>;
export interface IIssueSubIssuesStore extends IIssueSubIssuesStoreActions { export interface IIssueSubIssuesStore extends IIssueSubIssuesStoreActions {
// observables // observables
subIssuesStateDistribution: TIssueSubIssuesStateDistributionMap; subIssuesStateDistribution: TIssueSubIssuesStateDistributionMap;
subIssues: TIssueSubIssuesIdMap; subIssues: TIssueSubIssuesIdMap;
subIssueHelpers: Record<string, TSubIssueHelpers>; // parent_issue_id -> TSubIssueHelpers
// helper methods // helper methods
stateDistributionByIssueId: (issueId: string) => TSubIssuesStateDistribution | undefined; stateDistributionByIssueId: (issueId: string) => TSubIssuesStateDistribution | undefined;
subIssuesByIssueId: (issueId: string) => string[] | undefined; subIssuesByIssueId: (issueId: string) => string[] | undefined;
subIssueHelpersByIssueId: (issueId: string) => TSubIssueHelpers;
// actions
setSubIssueHelpers: (parentIssueId: string, key: TSubIssueHelpersKeys, value: string) => void;
} }
export class IssueSubIssuesStore implements IIssueSubIssuesStore { export class IssueSubIssuesStore implements IIssueSubIssuesStore {
// observables // observables
subIssuesStateDistribution: TIssueSubIssuesStateDistributionMap = {}; subIssuesStateDistribution: TIssueSubIssuesStateDistributionMap = {};
subIssues: TIssueSubIssuesIdMap = {}; subIssues: TIssueSubIssuesIdMap = {};
subIssueHelpers: Record<string, TSubIssueHelpers> = {};
// root store // root store
rootIssueDetailStore: IIssueDetail; rootIssueDetailStore: IIssueDetail;
// services // services
@ -58,11 +66,14 @@ export class IssueSubIssuesStore implements IIssueSubIssuesStore {
// observables // observables
subIssuesStateDistribution: observable, subIssuesStateDistribution: observable,
subIssues: observable, subIssues: observable,
subIssueHelpers: observable,
// actions // actions
setSubIssueHelpers: action,
fetchSubIssues: action, fetchSubIssues: action,
createSubIssues: action, createSubIssues: action,
updateSubIssue: action, updateSubIssue: action,
removeSubIssue: action, removeSubIssue: action,
deleteSubIssue: action,
}); });
// root store // root store
this.rootIssueDetailStore = rootStore; this.rootIssueDetailStore = rootStore;
@ -81,10 +92,27 @@ export class IssueSubIssuesStore implements IIssueSubIssuesStore {
return this.subIssues[issueId] ?? undefined; return this.subIssues[issueId] ?? undefined;
}; };
subIssueHelpersByIssueId = (issueId: string) => ({
preview_loader: this.subIssueHelpers?.[issueId]?.preview_loader || [],
issue_visibility: this.subIssueHelpers?.[issueId]?.issue_visibility || [],
issue_loader: this.subIssueHelpers?.[issueId]?.issue_loader || [],
});
// actions // actions
fetchSubIssues = async (workspaceSlug: string, projectId: string, issueId: string) => { setSubIssueHelpers = (parentIssueId: string, key: TSubIssueHelpersKeys, value: string) => {
if (!parentIssueId || !key || !value) return;
update(this.subIssueHelpers, [parentIssueId, key], (subIssueHelpers: string[]) => {
if (!subIssueHelpers || subIssueHelpers.length <= 0) return [value];
else if (subIssueHelpers.includes(value)) pull(subIssueHelpers, value);
else concat(subIssueHelpers, value);
return subIssueHelpers;
});
};
fetchSubIssues = async (workspaceSlug: string, projectId: string, parentIssueId: string) => {
try { try {
const response = await this.issueService.subIssues(workspaceSlug, projectId, issueId); const response = await this.issueService.subIssues(workspaceSlug, projectId, parentIssueId);
const subIssuesStateDistribution = response?.state_distribution ?? {}; const subIssuesStateDistribution = response?.state_distribution ?? {};
const subIssues = (response.sub_issues ?? []) as TIssue[]; const subIssues = (response.sub_issues ?? []) as TIssue[];
@ -92,38 +120,48 @@ export class IssueSubIssuesStore implements IIssueSubIssuesStore {
if (subIssues.length > 0) { if (subIssues.length > 0) {
runInAction(() => { runInAction(() => {
set(this.subIssuesStateDistribution, issueId, subIssuesStateDistribution); set(this.subIssuesStateDistribution, parentIssueId, subIssuesStateDistribution);
set( set(
this.subIssues, this.subIssues,
issueId, parentIssueId,
subIssues.map((issue) => issue.id) subIssues.map((issue) => issue.id)
); );
}); });
} }
return response; return response;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
createSubIssues = async (workspaceSlug: string, projectId: string, issueId: string, data: string[]) => { createSubIssues = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueIds: string[]) => {
try { try {
const response = await this.issueService.addSubIssues(workspaceSlug, projectId, issueId, { sub_issue_ids: data }); const response = await this.issueService.addSubIssues(workspaceSlug, projectId, parentIssueId, {
sub_issue_ids: issueIds,
});
const subIssuesStateDistribution = response?.state_distribution; const subIssuesStateDistribution = response?.state_distribution;
const subIssues = response.sub_issues as TIssue[]; const subIssues = response.sub_issues as TIssue[];
this.rootIssueDetailStore.rootIssueStore.issues.addIssue(subIssues);
runInAction(() => { runInAction(() => {
Object.keys(subIssuesStateDistribution).forEach((key) => { Object.keys(subIssuesStateDistribution).forEach((key) => {
const stateGroup = key as keyof TSubIssuesStateDistribution; const stateGroup = key as keyof TSubIssuesStateDistribution;
set(this.subIssuesStateDistribution, [issueId, key], subIssuesStateDistribution[stateGroup]); update(this.subIssuesStateDistribution, [parentIssueId, stateGroup], (stateDistribution) => {
if (!stateDistribution) return subIssuesStateDistribution[stateGroup];
return concat(stateDistribution, subIssuesStateDistribution[stateGroup]);
}); });
set(this.subIssuesStateDistribution, issueId, data);
}); });
return response; const issueIds = subIssues.map((issue) => issue.id);
update(this.subIssues, [parentIssueId], (issues) => {
if (!issues) return issueIds;
return concat(issues, issueIds);
});
});
this.rootIssueDetailStore.rootIssueStore.issues.addIssue(subIssues);
return;
} catch (error) { } catch (error) {
throw error; throw error;
} }
@ -134,45 +172,70 @@ export class IssueSubIssuesStore implements IIssueSubIssuesStore {
projectId: string, projectId: string,
parentIssueId: string, parentIssueId: string,
issueId: string, issueId: string,
data: { oldParentId: string; newParentId: string } currentIssue: Partial<TIssue>,
oldIssue: Partial<TIssue> | undefined = undefined,
fromModal: boolean = false
) => { ) => {
try { try {
const oldIssueParentId = data.oldParentId; if (!fromModal)
const newIssueParentId = data.newParentId; await this.rootIssueDetailStore.rootIssueStore.projectIssues.updateIssue(
workspaceSlug,
projectId,
issueId,
currentIssue
);
// const issue = this.rootIssueDetailStore.rootIssueStore.issues.getIssueById(issueId); if (!oldIssue) return;
// runInAction(() => { if (currentIssue.state_id != oldIssue.state_id) {
// Object.keys(subIssuesStateDistribution).forEach((key) => { }
// const stateGroup = key as keyof TSubIssuesStateDistribution;
// set(this.subIssuesStateDistribution, [issueId, key], subIssuesStateDistribution[stateGroup]);
// });
// set(this.subIssuesStateDistribution, issueId, data);
// });
return {} as any; if (currentIssue.parent_id != oldIssue.parent_id) {
}
// const updateResponse = await this.rootIssueDetailStore.rootIssueStore.projectIssues.updateIssue(
// workspaceSlug,
// projectId,
// issueId,
// oldIssue
// );
// console.log("---");
// console.log("parentIssueId", parentIssueId);
// console.log("fromModal", fromModal);
// console.log("updateResponse", updateResponse);
// console.log("---");
return;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
removeSubIssue = async (workspaceSlug: string, projectId: string, issueId: string, data: string[]) => { removeSubIssue = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => {
try { try {
const response = await this.issueService.addSubIssues(workspaceSlug, projectId, issueId, { sub_issue_ids: data }); await this.rootIssueDetailStore.rootIssueStore.projectIssues.updateIssue(workspaceSlug, projectId, issueId, {
const subIssuesStateDistribution = response?.state_distribution; parent_id: null,
const subIssues = response.sub_issues as TIssue[]; });
this.rootIssueDetailStore.rootIssueStore.issues.addIssue(subIssues);
runInAction(() => { runInAction(() => {
Object.keys(subIssuesStateDistribution).forEach((key) => { pull(this.subIssues[parentIssueId], issueId);
const stateGroup = key as keyof TSubIssuesStateDistribution;
set(this.subIssuesStateDistribution, [issueId, key], subIssuesStateDistribution[stateGroup]);
});
set(this.subIssuesStateDistribution, issueId, data);
}); });
return response; return;
} catch (error) {
throw error;
}
};
deleteSubIssue = async (workspaceSlug: string, projectId: string, parentIssueId: string, issueId: string) => {
try {
await this.rootIssueDetailStore.rootIssueStore.projectIssues.removeIssue(workspaceSlug, projectId, issueId);
runInAction(() => {
pull(this.subIssues[parentIssueId], issueId);
});
return;
} catch (error) { } catch (error) {
throw error; throw error;
} }

View File

@ -1,5 +1,8 @@
import { action, makeObservable, observable, runInAction, computed } from "mobx"; import { action, makeObservable, observable, runInAction, computed } from "mobx";
import set from "lodash/set"; import set from "lodash/set";
import update from "lodash/update";
import pull from "lodash/pull";
import concat from "lodash/concat";
// base class // base class
import { IssueHelperStore } from "../helpers/issue-helper.store"; import { IssueHelperStore } from "../helpers/issue-helper.store";
// services // services
@ -120,14 +123,16 @@ export class ProjectIssues extends IssueHelperStore implements IProjectIssues {
const response = await this.issueService.createIssue(workspaceSlug, projectId, data); const response = await this.issueService.createIssue(workspaceSlug, projectId, data);
runInAction(() => { runInAction(() => {
this.issues[projectId].push(response.id); update(this.issues, [projectId], (issueIds) => {
if (!issueIds) return [response.id];
return concat(issueIds, response.id);
});
}); });
this.rootStore.issues.addIssue([response]); this.rootStore.issues.addIssue([response]);
return response; return response;
} catch (error) { } catch (error) {
this.fetchIssues(workspaceSlug, projectId, "mutation");
throw error; throw error;
} }
}; };
@ -148,16 +153,13 @@ export class ProjectIssues extends IssueHelperStore implements IProjectIssues {
try { try {
const response = await this.issueService.deleteIssue(workspaceSlug, projectId, issueId); const response = await this.issueService.deleteIssue(workspaceSlug, projectId, issueId);
const issueIndex = this.issues[projectId].findIndex((_issueId) => _issueId === issueId);
if (issueIndex >= 0)
runInAction(() => { runInAction(() => {
this.issues[projectId].splice(issueIndex, 1); pull(this.issues[projectId], issueId);
}); });
this.rootStore.issues.removeIssue(issueId); this.rootStore.issues.removeIssue(issueId);
return response; return response;
} catch (error) { } catch (error) {
this.fetchIssues(workspaceSlug, projectId, "mutation");
throw error; throw error;
} }
}; };