Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: support drag and drop of files in rfq

Brad Barbine9f8bd4ad651
diff --git a/apps/carbon/app/components/FileDropzone.tsx b/apps/carbon/app/components/FileDropzone.tsx
new file mode 100644
index 0000000000..e8f359d27a
--- /dev/null
+++ b/apps/carbon/app/components/FileDropzone.tsx
@@ -0,0 +1,28 @@
+import React from "react";
+import { useDropzone } from "react-dropzone";
+import { LuUploadCloud } from "react-icons/lu";
+
+interface FileDropzoneProps {
+ onDrop: (acceptedFiles: File[]) => void;
+}
+
+const FileDropzone: React.FC<FileDropzoneProps> = ({ onDrop }) => {
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
+
+ return (
+ <div
+ {...getRootProps()}
+ className={`mt-4 border-2 border-dashed rounded-md p-6 text-center hover:border-primary hover:bg-primary/10 ${
+ isDragActive ? "border-primary bg-primary/10" : "border-muted"
+ }`}
+ >
+ <input {...getInputProps()} />
+ <LuUploadCloud className="mx-auto h-12 w-12 text-muted-foreground" />
+ <p className="mt-2 text-sm text-muted-foreground">
+ Drag and drop some files here, or click to select files
+ </p>
+ </div>
+ );
+};
+
+export default FileDropzone;
diff --git a/apps/carbon/app/components/index.ts b/apps/carbon/app/components/index.ts
index ad27b7e5a0..a1cf76b132 100644
--- a/apps/carbon/app/components/index.ts
+++ b/apps/carbon/app/components/index.ts
@@ -7,6 +7,7 @@ import DocumentPreview from "./DocumentPreview";
import EmployeeAvatar from "./EmployeeAvatar";
import EmployeeAvatarGroup from "./EmployeeAvatarGroup";
import Empty from "./Empty";
+import FileDropzone from "./FileDropzone";
import Hyperlink from "./Hyperlink";
import Location from "./Location";
import New from "./New";
@@ -26,6 +27,7 @@ export {
EmployeeAvatar,
EmployeeAvatarGroup,
Empty,
+ FileDropzone,
Hyperlink,
Location,
New,
diff --git a/apps/carbon/app/hooks/useRealtime.tsx b/apps/carbon/app/hooks/useRealtime.tsx
index e65a19967b..cfb0f1ad08 100644
--- a/apps/carbon/app/hooks/useRealtime.tsx
+++ b/apps/carbon/app/hooks/useRealtime.tsx
@@ -23,6 +23,7 @@ export function useRealtime(table: string, filter?: string) {
filter: filter,
},
(payload) => {
+ console.log({ table, filter, payload });
if (
"companyId" in payload.new &&
payload.new.companyId !== company.id
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
index 65dddd0a0a..0de40a800e 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
@@ -17,47 +17,59 @@ type DocumentIconProps = {
className?: string;
};
+const baseIconClasses = "w-6 h-6 flex-shrink-0";
+
const DocumentIcon = ({ type, className }: DocumentIconProps) => {
switch (type) {
case "Document":
return (
- <BsFileWordFill className={cn("w-6 h-6 text-blue-500", className)} />
+ <BsFileWordFill
+ className={cn(baseIconClasses, "text-blue-500", className)}
+ />
);
case "Spreadsheet":
return (
- <BsFileExcelFill className={cn("w-6 h-6 text-green-700", className)} />
+ <BsFileExcelFill
+ className={cn(baseIconClasses, "text-green-700", className)}
+ />
);
case "Presentation":
return (
- <BsFilePptFill className={cn("w-6 h-6 text-orange-400", className)} />
+ <BsFilePptFill
+ className={cn(baseIconClasses, "text-orange-400", className)}
+ />
);
case "PDF":
return (
- <BsFilePdfFill className={cn("w-6 h-6 text-red-600", className)} />
+ <BsFilePdfFill
+ className={cn(baseIconClasses, "text-red-600", className)}
+ />
);
case "Archive":
- return <BsFileZipFill className={cn("w-6 h-6", className)} />;
+ return <BsFileZipFill className={cn(baseIconClasses, className)} />;
case "Text":
- return <BsFileTextFill className={cn("w-6 h-6", className)} />;
+ return <BsFileTextFill className={cn(baseIconClasses, className)} />;
case "Image":
return (
- <BsFileImageFill className={cn("w-6 h-6 text-yellow-400", className)} />
+ <BsFileImageFill
+ className={cn(baseIconClasses, "text-yellow-400", className)}
+ />
);
case "Video":
return (
<BsFileEarmarkPlayFill
- className={cn("w-6 h-6 text-purple-500", className)}
+ className={cn(baseIconClasses, "text-purple-500", className)}
/>
);
case "Audio":
return (
<BsFileEarmarkPlayFill
- className={cn("w-6 h-6 text-cyan-400", className)}
+ className={cn(baseIconClasses, "text-cyan-400", className)}
/>
);
case "Other":
default:
- return <BsFileEarmarkFill className={cn("w-6 h-6", className)} />;
+ return <BsFileEarmarkFill className={cn(baseIconClasses, className)} />;
}
};
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 8684e1a923..dcaaaa12d0 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -638,6 +638,14 @@ export const salesRfqValidator = z.object({
status: z.enum(salesRFQStatusType).optional(),
});
+export const salesRfqDragValidator = z.object({
+ customerPartId: z.string(),
+ is3DModel: z.boolean().optional(),
+ lineId: z.string().optional(),
+ path: z.string(),
+ salesRfqId: z.string(),
+});
+
export const salesRfqLineValidator = z.object({
id: zfd.text(z.string().optional()),
salesRfqId: z.string().min(20, { message: "RFQ is required" }),
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
index d8b420b68b..1a4f2a5198 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
@@ -21,19 +21,19 @@ import {
toast,
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
+import { useDndContext, useDraggable } from "@dnd-kit/core";
import { Outlet, useRevalidator, useSubmit } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
-import { useDropzone } from "react-dropzone";
import {
+ LuGripVertical,
LuRadioTower,
LuShoppingCart,
LuUpload,
- LuUploadCloud,
} from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
-import { DocumentPreview, Hyperlink } from "~/components";
+import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
@@ -67,7 +67,56 @@ const OpportunityDocuments = ({
[upload]
);
- const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
+ const DraggableCell = ({ attachment }: { attachment: FileObject }) => {
+ const context = useDndContext();
+ const { attributes, listeners, setNodeRef, transform } = useDraggable({
+ id: attachment.id,
+ data: {
+ ...attachment,
+ path: getPath(attachment),
+ },
+ });
+
+ const style = transform
+ ? {
+ transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
+ zIndex: 1000,
+ }
+ : undefined;
+
+ return (
+ <Td ref={setNodeRef} style={style} {...attributes} {...listeners}>
+ <HStack>
+ {context.droppableContainers.size > 0 && <LuGripVertical />}
+ <DocumentIcon type={getDocumentType(attachment.name)} />
+ <Hyperlink onClick={() => download(attachment)}>
+ {["PDF", "Image"].includes(getDocumentType(attachment.name)) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={getDocumentType(attachment.name)}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </Hyperlink>
+ {opportunity?.purchaseOrderDocumentPath === getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuShoppingCart />
+ </Badge>
+ )}
+ {opportunity?.requestForQuoteDocumentPath === getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuRadioTower />
+ </Badge>
+ )}
+ </HStack>
+ </Td>
+ );
+ };
return (
<>
@@ -90,81 +139,47 @@ const OpportunityDocuments = ({
<Tr>
<Th>Name</Th>
<Th>Size</Th>
-
<Th></Th>
</Tr>
</Thead>
<Tbody>
{attachments.length ? (
- attachments.map((attachment) => {
- const type = getDocumentType(attachment.name);
- return (
- <Tr key={attachment.id}>
- <Td>
- <HStack>
- <DocumentIcon type={type} />
- <Hyperlink onClick={() => download(attachment)}>
- {["PDF", "Image"].includes(type) ? (
- <DocumentPreview
- bucket="private"
- pathToFile={getPath(attachment)}
- // @ts-ignore
- type={type}
- >
- {attachment.name}
- </DocumentPreview>
- ) : (
- attachment.name
- )}
- </Hyperlink>
- {opportunity?.purchaseOrderDocumentPath ===
- getPath(attachment) && (
- <Badge variant="secondary">
- <LuShoppingCart />
- </Badge>
- )}
- {opportunity?.requestForQuoteDocumentPath ===
- getPath(attachment) && (
- <Badge variant="secondary">
- <LuRadioTower />
- </Badge>
- )}
- </HStack>
- </Td>
- <Td className="text-xs font-mono">
- {convertKbToString(
- Math.floor((attachment.metadata?.size ?? 0) / 1024)
- )}
- </Td>
- <Td>
- <div className="flex justify-end gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<MdMoreVert />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => download(attachment)}
- >
- Download
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canDelete}
- onClick={() => deleteAttachment(attachment)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- );
- })
+ attachments.map((attachment) => (
+ <Tr key={attachment.id}>
+ <DraggableCell attachment={attachment} />
+ <Td className="text-xs font-mono">
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<MdMoreVert />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() => download(attachment)}
+ >
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ onClick={() => deleteAttachment(attachment)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ ))
) : (
<Tr>
<Td
@@ -177,20 +192,10 @@ const OpportunityDocuments = ({
)}
</Tbody>
</Table>
- <div
- {...getRootProps()}
- className={`mt-4 border-2 border-dashed rounded-md p-6 text-center ${
- isDragActive ? "border-primary bg-primary/10" : "border-muted"
- }`}
- >
- <input {...getInputProps()} />
- <LuUploadCloud className="mx-auto h-12 w-12 text-muted-foreground" />
- <p className="mt-2 text-sm text-muted-foreground">
- Drag and drop some files here, or click to select files
- </p>
- </div>
+ <FileDropzone onDrop={onDrop} />
</CardContent>
</Card>
+
<Outlet />
</>
);
@@ -233,7 +238,7 @@ export const useOpportunityDocuments = ({
return;
}
- toast.success("File deleted successfully");
+ toast.success(`${attachment.name} deleted successfully`);
revalidator.revalidate();
},
[supabase?.storage, getPath, revalidator]
@@ -310,7 +315,7 @@ export const useOpportunityDocuments = ({
if (fileUpload.error) {
toast.error(`Failed to upload file: ${file.name}`);
} else if (fileUpload.data?.path) {
- toast.success(`File uploaded: ${file.name}`);
+ toast.success(`Uploaded: ${file.name}`);
createDocumentRecord({
path: fileUpload.data.path,
name: file.name,
@@ -318,8 +323,9 @@ export const useOpportunityDocuments = ({
});
}
}
+ revalidator.revalidate();
},
- [getPath, createDocumentRecord, supabase]
+ [getPath, createDocumentRecord, supabase, revalidator]
);
return {
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
index ec4833deda..48f6f7ad8e 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
@@ -21,9 +21,9 @@ import {
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
import type { FileObject } from "@supabase/storage-js";
-import { LuAxis3D, LuUpload, LuUploadCloud } from "react-icons/lu";
+import { LuAxis3D, LuUpload } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
-import { DocumentPreview, Hyperlink } from "~/components";
+import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile, ModelUpload } from "~/modules/items";
@@ -34,7 +34,6 @@ import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
import { useCallback } from "react";
-import { useDropzone } from "react-dropzone";
const useOpportunityLineDocuments = ({
id,
@@ -73,7 +72,7 @@ const useOpportunityLineDocuments = ({
return;
}
- toast.success("File deleted successfully");
+ toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
[getPath, supabase?.storage, revalidator]
@@ -179,7 +178,6 @@ const useOpportunityLineDocuments = ({
if (fileUpload.error) {
toast.error(`Failed to upload file: ${file.name}`);
} else if (fileUpload.data?.path) {
- toast.success(`File uploaded: ${file.name}`);
createDocumentRecord({
path: fileUpload.data.path,
name: file.name,
@@ -187,8 +185,9 @@ const useOpportunityLineDocuments = ({
});
}
}
+ revalidator.revalidate();
},
- [getPath, createDocumentRecord, supabase]
+ [getPath, createDocumentRecord, supabase, revalidator]
);
return {
@@ -239,105 +238,48 @@ const OpportunityLineDocuments = ({
[upload]
);
- const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
-
return (
- <Card className="flex-grow">
- <HStack className="justify-between items-start">
- <CardHeader>
- <CardTitle>Files</CardTitle>
- </CardHeader>
- <CardAction>
- <OpportunityLineDocumentForm id={id} type={type} lineId={lineId} />
- </CardAction>
- </HStack>
- <CardContent>
- <Table>
- <Thead>
- <Tr>
- <Th>Name</Th>
- <Th>Size</Th>
- <Th />
- </Tr>
- </Thead>
- <Tbody>
- {modelUpload?.autodeskUrn && (
+ <>
+ <Card className="flex-grow">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <OpportunityLineDocumentForm id={id} type={type} lineId={lineId} />
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table>
+ <Thead>
<Tr>
- <Td>
- <HStack>
- <LuAxis3D className="text-green-500 w-6 h-6" />
- <Hyperlink
- target="_blank"
- onClick={() => viewModel(modelUpload)}
- >
- {modelUpload?.autodeskUrn
- ? modelUpload.modelName
- : "Uploading..."}
- </Hyperlink>
- </HStack>
- </Td>
- <Td>
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor((modelUpload.modelSize ?? 0) / 1024)
- )
- : "--"}
- </Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<MdMoreVert />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => viewModel(modelUpload)}
- >
- View
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canDelete}
- onClick={() => deleteModel(lineId)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ <Th />
</Tr>
- )}
- {files.map((file) => {
- const type = getDocumentType(file.name);
- return (
- <Tr key={file.id}>
+ </Thead>
+ <Tbody>
+ {modelUpload?.autodeskUrn && (
+ <Tr>
<Td>
<HStack>
- <DocumentIcon type={type} />
- <Hyperlink onClick={() => download(file)}>
- {["PDF", "Image"].includes(type) ? (
- <DocumentPreview
- bucket="private"
- pathToFile={getPath(file)}
- // @ts-ignore
- type={type}
- >
- {file.name}
- </DocumentPreview>
- ) : (
- file.name
- )}
+ <LuAxis3D className="text-green-500 w-6 h-6 flex-shrink-0" />
+ <Hyperlink
+ target="_blank"
+ onClick={() => viewModel(modelUpload)}
+ >
+ {modelUpload?.autodeskUrn
+ ? modelUpload.modelName
+ : "Uploading..."}
</Hyperlink>
</HStack>
</Td>
<Td>
- {convertKbToString(
- Math.floor((file.metadata?.size ?? 0) / 1024)
- )}
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
</Td>
<Td>
<div className="flex justify-end w-full">
@@ -350,12 +292,14 @@ const OpportunityLineDocuments = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
- <DropdownMenuItem onClick={() => download(file)}>
- Download
+ <DropdownMenuItem
+ onClick={() => viewModel(modelUpload)}
+ >
+ View
</DropdownMenuItem>
<DropdownMenuItem
disabled={!canDelete}
- onClick={() => deleteFile(file)}
+ onClick={() => deleteModel(lineId)}
>
Delete
</DropdownMenuItem>
@@ -364,34 +308,78 @@ const OpportunityLineDocuments = ({
</div>
</Td>
</Tr>
- );
- })}
- {files.length === 0 && !modelUpload && (
- <Tr>
- <Td
- colSpan={24}
- className="py-8 text-muted-foreground text-center"
- >
- No files
- </Td>
- </Tr>
- )}
- </Tbody>
- </Table>
- <div
- {...getRootProps()}
- className={`mt-4 border-2 border-dashed rounded-md p-6 text-center ${
- isDragActive ? "border-primary bg-primary/10" : "border-muted"
- }`}
- >
- <input {...getInputProps()} />
- <LuUploadCloud className="mx-auto h-12 w-12 text-muted-foreground" />
- <p className="mt-2 text-sm text-muted-foreground">
- Drag and drop some files here, or click to select files
- </p>
- </div>
- </CardContent>
- </Card>
+ )}
+ {files.map((file) => {
+ const type = getDocumentType(file.name);
+ return (
+ <Tr key={file.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <Hyperlink onClick={() => download(file)}>
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(file)}
+ // @ts-ignore
+ type={type}
+ >
+ {file.name}
+ </DocumentPreview>
+ ) : (
+ file.name
+ )}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((file.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<MdMoreVert />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem onClick={() => download(file)}>
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ onClick={() => deleteFile(file)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ );
+ })}
+ {files.length === 0 && !modelUpload && (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ No files
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ <FileDropzone onDrop={onDrop} />
+ </CardContent>
+ </Card>
+ </>
);
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index ffc12e949a..9bda592450 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -9,6 +9,7 @@ import {
HStack,
IconButton,
Kbd,
+ Spinner,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -28,6 +29,7 @@ import { flattenTree } from "~/components/TreeView";
import {
useOptimisticLocation,
usePermissions,
+ useRealtime,
useRouteData,
useUser,
} from "~/hooks";
@@ -57,10 +59,12 @@ export default function QuoteExplorer() {
unitOfMeasureCode: "",
};
- const newQuoteLineDisclosure = useDisclosure({
- defaultIsOpen:
- permissions.can("update", "sales") && quoteData?.lines?.length === 0,
- });
+ useRealtime(
+ "modelUpload",
+ `modelPath=in.(${quoteData?.lines.map((d) => d.modelPath).join(",")})`
+ );
+
+ const newQuoteLineDisclosure = useDisclosure();
const deleteLineDisclosure = useDisclosure();
const [deleteLine, setDeleteLine] = useState<QuotationLine | null>(null);
const isDisabled = quoteData?.quote?.status !== "Draft";
@@ -208,6 +212,10 @@ function QuoteLineItem({ line, isDisabled, onDelete }: QuoteLineItemProps) {
)}
src={`/file/preview/private/${line.thumbnailPath}`}
/>
+ ) : !!line.modelId && !line.thumbnailPath ? (
+ <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">
+ <Spinner className="w-6 h-6 text-muted-foreground" />
+ </div>
) : (
<div
className={cn(
@@ -221,8 +229,10 @@ function QuoteLineItem({ line, isDisabled, onDelete }: QuoteLineItemProps) {
)}
<VStack spacing={0}>
- <span className="font-semibold">{line.itemReadableId}</span>
- <span className="font-mono text-muted-foreground text-xs">
+ <span className="font-semibold line-clamp-1">
+ {line.itemReadableId}
+ </span>
+ <span className="font-mono text-muted-foreground text-xs line-clamp-1">
{line.customerPartId}
{line.customerPartRevision && ` (${line.customerPartRevision})`}
</span>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
index f10b12fe1d..bbe40cc1e1 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
@@ -115,7 +115,7 @@ const QuoteToOrderDrawer = ({
setUploading(true);
});
const file = acceptedFiles[0];
- if (file) upload(file);
+ if (file) upload([file]);
const purchaseOrderDocumentPath = getPath(file);
const { error } = await supabase
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index 15df3f8700..8e309c7d70 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -46,10 +46,7 @@ export default function SalesOrderExplorer() {
addOnCost: 0,
};
- const newSalesOrderLineDisclosure = useDisclosure({
- defaultIsOpen:
- permissions.can("update", "sales") && salesOrderData?.lines?.length === 0,
- });
+ const newSalesOrderLineDisclosure = useDisclosure();
const deleteLineDisclosure = useDisclosure();
const [deleteLine, setDeleteLine] = useState<SalesOrderLine | null>(null);
const isDisabled = salesOrderData?.salesOrder?.status !== "Draft";
@@ -199,9 +196,11 @@ function SalesOrderLineItem({
)}
<VStack spacing={0}>
- <span className="font-semibold">{line.itemReadableId}</span>
- <span className="text-muted-foreground text-xs truncate">
- {line.itemName}
+ <span className="font-semibold line-clamp-1">
+ {line.itemReadableId}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.description}
</span>
</VStack>
</HStack>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index 4570d9528a..66ba8ad945 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -9,6 +9,7 @@ import {
HStack,
IconButton,
Kbd,
+ Spinner,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -17,12 +18,18 @@ import {
VStack,
} from "@carbon/react";
import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { useDroppable } from "@dnd-kit/core";
import { useNavigate, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuImage, LuPlus, LuTrash } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import { Empty } from "~/components";
-import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
+import {
+ useOptimisticLocation,
+ usePermissions,
+ useRealtime,
+ useRouteData,
+} from "~/hooks";
import { path } from "~/utils/path";
import type { SalesRFQ, SalesRFQLine } from "../../types";
import DeleteSalesRFQLine from "./DeleteSalesRFQLine";
@@ -37,10 +44,12 @@ export default function SalesRFQExplorer() {
}>(path.to.salesRfq(rfqId));
const permissions = usePermissions();
- const newSalesRFQLineDisclosure = useDisclosure({
- defaultIsOpen:
- permissions.can("update", "sales") && salesRfqData?.lines?.length === 0,
- });
+ useRealtime(
+ "modelUpload",
+ `modelPath=in.(${salesRfqData?.lines.map((d) => d.modelPath).join(",")})`
+ );
+
+ const newSalesRFQLineDisclosure = useDisclosure();
const deleteLineDisclosure = useDisclosure();
const [deleteLine, setDeleteLine] = useState<SalesRFQLine | null>(null);
@@ -78,13 +87,24 @@ export default function SalesRFQExplorer() {
salesRfqData?.rfqSummary.status ?? ""
);
+ const { setNodeRef: setExplorerRef, isOver: isOverExplorer } = useDroppable({
+ id: "sales-rfq-explorer",
+ });
+
return (
- <>
+ <div
+ ref={setExplorerRef}
+ data-sales-rfq-explorer
+ className={cn(
+ "transition-colors duration-200",
+ isOverExplorer && "bg-primary/10 border-2 border-dashed border-primary"
+ )}
+ >
<VStack className="w-full h-[calc(100vh-99px)] justify-between">
<VStack className="flex-1 overflow-y-auto" spacing={0}>
{salesRfqData?.lines && salesRfqData?.lines?.length > 0 ? (
salesRfqData?.lines.map((line) => (
- <SalesRFQLineItem
+ <DroppableSalesRFQLineItem
key={line.id}
line={line}
isDisabled={isDisabled}
@@ -137,7 +157,40 @@ export default function SalesRFQExplorer() {
{deleteLineDisclosure.isOpen && (
<DeleteSalesRFQLine line={deleteLine!} onCancel={onDeleteCancel} />
)}
- </>
+ </div>
+ );
+}
+
+type DroppableSalesRFQLineItemProps = {
+ line: SalesRFQLine;
+ isDisabled: boolean;
+ onDelete: (line: SalesRFQLine) => void;
+};
+
+function DroppableSalesRFQLineItem({
+ line,
+ isDisabled,
+ onDelete,
+}: DroppableSalesRFQLineItemProps) {
+ const { setNodeRef, isOver } = useDroppable({
+ id: `sales-rfq-line-${line.id}`,
+ data: { lineId: line.id },
+ });
+
+ return (
+ <div
+ ref={setNodeRef}
+ className={cn(
+ "transition-colors duration-200 w-full",
+ isOver && "bg-primary/20 border-2 border-dashed border-primary"
+ )}
+ >
+ <SalesRFQLineItem
+ line={line}
+ isDisabled={isDisabled}
+ onDelete={onDelete}
+ />
+ </div>
);
}
@@ -183,6 +236,10 @@ function SalesRFQLineItem({
className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent"
src={`/file/preview/private/${line.thumbnailPath}`}
/>
+ ) : !!line.modelId && !line.thumbnailPath ? (
+ <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">
+ <Spinner className="w-6 h-6 text-muted-foreground" />
+ </div>
) : (
<div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">
<LuImage className="w-6 h-6 text-muted-foreground" />
@@ -190,12 +247,12 @@ function SalesRFQLineItem({
)}
<VStack spacing={0}>
- <span className="font-semibold">
+ <span className="font-semibold line-clamp-1">
{" "}
{line.customerPartId}
{line.customerPartRevision && ` (${line.customerPartRevision})`}
</span>
- <span className="font-mono text-muted-foreground text-xs">
+ <span className="font-mono text-muted-foreground text-xs line-clamp-1">
{line.itemReadableId}
</span>
</VStack>
diff --git a/apps/carbon/app/modules/shared/ui/CadModelUpload.tsx b/apps/carbon/app/modules/shared/ui/CadModelUpload.tsx
index 6e1b2d916b..c8078083cc 100644
--- a/apps/carbon/app/modules/shared/ui/CadModelUpload.tsx
+++ b/apps/carbon/app/modules/shared/ui/CadModelUpload.tsx
@@ -1,7 +1,7 @@
import { CardHeader, CardTitle, Spinner, cn, toast } from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
import { useDropzone } from "react-dropzone";
-import { HiArrowUpTray } from "react-icons/hi2";
+import { LuUploadCloud } from "react-icons/lu";
const fileSizeLimitMb = 50;
@@ -13,7 +13,7 @@ type CadModelUploadProps = {
onFileChange: (file: File | null) => void;
};
-const supportedFileTypes = [
+export const supportedFileTypes = [
"step",
"stp",
"stl",
@@ -82,7 +82,7 @@ const CadModelUpload = ({
className={cn(
"group flex flex-col flex-grow rounded-lg border border-border bg-gradient-to-tr from-background to-card text-card-foreground shadow-sm w-full",
!hasFile &&
- "cursor-pointer hover:border-primary/30 hover:border-dashed hover:to-primary/10 hover:via-card",
+ "cursor-pointer hover:border-primary/30 hover:border-dashed hover:to-primary/10 hover:via-card border-2 border-dashed",
className
)}
>
@@ -112,10 +112,7 @@ const CadModelUpload = ({
title ? "-mt-16" : "-mt-6"
)}
>
- <HiArrowUpTray
- className="h-10 w-10 text-foreground group-hover:text-primary-foreground"
- aria-hidden="true"
- />
+ <LuUploadCloud className="mx-auto h-12 w-12 text-muted-foreground group-hover:text-primary-foreground" />
</div>
<p className="text-lg text-muted-foreground group-hover:text-foreground mt-8">
Choose file to upload or drag and drop
diff --git a/apps/carbon/app/routes/api+/autodesk.upload.ts b/apps/carbon/app/routes/api+/autodesk.upload.ts
index 1ccddd5099..64d01b244a 100644
--- a/apps/carbon/app/routes/api+/autodesk.upload.ts
+++ b/apps/carbon/app/routes/api+/autodesk.upload.ts
@@ -70,14 +70,14 @@ export async function action({ request }: ActionFunctionArgs) {
await triggerClient.sendEvent({
name: "autodesk.upload",
payload: {
- name,
- modelPath,
companyId,
fileId,
- userId,
itemId,
- salesRfqLineId,
+ modelPath,
+ name,
quoteLineId,
+ salesRfqLineId,
+ userId,
},
});
} catch (err) {
diff --git a/apps/carbon/app/routes/x+/documents+/new.tsx b/apps/carbon/app/routes/x+/documents+/new.tsx
index cc96fee658..f14c89b2f9 100644
--- a/apps/carbon/app/routes/x+/documents+/new.tsx
+++ b/apps/carbon/app/routes/x+/documents+/new.tsx
@@ -5,7 +5,7 @@ import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
import { path, requestReferrer } from "~/utils/path";
-import { error, success } from "~/utils/result";
+import { error } from "~/utils/result";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -50,8 +50,5 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- throw redirect(
- requestReferrer(request) ?? path.to.documents,
- await flash(request, success(`Successfully uploaded ${name}`))
- );
+ throw redirect(requestReferrer(request) ?? path.to.documents);
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
new file mode 100644
index 0000000000..01858e0ea9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -0,0 +1,145 @@
+import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { nanoid } from "nanoid";
+import { triggerClient } from "~/lib/trigger.server";
+import { salesRfqDragValidator, upsertSalesRFQLine } from "~/modules/sales";
+import { upsertModelUpload } from "~/modules/shared";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { rfqId } = params;
+ if (!rfqId) {
+ throw new Error("rfqId not found");
+ }
+
+ const formData = await request.formData();
+ const payload = (formData.get("payload") as string) ?? "{}";
+ const validation = salesRfqDragValidator.safeParse(JSON.parse(payload));
+
+ if (!validation.success) {
+ return json({
+ error: validation.error.message,
+ });
+ }
+
+ const {
+ customerPartId,
+ is3DModel,
+ lineId,
+ path: documentPath,
+ salesRfqId,
+ } = validation.data;
+
+ let targetLineId = lineId;
+ if (!targetLineId) {
+ // we are creating a new line
+ let data = {
+ salesRfqId,
+ customerPartId,
+ quantity: [1],
+ unitOfMeasureCode: "EA",
+ order: 1,
+ };
+ const insertLine = await upsertSalesRFQLine(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertLine.error) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(
+ request,
+ error(insertLine.error, "Failed to insert RFQ line")
+ )
+ );
+ }
+
+ targetLineId = insertLine.data?.id;
+ if (!targetLineId) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(request, error(insertLine, "Failed to insert RFQ line"))
+ );
+ }
+ }
+
+ const fileName = documentPath.split("/").pop();
+ let newPath = "";
+ if (is3DModel) {
+ const fileId = nanoid();
+ const fileExtension = fileName?.split(".").pop();
+ newPath = `${companyId}/models/${fileId}.${fileExtension}`;
+
+ const [recordUpdate, recordCreate] = await Promise.all([
+ client
+ .from("salesRfqLine")
+ .update({ modelUploadId: fileId })
+ .eq("id", targetLineId),
+ upsertModelUpload(client, {
+ id: fileId,
+ modelPath: newPath,
+ companyId,
+ createdBy: userId,
+ }),
+ ]);
+
+ if (recordUpdate.error) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(
+ request,
+ error(recordUpdate.error, "Failed to update RFQ line with model")
+ )
+ );
+ }
+
+ if (recordCreate.error) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(
+ request,
+ error(recordCreate.error, "Failed to insert model record")
+ )
+ );
+ }
+
+ await triggerClient.sendEvent({
+ name: "autodesk.upload",
+ payload: {
+ companyId,
+ fileId,
+ itemId: null,
+ modelPath: newPath,
+ name: fileName,
+ quoteLineId: null,
+ salesRfqLineId: targetLineId,
+ userId,
+ },
+ });
+ } else {
+ newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;
+ }
+
+ // Move the file to the new path
+ const move = await client.storage.from("private").move(documentPath, newPath);
+
+ if (move.error) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(request, error(move.error, "Failed to move file"))
+ );
+ }
+
+ throw redirect(path.to.salesRfqDetails(rfqId));
+}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
index 146fbda5b0..e8a174a327 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
@@ -11,7 +11,7 @@ import { error } from "~/utils/result";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- create: "parts",
+ create: "sales",
});
const { rfqId } = params;
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
index ddd71c4193..37678f0b1b 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -4,22 +4,28 @@ import {
ResizablePanel,
ResizablePanelGroup,
ScrollArea,
+ toast,
VStack,
type JSONContent,
} from "@carbon/react";
+import type { DragEndEvent } from "@dnd-kit/core";
+import { DndContext } from "@dnd-kit/core";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { Outlet } from "@remix-run/react";
+import { Outlet, useFetcher, useParams } from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import { useCallback, useEffect } from "react";
import type { SalesRFQLine } from "~/modules/sales";
import {
- SalesRFQBreadcrumbs,
- SalesRFQExplorer,
- SalesRFQHeader,
getOpportunityBySalesRFQ,
getOpportunityDocuments,
getSalesRFQ,
getSalesRFQLines,
+ SalesRFQBreadcrumbs,
+ SalesRFQExplorer,
+ SalesRFQHeader,
} from "~/modules/sales";
+import { supportedFileTypes } from "~/modules/shared/ui/CadModelUpload";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import type { Handle } from "~/utils/handle";
@@ -91,42 +97,95 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function SalesRFQRoute() {
+ const { rfqId } = useParams();
+ if (!rfqId) throw new Error("Could not find rfqId");
+ const fetcher = useFetcher<{ error: string }>();
+
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data?.error);
+ }
+ }, [fetcher.data]);
+
+ const handleDrop = useCallback(
+ (document: FileObject & { path: string }, targetId: string) => {
+ console.log({ document });
+ const fileName = document.name.split(".").slice(0, -1).join(".");
+ const fileExtension = document.name.split(".").pop()?.toLowerCase();
+ const is3DModel = fileExtension
+ ? supportedFileTypes.includes(fileExtension)
+ : false;
+
+ const formData = new FormData();
+
+ const payload = {
+ customerPartId: fileName,
+ is3DModel: is3DModel ? true : undefined,
+ lineId: targetId.startsWith("sales-rfq-line-")
+ ? targetId.replace("sales-rfq-line-", "")
+ : undefined,
+ path: document.path,
+ salesRfqId: rfqId,
+ };
+
+ formData.append("payload", JSON.stringify(payload));
+
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.salesRfqDrag(rfqId),
+ });
+ },
+ [fetcher, rfqId]
+ );
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ const { over, active } = event;
+ if (over) {
+ handleDrop(
+ active.data.current as unknown as FileObject & { path: string },
+ over.id as string
+ );
+ }
+ };
+
return (
- <div className="flex flex-col h-[calc(100vh-49px)] w-full">
- <SalesRFQHeader />
- <div className="flex h-[calc(100vh-99px)] w-full">
- <div className="flex h-full w-full overflow-y-auto">
- <div className="flex flex-grow overflow-hidden">
- <ClientOnly fallback={null}>
- {() => (
- <ResizablePanelGroup direction="horizontal">
- <ResizablePanel
- order={1}
- minSize={10}
- defaultSize={20}
- className="bg-card h-full"
- >
- <ScrollArea className="h-[calc(100vh-99px)]">
- <div className="grid w-full h-full overflow-hidden">
- <SalesRFQExplorer />
- </div>
- </ScrollArea>
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel order={2}>
- <ScrollArea className="h-[calc(100vh-99px)]">
- <VStack spacing={2} className="p-2">
- <SalesRFQBreadcrumbs />
- <Outlet />
- </VStack>
- </ScrollArea>
- </ResizablePanel>
- </ResizablePanelGroup>
- )}
- </ClientOnly>
+ <DndContext onDragEnd={handleDragEnd}>
+ <div className="flex flex-col h-[calc(100vh-49px)] w-full">
+ <SalesRFQHeader />
+ <div className="flex h-[calc(100vh-99px)] w-full">
+ <div className="flex h-full w-full overflow-y-auto">
+ <div className="flex flex-grow overflow-hidden">
+ <ClientOnly fallback={null}>
+ {() => (
+ <ResizablePanelGroup direction="horizontal">
+ <ResizablePanel
+ order={1}
+ minSize={10}
+ defaultSize={20}
+ className="bg-card h-full z-0"
+ >
+ <ScrollArea className="h-[calc(100vh-99px)]">
+ <div className="grid w-full h-full overflow-hidden">
+ <SalesRFQExplorer />
+ </div>
+ </ScrollArea>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel order={2} className="z-1">
+ <ScrollArea className="h-[calc(100vh-99px)]">
+ <VStack spacing={2} className="p-2">
+ <SalesRFQBreadcrumbs />
+ <Outlet />
+ </VStack>
+ </ScrollArea>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ )}
+ </ClientOnly>
+ </div>
</div>
</div>
</div>
- </div>
+ </DndContext>
);
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 4d8ad8f965..5bdeab09fd 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -647,6 +647,7 @@ export const path = {
generatePath(`${x}/sales-rfq/${id}/convert`),
salesRfqDetails: (id: string) =>
generatePath(`${x}/sales-rfq/${id}/details`),
+ salesRfqDrag: (id: string) => generatePath(`${x}/sales-rfq/${id}/drag`),
salesRfqFavorite: `${x}/sales/rfqs/favorite`,
salesRfqLine: (id: string, lineId: string) =>
generatePath(`${x}/sales-rfq/${id}/${lineId}/details`),
diff --git a/packages/react/src/AutodeskViewer.tsx b/packages/react/src/AutodeskViewer.tsx
index 197bca585d..f9a7b9760b 100644
--- a/packages/react/src/AutodeskViewer.tsx
+++ b/packages/react/src/AutodeskViewer.tsx
@@ -1,6 +1,33 @@
import React, { useEffect, useRef, useState } from "react";
import { cn } from "./utils/cn";
+// Define Autodesk namespace and types
+declare namespace Autodesk {
+ namespace Viewing {
+ class GuiViewer3D {
+ constructor(container: HTMLElement, config?: object);
+ start(): void;
+ setTheme(theme: string): void;
+ resize(): void;
+ loadDocumentNode(doc: Document, node: any): Promise<void>;
+ loadExtension(extension: string): Promise<void>;
+ toolbar: { setVisible(visible: boolean): void };
+ setLightPreset(preset: number): void;
+ finish(): void;
+ }
+ class Document {
+ static load(
+ urn: string,
+ onSuccess: (doc: Document) => void,
+ onFailure: (errorCode: number, errorMsg: string, errors: any) => void
+ ): void;
+ getRoot(): { getDefaultGeometry(): any };
+ }
+ function Initializer(options: any, callback: () => void): void;
+ function shutdown(): void;
+ }
+}
+
interface ForgeViewerProps {
className?: string;
urn: string;
@@ -31,7 +58,12 @@ const AutodeskViewer: React.FC<ForgeViewerProps> = ({
const viewerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
- if (!urn || !accessToken || !viewerRef.current || !Autodesk) {
+ if (
+ !urn ||
+ !accessToken ||
+ !viewerRef.current ||
+ typeof Autodesk === "undefined"
+ ) {
return;
}
@@ -51,7 +83,7 @@ const AutodeskViewer: React.FC<ForgeViewerProps> = ({
};
const viewer = new Autodesk.Viewing.GuiViewer3D(
- viewerRef.current,
+ viewerRef.current!,
viewerOptions
);
viewer.start();
diff --git a/packages/react/src/hooks/useThrottle.ts b/packages/react/src/hooks/useThrottle.ts
index 1444fd7277..165804a731 100644
--- a/packages/react/src/hooks/useThrottle.ts
+++ b/packages/react/src/hooks/useThrottle.ts
@@ -21,7 +21,9 @@ export default function useThrottle<T extends (...args: any[]) => any>(
}
timeout.current = setTimeout(() => {
- fn(...lastArgs.current);
+ if (lastArgs.current) {
+ fn(...lastArgs.current);
+ }
timeout.current = undefined;
}, delay);
};