chore: file upload in the issue modal

This commit is contained in:
Aaryan Khandelwal 2023-09-20 15:16:13 +05:30
parent 220c572461
commit 4c016c85f1
9 changed files with 468 additions and 251 deletions

View File

@ -1,9 +1,9 @@
import React, { useRef, useState } from "react"; import React, { useRef, useState } from "react";
// headless ui // headless ui
import { Combobox, Transition } from "@headlessui/react"; import { Combobox } from "@headlessui/react";
// hooks // hooks
import useOutsideClickDetector from "hooks/use-outside-click-detector"; import useDynamicDropdownPosition from "hooks/use-dynamic-dropdown";
// icons // icons
import { Check, Search, XIcon } from "lucide-react"; import { Check, Search, XIcon } from "lucide-react";
// types // types
@ -36,46 +36,21 @@ export const CustomSelectAttribute: React.FC<Props> = (props) => {
option.display_name.toLowerCase().includes(query.toLowerCase()) option.display_name.toLowerCase().includes(query.toLowerCase())
); );
const handleOnOpen = () => {
const dropdownButton = dropdownButtonRef.current;
const dropdownOptions = dropdownOptionsRef.current;
if (!dropdownButton || !dropdownOptions) return;
const dropdownWidth = dropdownOptions.clientWidth;
const dropdownHeight = dropdownOptions.clientHeight;
const dropdownBtnX = dropdownButton.getBoundingClientRect().x;
const dropdownBtnY = dropdownButton.getBoundingClientRect().y;
const dropdownBtnHeight = dropdownButton.clientHeight;
let top = dropdownBtnY + dropdownBtnHeight;
if (dropdownBtnY + dropdownHeight > window.innerHeight)
top = dropdownBtnY - dropdownHeight - 10;
else top = top + 4;
let left = dropdownBtnX;
if (dropdownBtnX + dropdownWidth > window.innerWidth) left = dropdownBtnX - dropdownWidth;
dropdownOptions.style.top = `${Math.round(top)}px`;
dropdownOptions.style.left = `${Math.round(left)}px`;
};
useOutsideClickDetector(dropdownOptionsRef, () => {
if (isOpen) setIsOpen(false);
});
const comboboxProps: any = { const comboboxProps: any = {
onChange, onChange,
value, value,
}; };
useDynamicDropdownPosition(isOpen, () => setIsOpen(false), dropdownButtonRef, dropdownOptionsRef);
if (multiple) comboboxProps.multiple = true; if (multiple) comboboxProps.multiple = true;
return ( return (
<Combobox as="div" className="flex-shrink-0 text-left flex items-center" {...comboboxProps}> <Combobox as="div" className="flex-shrink-0 text-left flex items-center" {...comboboxProps}>
{({ open }: { open: boolean }) => { {({ open }: { open: boolean }) => {
if (open) handleOnOpen(); if (open) {
if (!isOpen) setIsOpen(true);
} else if (isOpen) setIsOpen(false);
return ( return (
<> <>
@ -98,8 +73,7 @@ export const CustomSelectAttribute: React.FC<Props> = (props) => {
{optionDetails?.display_name} {optionDetails?.display_name}
{((attributeDetails.is_required && value.length > 1) || {((attributeDetails.is_required && value.length > 1) ||
!attributeDetails.is_required) && ( !attributeDetails.is_required) && (
<button <span
type="button"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@ -108,7 +82,7 @@ export const CustomSelectAttribute: React.FC<Props> = (props) => {
}} }}
> >
<XIcon size={10} strokeWidth={1.5} /> <XIcon size={10} strokeWidth={1.5} />
</button> </span>
)} )}
</div> </div>
); );
@ -122,28 +96,25 @@ export const CustomSelectAttribute: React.FC<Props> = (props) => {
</div> </div>
) )
) : ( ) : (
<div className="flex items-center gap-2 flex-wrap"> <div
<div className="px-2.5 py-0.5 rounded text-xs flex items-center justify-between gap-1"
className="px-2.5 py-0.5 rounded text-xs flex items-center justify-between gap-1" style={{
style={{ backgroundColor: `${options.find((o) => o.id === value)?.color}40`,
backgroundColor: `${options.find((o) => o.id === value)?.color}40`, }}
}} >
> {options.find((o) => o.id === value)?.display_name}
{options.find((o) => o.id === value)?.display_name} {!attributeDetails.is_required && (
{!attributeDetails.is_required && ( <span
<button onClick={(e) => {
type="button" e.preventDefault();
onClick={(e) => { e.stopPropagation();
e.preventDefault();
e.stopPropagation();
onChange(undefined); onChange(undefined);
}} }}
> >
<XIcon size={10} strokeWidth={1.5} /> <XIcon size={10} strokeWidth={1.5} />
</button> </span>
)} )}
</div>
</div> </div>
) )
) : ( ) : (
@ -154,58 +125,48 @@ export const CustomSelectAttribute: React.FC<Props> = (props) => {
</div> </div>
)} )}
</Combobox.Button> </Combobox.Button>
<Transition <div className={`${open ? "fixed z-20 top-0 left-0 h-full w-full cursor-auto" : ""}`}>
as={React.Fragment} <Combobox.Options
enter="transition ease-out duration-200" ref={dropdownOptionsRef}
enterFrom="opacity-0 translate-y-1" className="fixed z-10 border border-custom-border-300 px-2 py-2.5 rounded bg-custom-background-100 text-xs shadow-custom-shadow-rg focus:outline-none w-48 whitespace-nowrap mt-1"
enterTo="opacity-100 translate-y-0" >
leave="transition ease-in duration-150" <div className="flex w-full items-center justify-start rounded-sm border-[0.5px] border-custom-border-200 bg-custom-background-90 px-2 mb-1">
leaveFrom="opacity-100 translate-y-0" <Search className="text-custom-text-400" size={12} strokeWidth={1.5} />
leaveTo="opacity-0 translate-y-1" <Combobox.Input
> className="w-full bg-transparent py-1 px-2 text-xs text-custom-text-200 placeholder:text-custom-text-400 focus:outline-none"
<div className="fixed z-10 top-0 left-0 h-full w-full cursor-auto"> value={query}
<Combobox.Options onChange={(e) => setQuery(e.target.value)}
ref={dropdownOptionsRef} placeholder="Type to search..."
className="fixed z-10 border border-custom-border-300 px-2 py-2.5 rounded bg-custom-background-100 text-xs shadow-lg focus:outline-none w-48 whitespace-nowrap" displayValue={(assigned: any) => assigned?.name}
> />
<div className="flex w-full items-center justify-start rounded-sm border-[0.6px] border-custom-border-200 bg-custom-background-90 px-2 mb-1"> </div>
<Search className="text-custom-text-400" size={12} strokeWidth={1.5} /> <div className="mt-1 overflow-y-auto">
<Combobox.Input {(options ?? []).map((option) => (
className="w-full bg-transparent py-1 px-2 text-xs text-custom-text-200 placeholder:text-custom-text-400 focus:outline-none" <Combobox.Option
value={query} key={option.id}
onChange={(e) => setQuery(e.target.value)} value={option.id}
placeholder="Type to search..." className={({ active }) =>
displayValue={(assigned: any) => assigned?.name} `flex items-center justify-between gap-1 cursor-pointer select-none truncate rounded px-1 py-1.5 w-full ${
/> active ? "bg-custom-background-80" : ""
</div> }`
<div className="mt-1 overflow-y-auto"> }
{(options ?? []).map((option) => ( >
<Combobox.Option {({ selected }) => (
key={option.id} <>
value={option.id} <span
className={({ active }) => className="px-1 rounded-sm truncate"
`flex items-center justify-between gap-1 cursor-pointer select-none truncate rounded px-1 py-1.5 w-full ${ style={{ backgroundColor: `${option.color}40` }}
active ? "bg-custom-background-80" : "" >
}` {option.display_name}
} </span>
> {selected && <Check size={14} strokeWidth={1.5} />}
{({ selected }) => ( </>
<> )}
<span </Combobox.Option>
className="px-1 rounded-sm truncate" ))}
style={{ backgroundColor: `${option.color}40` }} </div>
> </Combobox.Options>
{option.display_name} </div>
</span>
{selected && <Check size={14} strokeWidth={1.5} />}
</>
)}
</Combobox.Option>
))}
</div>
</Combobox.Options>
</div>
</Transition>
</> </>
); );
}} }}

