[WEB-738] chore: conditionally render projects in the dropdown (#3952)

* chore: show authorized projects in the dropdown

* refactor: command palette logic

* chore: add helper function to check for project role

* fix: add preventDefault for shortcuts
This commit is contained in:
Aaryan Khandelwal 2024-03-15 17:44:01 +05:30 committed by GitHub
parent 5244ba72c9
commit 861a1c4132
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 179 additions and 101 deletions

View File

@ -1,4 +1,4 @@
import React, { useCallback, useEffect, FC } from "react"; import React, { useCallback, useEffect, FC, useMemo } from "react";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import useSWR from "swr"; import useSWR from "swr";
@ -23,24 +23,29 @@ import { EIssuesStoreType } from "constants/issue";
import { copyTextToClipboard } from "helpers/string.helper"; import { copyTextToClipboard } from "helpers/string.helper";
import { useApplication, useEventTracker, useIssues, useUser } from "hooks/store"; import { useApplication, useEventTracker, useIssues, useUser } from "hooks/store";
import { IssueService } from "services/issue"; import { IssueService } from "services/issue";
import { EUserProjectRoles } from "constants/project";
import { EUserWorkspaceRoles } from "constants/workspace";
// services // services
const issueService = new IssueService(); const issueService = new IssueService();
export const CommandPalette: FC = observer(() => { export const CommandPalette: FC = observer(() => {
// router
const router = useRouter(); const router = useRouter();
const { workspaceSlug, projectId, issueId, cycleId, moduleId } = router.query; const { workspaceSlug, projectId, issueId, cycleId, moduleId } = router.query;
// store hooks
const { const {
commandPalette, commandPalette,
theme: { toggleSidebar }, theme: { toggleSidebar },
} = useApplication(); } = useApplication();
const { setTrackElement } = useEventTracker(); const { setTrackElement } = useEventTracker();
const { currentUser } = useUser(); const {
currentUser,
membership: { currentWorkspaceRole, currentProjectRole },
} = useUser();
const { const {
issues: { removeIssue }, issues: { removeIssue },
} = useIssues(EIssuesStoreType.PROJECT); } = useIssues(EIssuesStoreType.PROJECT);
const { const {
toggleCommandPaletteModal, toggleCommandPaletteModal,
isCreateIssueModalOpen, isCreateIssueModalOpen,
@ -91,6 +96,105 @@ export const CommandPalette: FC = observer(() => {
}); });
}, [issueId]); }, [issueId]);
// auth
const canPerformProjectCreateActions = useCallback(
(showToast: boolean = true) => {
const isAllowed = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
if (!isAllowed && showToast)
setToast({
type: TOAST_TYPE.ERROR,
title: "You don't have permission to perform this action.",
});
return isAllowed;
},
[currentProjectRole]
);
const canPerformWorkspaceCreateActions = useCallback(
(showToast: boolean = true) => {
const isAllowed = !!currentWorkspaceRole && currentWorkspaceRole >= EUserWorkspaceRoles.MEMBER;
console.log("currentWorkspaceRole", currentWorkspaceRole);
console.log("isAllowed", isAllowed);
if (!isAllowed && showToast)
setToast({
type: TOAST_TYPE.ERROR,
title: "You don't have permission to perform this action.",
});
return isAllowed;
},
[currentWorkspaceRole]
);
const shortcutsList: {
global: Record<string, { title: string; description: string; action: () => void }>;
workspace: Record<string, { title: string; description: string; action: () => void }>;
project: Record<string, { title: string; description: string; action: () => void }>;
} = useMemo(
() => ({
global: {
c: {
title: "Create a new issue",
description: "Create a new issue in the current project",
action: () => toggleCreateIssueModal(true),
},
h: {
title: "Show shortcuts",
description: "Show all the available shortcuts",
action: () => toggleShortcutModal(true),
},
},
workspace: {
p: {
title: "Create a new project",
description: "Create a new project in the current workspace",
action: () => toggleCreateProjectModal(true),
},
},
project: {
d: {
title: "Create a new page",
description: "Create a new page in the current project",
action: () => toggleCreatePageModal(true),
},
m: {
title: "Create a new module",
description: "Create a new module in the current project",
action: () => toggleCreateModuleModal(true),
},
q: {
title: "Create a new cycle",
description: "Create a new cycle in the current project",
action: () => toggleCreateCycleModal(true),
},
v: {
title: "Create a new view",
description: "Create a new view in the current project",
action: () => toggleCreateViewModal(true),
},
backspace: {
title: "Bulk delete issues",
description: "Bulk delete issues in the current project",
action: () => toggleBulkDeleteIssueModal(true),
},
delete: {
title: "Bulk delete issues",
description: "Bulk delete issues in the current project",
action: () => toggleBulkDeleteIssueModal(true),
},
},
}),
[
toggleBulkDeleteIssueModal,
toggleCreateCycleModal,
toggleCreateIssueModal,
toggleCreateModuleModal,
toggleCreatePageModal,
toggleCreateProjectModal,
toggleCreateViewModal,
toggleShortcutModal,
]
);
const handleKeyDown = useCallback( const handleKeyDown = useCallback(
(e: KeyboardEvent) => { (e: KeyboardEvent) => {
const { key, ctrlKey, metaKey, altKey } = e; const { key, ctrlKey, metaKey, altKey } = e;
@ -102,7 +206,7 @@ export const CommandPalette: FC = observer(() => {
if ( if (
e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLInputElement || e.target instanceof HTMLInputElement ||
(e.target as Element).classList?.contains("ProseMirror") (e.target as Element)?.classList?.contains("ProseMirror")
) )
return; return;
@ -119,42 +223,37 @@ export const CommandPalette: FC = observer(() => {
} }
} else if (!isAnyModalOpen) { } else if (!isAnyModalOpen) {
setTrackElement("Shortcut key"); setTrackElement("Shortcut key");
if (keyPressed === "c") { if (Object.keys(shortcutsList.global).includes(keyPressed)) shortcutsList.global[keyPressed].action();
toggleCreateIssueModal(true); // workspace authorized actions
} else if (keyPressed === "p") { else if (
toggleCreateProjectModal(true); Object.keys(shortcutsList.workspace).includes(keyPressed) &&
} else if (keyPressed === "h") { workspaceSlug &&
toggleShortcutModal(true); canPerformWorkspaceCreateActions()
} else if (keyPressed === "v" && workspaceSlug && projectId) { )
toggleCreateViewModal(true); shortcutsList.workspace[keyPressed].action();
} else if (keyPressed === "d" && workspaceSlug && projectId) { // project authorized actions
toggleCreatePageModal(true); else if (
} else if (keyPressed === "q" && workspaceSlug && projectId) { Object.keys(shortcutsList.project).includes(keyPressed) &&
toggleCreateCycleModal(true); projectId &&
} else if (keyPressed === "m" && workspaceSlug && projectId) { canPerformProjectCreateActions()
toggleCreateModuleModal(true); ) {
} else if (keyPressed === "backspace" || keyPressed === "delete") {
e.preventDefault(); e.preventDefault();
toggleBulkDeleteIssueModal(true); // actions that can be performed only inside a project
shortcutsList.project[keyPressed].action();
} }
} }
}, },
[ [
canPerformProjectCreateActions,
canPerformWorkspaceCreateActions,
copyIssueUrlToClipboard, copyIssueUrlToClipboard,
toggleCreateProjectModal, isAnyModalOpen,
toggleCreateViewModal, projectId,
toggleCreatePageModal, setTrackElement,
toggleShortcutModal, shortcutsList,
toggleCreateCycleModal,
toggleCreateModuleModal,
toggleBulkDeleteIssueModal,
toggleCommandPaletteModal, toggleCommandPaletteModal,
toggleSidebar, toggleSidebar,
toggleCreateIssueModal,
projectId,
workspaceSlug, workspaceSlug,
isAnyModalOpen,
setTrackElement,
] ]
); );
@ -169,18 +268,11 @@ export const CommandPalette: FC = observer(() => {
return ( return (
<> <>
<ShortcutsModal <ShortcutsModal isOpen={isShortcutModalOpen} onClose={() => toggleShortcutModal(false)} />
isOpen={isShortcutModalOpen}
onClose={() => {
toggleShortcutModal(false);
}}
/>
{workspaceSlug && ( {workspaceSlug && (
<CreateProjectModal <CreateProjectModal
isOpen={isCreateProjectModalOpen} isOpen={isCreateProjectModalOpen}
onClose={() => { onClose={() => toggleCreateProjectModal(false)}
toggleCreateProjectModal(false);
}}
workspaceSlug={workspaceSlug.toString()} workspaceSlug={workspaceSlug.toString()}
/> />
)} )}
@ -194,9 +286,7 @@ export const CommandPalette: FC = observer(() => {
/> />
<CreateUpdateModuleModal <CreateUpdateModuleModal
isOpen={isCreateModuleModalOpen} isOpen={isCreateModuleModalOpen}
onClose={() => { onClose={() => toggleCreateModuleModal(false)}
toggleCreateModuleModal(false);
}}
workspaceSlug={workspaceSlug.toString()} workspaceSlug={workspaceSlug.toString()}
projectId={projectId.toString()} projectId={projectId.toString()}
/> />
@ -236,9 +326,7 @@ export const CommandPalette: FC = observer(() => {
<BulkDeleteIssuesModal <BulkDeleteIssuesModal
isOpen={isBulkDeleteIssueModalOpen} isOpen={isBulkDeleteIssueModalOpen}
onClose={() => { onClose={() => toggleBulkDeleteIssueModal(false)}
toggleBulkDeleteIssueModal(false);
}}
user={currentUser} user={currentUser}
/> />
<CommandModal /> <CommandModal />

View File

@ -6,6 +6,7 @@ import { DateRangeDropdown, ProjectDropdown } from "components/dropdowns";
// ui // ui
// helpers // helpers
import { renderFormattedPayloadDate } from "helpers/date-time.helper"; import { renderFormattedPayloadDate } from "helpers/date-time.helper";
import { shouldRenderProject } from "helpers/project.helper";
// types // types
import { ICycle } from "@plane/types"; import { ICycle } from "@plane/types";
@ -66,6 +67,7 @@ export const CycleForm: React.FC<Props> = (props) => {
setActiveProject(val); setActiveProject(val);
}} }}
buttonVariant="background-with-text" buttonVariant="background-with-text"
renderCondition={(project) => shouldRenderProject(project)}
tabIndex={7} tabIndex={7}
/> />
)} )}

View File

@ -15,6 +15,7 @@ import { ProjectLogo } from "components/project";
// types // types
import { BUTTON_VARIANTS_WITH_TEXT } from "./constants"; import { BUTTON_VARIANTS_WITH_TEXT } from "./constants";
import { TDropdownProps } from "./types"; import { TDropdownProps } from "./types";
import { IProject } from "@plane/types";
// constants // constants
type Props = TDropdownProps & { type Props = TDropdownProps & {
@ -23,6 +24,7 @@ type Props = TDropdownProps & {
dropdownArrowClassName?: string; dropdownArrowClassName?: string;
onChange: (val: string) => void; onChange: (val: string) => void;
onClose?: () => void; onClose?: () => void;
renderCondition?: (project: IProject) => boolean;
value: string | null; value: string | null;
}; };
@ -41,6 +43,7 @@ export const ProjectDropdown: React.FC<Props> = observer((props) => {
onClose, onClose,
placeholder = "Project", placeholder = "Project",
placement, placement,
renderCondition,
showTooltip = false, showTooltip = false,
tabIndex, tabIndex,
value, value,
@ -71,7 +74,7 @@ export const ProjectDropdown: React.FC<Props> = observer((props) => {
const options = joinedProjectIds?.map((projectId) => { const options = joinedProjectIds?.map((projectId) => {
const projectDetails = getProjectById(projectId); const projectDetails = getProjectById(projectId);
if (renderCondition && projectDetails && !renderCondition(projectDetails)) return;
return { return {
value: projectId, value: projectId,
query: `${projectDetails?.name}`, query: `${projectDetails?.name}`,
@ -89,7 +92,7 @@ export const ProjectDropdown: React.FC<Props> = observer((props) => {
}); });
const filteredOptions = const filteredOptions =
query === "" ? options : options?.filter((o) => o.query.toLowerCase().includes(query.toLowerCase())); query === "" ? options : options?.filter((o) => o?.query.toLowerCase().includes(query.toLowerCase()));
const selectedProject = value ? getProjectById(value) : null; const selectedProject = value ? getProjectById(value) : null;
@ -205,7 +208,9 @@ export const ProjectDropdown: React.FC<Props> = observer((props) => {
<div className="mt-2 max-h-48 space-y-1 overflow-y-scroll"> <div className="mt-2 max-h-48 space-y-1 overflow-y-scroll">
{filteredOptions ? ( {filteredOptions ? (
filteredOptions.length > 0 ? ( filteredOptions.length > 0 ? (
filteredOptions.map((option) => ( filteredOptions.map((option) => {
if (!option) return;
return (
<Combobox.Option <Combobox.Option
key={option.value} key={option.value}
value={option.value} value={option.value}
@ -222,7 +227,8 @@ export const ProjectDropdown: React.FC<Props> = observer((props) => {
</> </>
)} )}
</Combobox.Option> </Combobox.Option>
)) );
})
) : ( ) : (
<p className="text-custom-text-400 italic py-1 px-1.5">No matching results</p> <p className="text-custom-text-400 italic py-1 px-1.5">No matching results</p>
) )

View File

@ -30,6 +30,7 @@ import { FileService } from "services/file.service";
// ui // ui
// helpers // helpers
import { getChangedIssuefields } from "helpers/issue.helper"; import { getChangedIssuefields } from "helpers/issue.helper";
import { shouldRenderProject } from "helpers/project.helper";
// types // types
import type { TIssue, ISearchIssueResponse } from "@plane/types"; import type { TIssue, ISearchIssueResponse } from "@plane/types";
@ -304,7 +305,7 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
handleFormChange(); handleFormChange();
}} }}
buttonVariant="border-with-text" buttonVariant="border-with-text"
// TODO: update tabIndex logic renderCondition={(project) => shouldRenderProject(project)}
tabIndex={getTabIndex("project_id")} tabIndex={getTabIndex("project_id")}
/> />
</div> </div>

View File

@ -7,6 +7,7 @@ import { ModuleStatusSelect } from "components/modules";
// ui // ui
// helpers // helpers
import { renderFormattedPayloadDate } from "helpers/date-time.helper"; import { renderFormattedPayloadDate } from "helpers/date-time.helper";
import { shouldRenderProject } from "helpers/project.helper";
// types // types
import { IModule } from "@plane/types"; import { IModule } from "@plane/types";
@ -78,6 +79,7 @@ export const ModuleForm: React.FC<Props> = (props) => {
setActiveProject(val); setActiveProject(val);
}} }}
buttonVariant="border-with-text" buttonVariant="border-with-text"
renderCondition={(project) => shouldRenderProject(project)}
tabIndex={10} tabIndex={10}
/> />
</div> </div>

View File

@ -1,15 +1,8 @@
import { useEffect, Fragment, FC, useState } from "react"; import { useEffect, Fragment, FC, useState } from "react";
import { observer } from "mobx-react-lite";
import { Dialog, Transition } from "@headlessui/react"; import { Dialog, Transition } from "@headlessui/react";
// ui
import { setToast, TOAST_TYPE } from "@plane/ui";
// components // components
import { CreateProjectForm } from "./create-project-form"; import { CreateProjectForm } from "./create-project-form";
import { ProjectFeatureUpdate } from "./project-feature-update"; import { ProjectFeatureUpdate } from "./project-feature-update";
// constants
import { EUserWorkspaceRoles } from "constants/workspace";
// hooks
import { useUser } from "hooks/store";
type Props = { type Props = {
isOpen: boolean; isOpen: boolean;
@ -23,32 +16,11 @@ enum EProjectCreationSteps {
FEATURE_SELECTION = "FEATURE_SELECTION", FEATURE_SELECTION = "FEATURE_SELECTION",
} }
interface IIsGuestCondition { export const CreateProjectModal: FC<Props> = (props) => {
onClose: () => void;
}
const IsGuestCondition: FC<IIsGuestCondition> = ({ onClose }) => {
useEffect(() => {
onClose();
setToast({
title: "Error",
type: TOAST_TYPE.ERROR,
message: "You don't have permission to create project.",
});
}, [onClose]);
return null;
};
export const CreateProjectModal: FC<Props> = observer((props) => {
const { isOpen, onClose, setToFavorite = false, workspaceSlug } = props; const { isOpen, onClose, setToFavorite = false, workspaceSlug } = props;
// states // states
const [currentStep, setCurrentStep] = useState<EProjectCreationSteps>(EProjectCreationSteps.CREATE_PROJECT); const [currentStep, setCurrentStep] = useState<EProjectCreationSteps>(EProjectCreationSteps.CREATE_PROJECT);
const [createdProjectId, setCreatedProjectId] = useState<string | null>(null); const [createdProjectId, setCreatedProjectId] = useState<string | null>(null);
// hooks
const {
membership: { currentWorkspaceRole },
} = useUser();
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
@ -57,9 +29,6 @@ export const CreateProjectModal: FC<Props> = observer((props) => {
} }
}, [isOpen]); }, [isOpen]);
if (currentWorkspaceRole && isOpen)
if (currentWorkspaceRole < EUserWorkspaceRoles.MEMBER) return <IsGuestCondition onClose={onClose} />;
const handleNextStep = (projectId: string) => { const handleNextStep = (projectId: string) => {
if (!projectId) return; if (!projectId) return;
setCreatedProjectId(projectId); setCreatedProjectId(projectId);
@ -111,4 +80,4 @@ export const CreateProjectModal: FC<Props> = observer((props) => {
</Dialog> </Dialog>
</Transition.Root> </Transition.Root>
); );
}); };

View File

@ -3,6 +3,8 @@ import sortBy from "lodash/sortBy";
import { satisfiesDateFilter } from "helpers/filter.helper"; import { satisfiesDateFilter } from "helpers/filter.helper";
// types // types
import { IProject, TProjectDisplayFilters, TProjectFilters, TProjectOrderByOptions } from "@plane/types"; import { IProject, TProjectDisplayFilters, TProjectFilters, TProjectOrderByOptions } from "@plane/types";
// constants
import { EUserProjectRoles } from "constants/project";
/** /**
* Updates the sort order of the project. * Updates the sort order of the project.
@ -51,6 +53,14 @@ export const orderJoinedProjects = (
export const projectIdentifierSanitizer = (identifier: string): string => export const projectIdentifierSanitizer = (identifier: string): string =>
identifier.replace(/[^ÇŞĞIİÖÜA-Za-z0-9]/g, ""); identifier.replace(/[^ÇŞĞIİÖÜA-Za-z0-9]/g, "");
/**
* @description Checks if the project should be rendered or not based on the user role
* @param {IProject} project
* @returns {boolean}
*/
export const shouldRenderProject = (project: IProject): boolean =>
!!project.member_role && project.member_role >= EUserProjectRoles.MEMBER;
/** /**
* @description filters projects based on the filter * @description filters projects based on the filter
* @param {IProject} project * @param {IProject} project