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.

fix: save debounced editor onchange on dismount

Brad Barbind5d08f1c15d3
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index 0c388401b9..7d35d2aab0 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -191,14 +191,18 @@ const BillOfMaterial = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.methodMaterialsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.methodMaterialsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 244b8a13e8..a1d23815f7 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -215,14 +215,18 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- sortOrderFetcher.submit(formData, {
- method: "post",
- action: path.to.methodOperationsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, {
+ method: "post",
+ action: path.to.methodOperationsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
diff --git a/apps/carbon/app/modules/people/ui/Attributes/AttributeCategoryDetail.tsx b/apps/carbon/app/modules/people/ui/Attributes/AttributeCategoryDetail.tsx
index 34423a2347..e9e60ac541 100644
--- a/apps/carbon/app/modules/people/ui/Attributes/AttributeCategoryDetail.tsx
+++ b/apps/carbon/app/modules/people/ui/Attributes/AttributeCategoryDetail.tsx
@@ -90,11 +90,15 @@ const AttributeCategoryDetail = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- sortOrderFetcher.submit(formData, { method: "post" });
- }, 500);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, { method: "post" });
+ },
+ 1000,
+ true
+ );
const deleteModal = useDisclosure();
const [selectedAttribute, setSelectedAttribute] = useState<
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index af220ce7a9..560a019942 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -200,14 +200,18 @@ const JobBillOfMaterial = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.jobMaterialsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.jobMaterialsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index d2ae2610c0..8f205c4584 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -248,14 +248,18 @@ const JobBillOfProcess = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- sortOrderFetcher.submit(formData, {
- method: "post",
- action: path.to.jobOperationsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, {
+ method: "post",
+ action: path.to.jobOperationsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
@@ -270,31 +274,35 @@ const JobBillOfProcess = ({
});
}, []);
- const onUpdateWorkInstruction = useDebounce(async (content: JSONContent) => {
- if (!permissions.can("update", "parts")) return;
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === selectedItemId
- ? {
- ...item,
- data: {
- ...item.data,
- workInstruction: content,
- },
- }
- : item
- )
- );
- if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await carbon
- ?.from("jobOperation")
- .update({
- workInstruction: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", selectedItemId!);
- }, 2500);
+ const onUpdateWorkInstruction = useDebounce(
+ async (content: JSONContent) => {
+ if (!permissions.can("update", "parts")) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === selectedItemId
+ ? {
+ ...item,
+ data: {
+ ...item.data,
+ workInstruction: content,
+ },
+ }
+ : item
+ )
+ );
+ if (selectedItemId !== null && !isTemporaryId(selectedItemId))
+ await carbon
+ ?.from("jobOperation")
+ .update({
+ workInstruction: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", selectedItemId!);
+ },
+ 2500,
+ true
+ );
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobNotes.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobNotes.tsx
index 8f5d8a095b..fd5be1f6c7 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobNotes.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobNotes.tsx
@@ -55,16 +55,20 @@ const JobNotes = ({
return getPrivateUrl(result.data.path);
};
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
- await carbon
- ?.from("job")
- .update({
- notes: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", id!);
- }, 2500);
+ const onUpdateInternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from("job")
+ .update({
+ notes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
if (!id) return null;
diff --git a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
index 68f4df7076..a4269b3ce5 100644
--- a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
@@ -57,16 +57,20 @@ const OpportunityLineNotes = ({
return getPrivateUrl(result.data.path);
};
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
- await carbon
- ?.from(table)
- .update({
- [table === "salesRfqLine" ? "internalNotes" : "notes"]: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", id!);
- }, 2500);
+ const onUpdateInternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ [table === "salesRfqLine" ? "internalNotes" : "notes"]: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
if (!id) return null;
diff --git a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
index 157152aed1..b3b4b4bd15 100644
--- a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
@@ -68,27 +68,35 @@ const OpportunityNotes = ({
return getPrivateUrl(result.data.path);
};
- const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {
- await carbon
- ?.from(table)
- .update({
- externalNotes: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", id!);
- }, 2500);
+ const onUpdateExternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ externalNotes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
- await carbon
- ?.from(table)
- .update({
- internalNotes: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", id!);
- }, 2500);
+ const onUpdateInternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ internalNotes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
if (!id) return null;
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index f37ab591f7..a15bcfaf87 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -199,14 +199,18 @@ const QuoteBillOfMaterial = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.quoteMaterialsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.quoteMaterialsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 7e07eacc01..4206e5cb82 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -228,14 +228,18 @@ const QuoteBillOfProcess = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- sortOrderFetcher.submit(formData, {
- method: "post",
- action: path.to.quoteOperationsOrder,
- });
- }, 1000);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, {
+ method: "post",
+ action: path.to.quoteOperationsOrder,
+ });
+ },
+ 1000,
+ true
+ );
const onCloseOnDrag = useCallback(() => {
setItems((prevItems) => {
@@ -250,31 +254,35 @@ const QuoteBillOfProcess = ({
});
}, []);
- const onUpdateWorkInstruction = useDebounce(async (content: JSONContent) => {
- if (!permissions.can("update", "parts")) return;
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === selectedItemId
- ? {
- ...item,
- data: {
- ...item.data,
- workInstruction: content,
- },
- }
- : item
- )
- );
- if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await carbon
- ?.from("quoteOperation")
- .update({
- workInstruction: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", selectedItemId!);
- }, 2500);
+ const onUpdateWorkInstruction = useDebounce(
+ async (content: JSONContent) => {
+ if (!permissions.can("update", "parts")) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === selectedItemId
+ ? {
+ ...item,
+ data: {
+ ...item.data,
+ workInstruction: content,
+ },
+ }
+ : item
+ )
+ );
+ if (selectedItemId !== null && !isTemporaryId(selectedItemId))
+ await carbon
+ ?.from("quoteOperation")
+ .update({
+ workInstruction: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", selectedItemId!);
+ },
+ 2500,
+ true
+ );
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx
index 6b59ff481e..ba4ab7ac1d 100644
--- a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx
@@ -114,11 +114,15 @@ const CustomFieldCategoryDetail = ({
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- sortOrderFetcher.submit(formData, { method: "post" });
- }, 500);
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, { method: "post" });
+ },
+ 1000,
+ true
+ );
const deleteModal = useDisclosure();
const [selectedCustomField, setSelectedCustomField] = useState<
diff --git a/apps/carbon/app/routes/x+/settings+/terms.tsx b/apps/carbon/app/routes/x+/settings+/terms.tsx
index 85d328625f..7265754c48 100644
--- a/apps/carbon/app/routes/x+/settings+/terms.tsx
+++ b/apps/carbon/app/routes/x+/settings+/terms.tsx
@@ -70,35 +70,44 @@ export default function Terms() {
setPurchasingTermsStatus("draft");
onUpdatePurchasingTerms(content);
};
- const onUpdatePurchasingTerms = useDebounce(async (content: JSONContent) => {
- if (!carbon) return;
- const { error } = await carbon
- .from("terms")
- .update({
- purchasingTerms: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", companyId);
- if (!error) setPurchasingTermsStatus("saved");
- }, 2500);
+ const onUpdatePurchasingTerms = useDebounce(
+ async (content: JSONContent) => {
+ if (!carbon) return;
+ const { error } = await carbon
+ .from("terms")
+ .update({
+ purchasingTerms: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", companyId);
+ if (!error) setPurchasingTermsStatus("saved");
+ },
+ 2500,
+ true
+ );
const handleUpdateSalesTerms = (content: JSONContent) => {
setSalesTermsStatus("draft");
onUpdateSalesTerms(content);
};
- const onUpdateSalesTerms = useDebounce(async (content: JSONContent) => {
- setSalesTermsStatus("draft");
- await carbon
- ?.from("terms")
- .update({
- salesTerms: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", companyId);
- setSalesTermsStatus("saved");
- }, 2500);
+
+ const onUpdateSalesTerms = useDebounce(
+ async (content: JSONContent) => {
+ setSalesTermsStatus("draft");
+ await carbon
+ ?.from("terms")
+ .update({
+ salesTerms: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", companyId);
+ setSalesTermsStatus("saved");
+ },
+ 2500,
+ true
+ );
const onUploadImage = async (file: File) => {
// Implement image upload logic here
diff --git a/packages/react/src/hooks/useDebounce.ts b/packages/react/src/hooks/useDebounce.ts
index cf3875afa8..e2766c71e1 100644
--- a/packages/react/src/hooks/useDebounce.ts
+++ b/packages/react/src/hooks/useDebounce.ts
@@ -1,22 +1,38 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
/**
* A function that you call with a debounce delay, the function will only be called after the delay has passed
*
* @param fn The function to debounce
* @param delay In ms
+ * @param executeOnUnmount Whether to execute the pending function when component unmounts
*/
export default function useDebounce<T extends (...args: any[]) => any>(
fn: T,
- delay: number
+ delay: number,
+ executeOnUnmount: boolean = false
) {
const timeout = useRef<ReturnType<typeof setTimeout>>();
+ const argsRef = useRef<Parameters<T>>();
+
+ useEffect(() => {
+ return () => {
+ if (executeOnUnmount && timeout.current && argsRef.current) {
+ clearTimeout(timeout.current);
+ fn(...argsRef.current);
+ } else if (timeout.current) {
+ clearTimeout(timeout.current);
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [executeOnUnmount]);
return (...args: Parameters<T>) => {
if (timeout.current) {
clearTimeout(timeout.current);
}
+ argsRef.current = args;
timeout.current = setTimeout(() => {
fn(...args);
}, delay);
diff --git a/packages/react/src/hooks/useThrottle.ts b/packages/react/src/hooks/useThrottle.ts
index 165804a731..caa48e7fda 100644
--- a/packages/react/src/hooks/useThrottle.ts
+++ b/packages/react/src/hooks/useThrottle.ts
@@ -1,18 +1,32 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
/**
* A function that you call with a throttle delay, the function will be called at most once per delay
*
* @param fn The function to throttle
* @param delay In ms
+ * @param executeOnUnmount Whether to execute the pending function when component unmounts
*/
export default function useThrottle<T extends (...args: any[]) => any>(
fn: T,
- delay: number
+ delay: number,
+ executeOnUnmount: boolean = false
) {
const timeout = useRef<ReturnType<typeof setTimeout>>();
const lastArgs = useRef<Parameters<T>>();
+ useEffect(() => {
+ return () => {
+ if (executeOnUnmount && timeout.current && lastArgs.current) {
+ clearTimeout(timeout.current);
+ fn(...lastArgs.current);
+ } else if (timeout.current) {
+ clearTimeout(timeout.current);
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [executeOnUnmount]);
+
return (...args: Parameters<T>) => {
lastArgs.current = args;