View File

@ -1,7 +1,3 @@
import { useEffect } from "react";
import { useRouter } from "next/router";
// mobx // mobx
import { useMobxStore } from "lib/mobx/store-provider"; import { useMobxStore } from "lib/mobx/store-provider";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
@ -21,58 +17,40 @@ type Props = {
export const CustomAttributesCheckboxes: React.FC<Props> = observer((props) => { export const CustomAttributesCheckboxes: React.FC<Props> = observer((props) => {
const { entityId, issueId, onChange, projectId, values } = props; const { entityId, issueId, onChange, projectId, values } = props;
const router = useRouter(); const { customAttributes } = useMobxStore();
const { workspaceSlug } = router.query;
const { customAttributes: customAttributesStore } = useMobxStore(); const attributes = customAttributes.entityAttributes[entityId] ?? {};
const { entityAttributes, fetchEntityDetails, fetchEntityDetailsLoader } = customAttributesStore;
const attributes = entityAttributes[entityId] ?? {};
// fetch entity details
useEffect(() => {
if (!entityAttributes[entityId]) {
if (!workspaceSlug) return;
fetchEntityDetails(workspaceSlug.toString(), entityId);
}
}, [entityAttributes, entityId, fetchEntityDetails, workspaceSlug]);
const checkboxFields = Object.values(attributes).filter((a) => a.type === "checkbox"); const checkboxFields = Object.values(attributes).filter((a) => a.type === "checkbox");
return ( return (
<> <>
{fetchEntityDetailsLoader ? ( {customAttributes.fetchEntityDetailsLoader ? (
<Loader className="flex items-center gap-2"> <Loader className="space-y-3.5">
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
</Loader> </Loader>
) : ( ) : (
<div> <div className="space-y-4">
<h5 className="text-sm">Checkboxes</h5> {Object.entries(checkboxFields).map(([attributeId, attribute]) => (
<div className="mt-3.5 space-y-4"> <div key={attributeId} className="flex items-center gap-2">
{Object.entries(checkboxFields).map(([attributeId, attribute]) => ( <Tooltip tooltipContent={attribute.display_name} position="top-left">
<div key={attributeId} className="flex items-center gap-2"> <p className="text-xs text-custom-text-300 w-2/5 truncate">
<Tooltip tooltipContent={attribute.display_name} position="top-left"> {attribute.display_name}
<p className="text-xs text-custom-text-300 w-1/3 truncate"> </p>
{attribute.display_name} </Tooltip>
</p> <div className="w-3/5 flex-shrink-0">
</Tooltip> <CustomCheckboxAttribute
<div className="w-2/3 flex-shrink-0"> attributeDetails={attribute}
{attribute.type === "checkbox" && ( issueId={issueId}
<CustomCheckboxAttribute onChange={(val) => onChange(attribute.id, [`${val}`])}
attributeDetails={attribute} projectId={projectId}
issueId={issueId} value={values[attribute.id]?.[0] === "true" ? true : false}
onChange={(val) => onChange(attribute.id, [`${val}`])} />
projectId={projectId}
value={values[attribute.id]?.[0] === "true" ? true : false}
/>
)}
</div>
</div> </div>
))} </div>
</div> ))}
</div> </div>
)} )}
</> </>

View File

@ -1,6 +1,4 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { useRouter } from "next/router";
// mobx // mobx
import { useMobxStore } from "lib/mobx/store-provider"; import { useMobxStore } from "lib/mobx/store-provider";
@ -25,26 +23,13 @@ type Props = {
const DESCRIPTION_FIELDS: TCustomAttributeTypes[] = ["email", "number", "text", "url"]; const DESCRIPTION_FIELDS: TCustomAttributeTypes[] = ["email", "number", "text", "url"];
export const CustomAttributesDescriptionFields: React.FC<Props> = observer((props) => { export const CustomAttributesDescriptionFields: React.FC<Props> = observer((props) => {
const { entityId, issueId, onChange, projectId, values } = props; const { entityId, onChange, values } = props;
const [hideOptionalFields, setHideOptionalFields] = useState(false); const [hideOptionalFields, setHideOptionalFields] = useState(false);
const router = useRouter(); const { customAttributes } = useMobxStore();
const { workspaceSlug } = router.query;
const { customAttributes: customAttributesStore } = useMobxStore(); const attributes = customAttributes.entityAttributes[entityId] ?? {};
const { entityAttributes, fetchEntityDetails, fetchEntityDetailsLoader } = customAttributesStore;
const attributes = entityAttributes[entityId] ?? {};
// fetch entity details
useEffect(() => {
if (!entityAttributes[entityId]) {
if (!workspaceSlug) return;
fetchEntityDetails(workspaceSlug.toString(), entityId);
}
}, [entityAttributes, entityId, fetchEntityDetails, workspaceSlug]);
const descriptionFields = Object.values(attributes).filter((a) => const descriptionFields = Object.values(attributes).filter((a) =>
DESCRIPTION_FIELDS.includes(a.type) DESCRIPTION_FIELDS.includes(a.type)
@ -52,11 +37,11 @@ export const CustomAttributesDescriptionFields: React.FC<Props> = observer((prop
return ( return (
<> <>
{fetchEntityDetailsLoader ? ( {customAttributes.fetchEntityDetailsLoader ? (
<Loader className="flex items-center gap-2"> <Loader className="space-y-3.5">
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
<Loader.Item height="27px" width="90px" /> <Loader.Item height="35px" />
</Loader> </Loader>
) : ( ) : (
<Disclosure defaultOpen> <Disclosure defaultOpen>

View File

@ -0,0 +1,225 @@
import { useCallback, useState } from "react";
import { useRouter } from "next/router";
// mobx
import { useMobxStore } from "lib/mobx/store-provider";
import { observer } from "mobx-react-lite";
// react-dropzone
import { useDropzone } from "react-dropzone";
// services
import fileService from "services/file.service";
// hooks
import useWorkspaceDetails from "hooks/use-workspace-details";
import useToast from "hooks/use-toast";
// components
// ui
import { Loader, Tooltip } from "components/ui";
// icons
import { Plus, Trash2, X } from "lucide-react";
import { getFileIcon } from "components/icons";
// helpers
import { getFileExtension } from "helpers/attachment.helper";
// types
import { ICustomAttribute } from "types";
type Props = {
entityId: string;
issueId: string;
onChange: (attributeId: string, val: string | string[] | undefined) => void;
projectId: string;
values: { [key: string]: string[] };
};
type FileUploadProps = {
attributeDetails: ICustomAttribute;
className?: string;
issueId: string;
projectId: string;
value: string | undefined;
onChange: (val: string | undefined) => void;
};
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
const UploadFile: React.FC<FileUploadProps> = (props) => {
const { attributeDetails, className = "", onChange, value } = props;
const [isUploading, setIsUploading] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const { workspaceDetails } = useWorkspaceDetails();
const { setToastAlert } = useToast();
const onDrop = useCallback(
(acceptedFiles: File[]) => {
if (!acceptedFiles[0] || !workspaceSlug) return;
const extension = getFileExtension(acceptedFiles[0].name);
if (!attributeDetails.extra_settings?.file_formats?.includes(`.${extension}`)) {
setToastAlert({
type: "error",
title: "Error!",
message: `File format not accepted. Accepted file formats- ${attributeDetails.extra_settings?.file_formats?.join(
", "
)}`,
});
return;
}
const formData = new FormData();
formData.append("asset", acceptedFiles[0]);
formData.append(
"attributes",
JSON.stringify({
name: acceptedFiles[0].name,
size: acceptedFiles[0].size,
})
);
setIsUploading(true);
fileService
.uploadFile(workspaceSlug.toString(), formData)
.then((res) => {
const imageUrl = res.asset;
onChange(imageUrl);
if (value && value !== "" && workspaceDetails)
fileService.deleteFile(workspaceDetails.id, value);
})
.finally(() => setIsUploading(false));
},
[
attributeDetails.extra_settings?.file_formats,
onChange,
setToastAlert,
value,
workspaceDetails,
workspaceSlug,
]
);
const handleRemoveFile = () => {
if (!workspaceDetails || !value || value === "") return;
onChange(undefined);
fileService.deleteFile(workspaceDetails.id, value);
};
const { getRootProps, getInputProps, isDragActive, isDragReject, fileRejections } = useDropzone({
onDrop,
maxSize: MAX_FILE_SIZE,
multiple: false,
disabled: isUploading,
});
const fileError =
fileRejections.length > 0
? `Invalid file type or size (max ${MAX_FILE_SIZE / 1024 / 1024} MB)`
: null;
return (
<div className="flex-shrink-0 truncate space-y-1">
{value && value !== "" ? (
<div className="group flex items-center justify-between gap-1.5 h-10 px-2.5 rounded border border-custom-border-200 text-xs truncate w-full">
<a
href={value}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 flex-grow truncate"
>
<span className="flex-shrink-0 h-6 w-6 grid place-items-center border border-custom-border-200 p-1 rounded-sm">
{getFileIcon(getFileExtension(value))}
</span>
<span className="truncate">
{value.split("/")[value.split("/").length - 1].split("-")[1]}
</span>
</a>
<button
type="button"
className="opacity-0 group-hover:opacity-100 grid place-items-center flex-shrink-0"
onClick={handleRemoveFile}
>
<Trash2 size={12} strokeWidth={1.5} />
</button>
</div>
) : (
<div
{...getRootProps()}
className={`flex items-center text-xs rounded cursor-pointer truncate w-full ${
isDragActive ? "bg-custom-primary-100/10" : ""
} ${isDragReject ? "bg-red-500/10" : ""} ${className}`}
>
<input className="flex-shrink-0" {...getInputProps()} />
<div
className={`border border-dashed flex items-center gap-1.5 h-10 px-2.5 rounded text-custom-text-400 w-full ${
fileError ? "border-red-500" : "border-custom-primary-100"
}`}
>
<span className="bg-custom-primary-100/10 rounded-sm text-custom-primary-100 h-4 w-4 grid place-items-center">
<Plus size={10} strokeWidth={1.5} />
</span>
{isDragActive ? (
<span>Drop here</span>
) : fileError ? (
<span>File error</span>
) : isUploading ? (
<span>Uploading...</span>
) : (
<span>Drag and drop files</span>
)}
</div>
</div>
)}
</div>
);
};
export const CustomAttributesFileUploads: React.FC<Props> = observer((props) => {
const { entityId, onChange, issueId, projectId, values } = props;
const { customAttributes } = useMobxStore();
const attributes = customAttributes.entityAttributes[entityId] ?? {};
const fileUploadFields = Object.values(attributes).filter((a) => a.type === "file");
return (
<>
{customAttributes.fetchEntityDetailsLoader ? (
<Loader className="space-y-3.5">
<Loader.Item height="35px" />
<Loader.Item height="35px" />
<Loader.Item height="35px" />
</Loader>
) : (
<div>
<h5 className="text-sm">File uploads</h5>
<div className="mt-3.5 grid grid-cols-3 gap-4">
{Object.entries(fileUploadFields).map(([attributeId, attribute]) => (
<div key={attributeId}>
<Tooltip tooltipContent={attribute.display_name} position="top-left">
<p className="text-xs text-custom-text-300 truncate">{attribute.display_name}</p>
</Tooltip>
<div className="flex-shrink-0 mt-2">
<UploadFile
attributeDetails={attribute}
issueId={issueId}
onChange={(val) => onChange(attribute.id, val)}
projectId={projectId}
value={values[attribute.id]?.[0] ? values[attribute.id]?.[0] : undefined}
/>
</div>
</div>
))}
</div>
</div>
)}
</>
);
});

View File

@ -1,3 +1,4 @@
export * from "./checkboxes"; export * from "./checkboxes";
export * from "./description-fields"; export * from "./description-fields";
export * from "./file-uploads";
export * from "./select-fields"; export * from "./select-fields";

View File

@ -1,7 +1,3 @@
import { useEffect } from "react";
import { useRouter } from "next/router";
// mobx // mobx
import { useMobxStore } from "lib/mobx/store-provider"; import { useMobxStore } from "lib/mobx/store-provider";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
@ -30,28 +26,15 @@ const SELECT_FIELDS: TCustomAttributeTypes[] = ["datetime", "multi_select", "rel
export const CustomAttributesSelectFields: React.FC<Props> = observer((props) => { export const CustomAttributesSelectFields: React.FC<Props> = observer((props) => {
const { entityId, issueId, onChange, projectId, values } = props; const { entityId, issueId, onChange, projectId, values } = props;
const router = useRouter(); const { customAttributes } = useMobxStore();
const { workspaceSlug } = router.query;
const { customAttributes: customAttributesStore } = useMobxStore(); const attributes = customAttributes.entityAttributes[entityId] ?? {};
const { entityAttributes, fetchEntityDetails, fetchEntityDetailsLoader } = customAttributesStore;
const attributes = entityAttributes[entityId] ?? {};
// fetch entity details
useEffect(() => {
if (!entityAttributes[entityId]) {
if (!workspaceSlug) return;
fetchEntityDetails(workspaceSlug.toString(), entityId);
}
}, [entityAttributes, entityId, fetchEntityDetails, workspaceSlug]);
const selectFields = Object.values(attributes).filter((a) => SELECT_FIELDS.includes(a.type)); const selectFields = Object.values(attributes).filter((a) => SELECT_FIELDS.includes(a.type));
return ( return (
<> <>
{fetchEntityDetailsLoader ? ( {customAttributes.fetchEntityDetailsLoader ? (
<Loader className="flex items-center gap-2"> <Loader className="flex items-center gap-2">
<Loader.Item height="27px" width="90px" /> <Loader.Item height="27px" width="90px" />
<Loader.Item height="27px" width="90px" /> <Loader.Item height="27px" width="90px" />

View File

@ -1,7 +1,9 @@
import React from "react"; import React, { useRef, useState } from "react";
// headless ui // headless ui
import { Menu, Transition } from "@headlessui/react"; import { Menu } from "@headlessui/react";
// hooks
import useDynamicDropdownPosition from "hooks/use-dynamic-dropdown";
// icons // icons
import { Plus } from "lucide-react"; import { Plus } from "lucide-react";
// types // types
@ -13,44 +15,56 @@ type Props = {
onClick: (type: TCustomAttributeTypes) => void; onClick: (type: TCustomAttributeTypes) => void;
}; };
export const TypesDropdown: React.FC<Props> = ({ onClick }) => ( export const TypesDropdown: React.FC<Props> = ({ onClick }) => {
<Menu as="div" className="relative flex-shrink-0 text-left"> const [isOpen, setIsOpen] = useState(false);
{({ open }: { open: boolean }) => (
<>
<Menu.Button className="flex items-center gap-1 text-xs font-medium text-custom-primary-100">
<Plus size={14} strokeWidth={1.5} />
Add Attribute
</Menu.Button>
<Transition
show={open}
as={React.Fragment}
enter="transition ease-out duration-200"
enterFrom="opacity-0 translate-y-1"
enterTo="opacity-100 translate-y-0"
leave="transition ease-in duration-150"
leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1"
>
<Menu.Items className="fixed z-10 mb-2 border-[0.5px] border-custom-border-300 p-1 min-w-[10rem] max-h-60 rounded bg-custom-background-100 text-xs shadow-custom-shadow-rg focus:outline-none overflow-y-auto">
{Object.keys(CUSTOM_ATTRIBUTES_LIST).map((type) => {
const typeMetaData = CUSTOM_ATTRIBUTES_LIST[type as TCustomAttributeTypes];
return ( const buttonRef = useRef<HTMLButtonElement>(null);
<Menu.Item const optionsRef = useRef<HTMLDivElement>(null);
key={type}
as="button" useDynamicDropdownPosition(isOpen, () => setIsOpen(false), buttonRef, optionsRef);
type="button"
onClick={() => onClick(type as TCustomAttributeTypes)} return (
className="flex items-center gap-1 cursor-pointer select-none truncate rounded px-1 py-1.5 hover:bg-custom-background-80 w-full" <Menu as="div" className="flex-shrink-0 text-left">
> {({ open }: { open: boolean }) => {
<typeMetaData.icon size={14} strokeWidth={1.5} /> if (open) {
{typeMetaData.label} if (!isOpen) setIsOpen(true);
</Menu.Item> } else if (isOpen) setIsOpen(false);
);
})} return (
</Menu.Items> <>
</Transition> <Menu.Button
</> ref={buttonRef}
)} className="flex items-center gap-1 text-xs font-medium text-custom-primary-100"
</Menu> >
); <Plus size={14} strokeWidth={1.5} />
Add Attribute
</Menu.Button>
<div className={`${open ? "fixed z-20 top-0 left-0 h-full w-full cursor-auto" : ""}`}>
<Menu.Items
ref={optionsRef}
className="fixed z-10 border-[0.5px] border-custom-border-300 p-1 min-w-[10rem] max-h-60 rounded bg-custom-background-100 text-xs shadow-custom-shadow-rg focus:outline-none overflow-y-auto"
>
{Object.keys(CUSTOM_ATTRIBUTES_LIST).map((type) => {
const typeMetaData = CUSTOM_ATTRIBUTES_LIST[type as TCustomAttributeTypes];
return (
<Menu.Item
key={type}
as="button"
type="button"
onClick={() => onClick(type as TCustomAttributeTypes)}
className="flex items-center gap-1 cursor-pointer select-none truncate rounded px-1 py-1.5 hover:bg-custom-background-80 w-full"
>
<typeMetaData.icon size={14} strokeWidth={1.5} />
{typeMetaData.label}
</Menu.Item>
);
})}
</Menu.Items>
</div>
</>
);
}}
</Menu>
);
};

View File

@ -4,6 +4,7 @@ import { useRouter } from "next/router";
// mobx // mobx
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { useMobxStore } from "lib/mobx/store-provider";
// react-hook-form // react-hook-form
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
// services // services
@ -27,6 +28,7 @@ import { CreateLabelModal } from "components/labels";
import { import {
CustomAttributesCheckboxes, CustomAttributesCheckboxes,
CustomAttributesDescriptionFields, CustomAttributesDescriptionFields,
CustomAttributesFileUploads,
CustomAttributesSelectFields, CustomAttributesSelectFields,
ObjectsSelect, ObjectsSelect,
} from "components/custom-attributes"; } from "components/custom-attributes";
@ -103,6 +105,8 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
const { customAttributes, customAttributeValues } = useMobxStore();
const { const {
register, register,
formState: { errors, isSubmitting, isDirty }, formState: { errors, isSubmitting, isDirty },
@ -133,6 +137,8 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
parent: getValues("parent"), parent: getValues("parent"),
}; };
const entityId = watch("entity");
useEffect(() => { useEffect(() => {
if (isDirty) handleFormDirty(payload); if (isDirty) handleFormDirty(payload);
else handleFormDirty(null); else handleFormDirty(null);
@ -234,6 +240,59 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
const maxDate = targetDate ? new Date(targetDate) : null; const maxDate = targetDate ? new Date(targetDate) : null;
maxDate?.setDate(maxDate.getDate()); maxDate?.setDate(maxDate.getDate());
// fetch entity/object details, including the list of attributes
useEffect(() => {
if (!entityId) return;
if (!customAttributes.entityAttributes[entityId]) {
if (!workspaceSlug) return;
customAttributes.fetchEntityDetails(workspaceSlug.toString(), entityId);
}
}, [customAttributes, entityId, workspaceSlug]);
// fetch issue attribute values
useEffect(() => {
if (!initialData || !initialData.id) return;
if (
!customAttributeValues.issueAttributeValues ||
!customAttributeValues.issueAttributeValues[initialData.id]
) {
if (!workspaceSlug) return;
customAttributeValues
.fetchIssueAttributeValues(workspaceSlug.toString(), projectId, initialData.id)
.then(() => {
const issueAttributeValues =
customAttributeValues.issueAttributeValues?.[initialData.id ?? ""];
if (!issueAttributeValues || issueAttributeValues.length === 0) return;
issueAttributeValues.forEach((attributeValue) => {
if (attributeValue.prop_value)
handleCustomAttributesChange(
attributeValue.id,
attributeValue.prop_value.map((val) => val.value)
);
});
});
} else {
const issueAttributeValues =
customAttributeValues.issueAttributeValues?.[initialData.id ?? ""];
if (!issueAttributeValues || issueAttributeValues.length === 0) return;
issueAttributeValues.forEach((attributeValue) => {
if (attributeValue.prop_value)
handleCustomAttributesChange(
attributeValue.id,
attributeValue.prop_value.map((val) => val.value)
);
});
}
}, [customAttributeValues, handleCustomAttributesChange, initialData, projectId, workspaceSlug]);
return ( return (
<> <>
{projectId && ( {projectId && (
@ -414,17 +473,24 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
/> />
</div> </div>
)} )}
{watch("entity") !== null && ( {entityId !== null && (
<div className="space-y-5"> <div className="space-y-5">
<CustomAttributesDescriptionFields <CustomAttributesDescriptionFields
entityId={watch("entity") ?? ""} entityId={entityId ?? ""}
issueId={watch("id") ?? ""} issueId={watch("id") ?? ""}
onChange={handleCustomAttributesChange} onChange={handleCustomAttributesChange}
projectId={projectId} projectId={projectId}
values={customAttributesList} values={customAttributesList}
/> />
<CustomAttributesCheckboxes <CustomAttributesCheckboxes
entityId={watch("entity") ?? ""} entityId={entityId ?? ""}
issueId={watch("id") ?? ""}
onChange={handleCustomAttributesChange}
projectId={projectId}
values={customAttributesList}
/>
<CustomAttributesFileUploads
entityId={entityId ?? ""}
issueId={watch("id") ?? ""} issueId={watch("id") ?? ""}
onChange={handleCustomAttributesChange} onChange={handleCustomAttributesChange}
projectId={projectId} projectId={projectId}
@ -452,7 +518,7 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
/> />
)} )}
{/* default object properties */} {/* default object properties */}
{watch("entity") === null ? ( {entityId === null ? (
<> <>
{(fieldsToShow.includes("all") || fieldsToShow.includes("priority")) && ( {(fieldsToShow.includes("all") || fieldsToShow.includes("priority")) && (
<Controller <Controller
@ -580,7 +646,7 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
</> </>
) : ( ) : (
<CustomAttributesSelectFields <CustomAttributesSelectFields
entityId={watch("entity") ?? ""} entityId={entityId ?? ""}
issueId={watch("id") ?? ""} issueId={watch("id") ?? ""}
onChange={handleCustomAttributesChange} onChange={handleCustomAttributesChange}
projectId={projectId} projectId={projectId}

View File

@ -92,8 +92,7 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer(
const router = useRouter(); const router = useRouter();
const { workspaceSlug, projectId, cycleId, moduleId, viewId, inboxId } = router.query; const { workspaceSlug, projectId, cycleId, moduleId, viewId, inboxId } = router.query;
const { customAttributeValues: customAttributeValuesStore } = useMobxStore(); const { customAttributeValues } = useMobxStore();
const { createAttributeValue } = customAttributeValuesStore;
const { displayFilters, params } = useIssuesView(); const { displayFilters, params } = useIssuesView();
const { params: calendarParams } = useCalendarIssuesView(); const { params: calendarParams } = useCalendarIssuesView();
@ -452,9 +451,14 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer(
issueResponse.id && issueResponse.id &&
Object.keys(customAttributesList).length > 0 Object.keys(customAttributesList).length > 0
) )
await createAttributeValue(workspaceSlug.toString(), activeProject, issueResponse.id, { await customAttributeValues.createAttributeValue(
issue_properties: customAttributesList, workspaceSlug.toString(),
}); activeProject,
issueResponse.id,
{
issue_properties: customAttributesList,
}
);
if (onSubmit) await onSubmit(payload); if (onSubmit) await onSubmit(payload);
}; };