for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (!currentSet) currentSet = set1;
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
// console.log("Actual Text :", text);
return text; // do not convert to lowercase here
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal) ? conditionsVal : [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
const duplicateGroupsMap = useMemo(() => {
// groups: array of arrays of duplicate rules with length > 1
let allRules = [];
if (activeTab === "ticketcreate") allRules = ticketCreationRules;
else if (activeTab === "ticketupdate") allRules = ticketUpdateRules;
else if (activeTab === "hourly") allRules = hourlyTriggerRules;
// group duplicates, filtered active only
const groups = groupDuplicates(allRules).filter((g) => g.length > 1);
// Map rule_id -> isFirstInGroup flag (true only for first rule of each duplicate group)
const firstRuleIds = new Set();
groups.forEach((group) => {
if (group.length > 0) {
firstRuleIds.add(group[0].id);
}
});
// Return structure for lookup: firstRuleIds set + flattened set of all duplicate IDs
const duplicateRuleIds = new Set(groups.flat().map((r) => r.id));
return { firstRuleIds, duplicateRuleIds };
// let groups = [];
// if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
// else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
// else if (activeTab === "hourly") groups = hourlyRuleGroups;
Certainly! Let's focus on the checkAndSetButtonState function and explain its purpose and workings in the given React component.
What is checkAndSetButtonState?
checkAndSetButtonState is an asynchronous function designed to:
Check the status of some kind of rules database readiness flag (RulesDB) stored in the client's database.
Set the state of the component accordingly to enable or disable interactions that depend on the rules database being ready.
Manage a polling interval to periodically re-check the database readiness if the rules DB isn't ready yet.
Handle errors, for example when the database key is not found.
Where and how is it used?
It is called once on component mount inside a useEffect hook.
If the rules database is not "ready", this function sets a timer to check again after 60 seconds.
If the rules database is ready, it clears any polling interval and updates state to reflect readiness.
It updates two pieces of state:
setIsRulesDBReady: Determines if rules are ready for use.
setLoadingBannerVisible: Shows or hides a loading banner/message about waiting for rules to be ready.
Breakdown of the function
const checkAndSetButtonState = async () => {
try {
// Attempt to fetch a 'RulesDB' stored value from the client's DB
const storedvalue1 = await client.db.get("RulesDB");
// Check if the stored value indicates readiness
const isButtonEnabled = !!storedvalue1.stored;
if (isButtonEnabled) {
// If ready, update states to enable functionality and hide banner
setIsRulesDBReady(true);
setLoadingBannerVisible(false);
// Clear any existing polling interval
if (intervalIdRef.current) {
clearInterval(intervalIdRef.current);
intervalIdRef.current = null;
}
} else {
// If not ready, mark rules as not ready, show banner
setIsRulesDBReady(false);
setLoadingBannerVisible(true);
// Start checking every 60 seconds if there's no interval already set
if (!intervalIdRef.current) {
intervalIdRef.current = setInterval(checkAndSetButtonState, 60000);
}
}
} catch (error) {
// Handle the error case such as RulesDB not found (404)
if (error.status === 404) {
setIsRulesDBReady(false);
setLoadingBannerVisible(true);
// Clear the polling interval if any
if (intervalIdRef.current) {
clearInterval(intervalIdRef.current);
intervalIdRef.current = null;
}
}
}
};
Important details:
Client database access:
It uses client.db.get("RulesDB") to read from some persistent storage or indexedDB, which stores the key "RulesDB" and expects a property stored within it.
State updates:
isRulesDBReady — Used to enable or disable certain UI parts depending on readiness of the rules data.
loadingBannerVisible — Shows a spinner and message while waiting for rules to be ready.
Interval polling:
If the rules DB is not ready, it sets a 60-seconds interval (setInterval(checkAndSetButtonState, 60000)) to keep checking.
Once ready, or on error (404), it cleans up the interval to avoid unnecessary checks.
Error handling:
If the error status is 404 (not found), it assumes the rules DB is not ready, and handles cleanup same as above.
No explicit action is taken for other types of errors, but it gracefully avoids breaking.
Why is this needed?
This function is important because it:
Allows the UI to reactively adapt to when the rules data is available.
Provides a user-friendly waiting experience by showing a loading banner or spinner.
Avoids repeated manual refreshes by implementing automated polling in the background.
Prevents crashes or broken interactions by controlling the app flow until required data is ready.
Where in the component is it used?
Right here, in a useEffect hook that runs after component mounts:
checkAndSetButtonState checks if the rules-related data (RulesDB) is ready.
If data is ready, it enables UI elements and stops polling.
If not ready, it shows a loading banner and starts polling every 60 seconds.
It also handles error cases gracefully.
The function helps to make the UI dynamic and responsive to backend state changes without user intervention.
If you want me to explain any other parts or modify this for your needs, let me know!
async function checkAndSetButtonState1(data, containerid) {
try {
localStorage.setItem("checkState_data", JSON.stringify(data));
localStorage.setItem("checkState_containerid", containerid);
console.log("automationtypeid inside checkAndSetButtonState",data);
console.log("Initially stored all value from RulesDB:", storedvalue1);
console.log("creationtotal",storedvalue1.creationTotal);
console.log("hourlyTotal",storedvalue1.hourlyTotal);
console.log("updateTotal",storedvalue1.updateTotal);
console.log("Initial stored true/false value from RulesDB:", storedvalue1.stored);
if (containerid === "Ticketcreation" && storedvalue1.creationTotal > 0) {
showLoader("Ticketcreation");
const duration = getDurationForTotal(storedvalue1.creationTotal);
if (typeof duration !== "number" || isNaN(duration)) {
console.error("❌ Invalid duration calculated. Skipping timer setup.");
return;
}
console.log(`✅ Timer condition met. Setting timer for ${duration} seconds.`);
const container = document.getElementById("Ticketcreation");
if (!container) {
console.error("❌ Ticketcreation container not found.");
return;
}
const timerId = "simple-timer-Ticketcreation";
if (document.getElementById(timerId)) {
console.log("⚠️ Timer already running for Ticketcreation. Skipping new timer setup.");
return;
}
// Create timer
const timerDiv = document.createElement("div");
timerDiv.id = timerId;
timerDiv.style.cssText = `
position: fixed;
top: 63%;
left: 50%;
transform: translateX(-50%);
color: black;
padding: 10px 20px;
border-radius: 5px;
font-family: sans-serif;
font-size: 16px;
z-index: 9999;
`;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${duration} sec...`;
container.appendChild(timerDiv);
let remaining = duration;
const interval = setInterval(() => {
remaining--;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
if (remaining <= 0) {
clearInterval(interval);
timerDiv.remove();
console.log("Ticketcreation timer ended. Calling handleDuplicateRulestype(1).");
handleDuplicateRulestype(1);
}
}, 1000);
}
else if (containerid === "HourlyTriggers" && storedvalue1.hourlyTotal > 0) {
showLoader("HourlyTriggers");
const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
const totalDuration = creationDuration + hourlyDuration;
if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
console.error("❌ Invalid duration calculated. Skipping timer setup.");
return;
}
console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
const container = document.getElementById("HourlyTriggers");
if (!container) {
console.error("❌ HourlyTriggers container not found.");
return;
}
const timerId = "simple-timer-HourlyTriggers";
if (document.getElementById(timerId)) {
console.log("⚠️ Timer already running for HourlyTriggers. Skipping new timer setup.");
return;
}
// Create timer
const timerDiv = document.createElement("div");
timerDiv.id = timerId;
timerDiv.style.cssText = `
position: fixed;
top: 63%;
left: 50%;
transform: translateX(-50%);
color: black;
padding: 10px 20px;
border-radius: 5px;
font-family: sans-serif;
font-size: 16px;
z-index: 9999;
`;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
container.appendChild(timerDiv);
let remaining = totalDuration;
const interval = setInterval(() => {
remaining--;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
if (remaining <= 0) {
clearInterval(interval);
timerDiv.remove();
console.log("✅ HourlyTriggers timer ended. Calling handleDuplicateRulestype(3).");
handleDuplicateRulestype(3);
}
}, 1000);
}
else if (containerid === "TicketUpdates" && storedvalue1.updateTotal > 0) {
showLoader("TicketUpdates");
const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
const updateDuration = getDurationForTotal(storedvalue1.updateTotal);
const totalDuration = creationDuration + hourlyDuration + updateDuration;
if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
console.error("❌ Invalid duration calculated. Skipping timer setup.");
return;
}
console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
const timerId = "simple-timer-TicketUpdates";
if (document.getElementById(timerId)) {
console.log("⚠️ Timer already running for TicketUpdates. Skipping new timer setup.");
return;
}
const container = document.getElementById("TicketUpdates");
if (!container) {
console.error("❌ TicketUpdates container not found.");
return;
}
// Create the timer element
const timerDiv = document.createElement("div");
timerDiv.id = timerId;
timerDiv.style.cssText = `
position: fixed;
top: 63%;
left: 50%;
transform: translateX(-50%);
color: black;
padding: 10px 20px;
border-radius: 5px;
font-family: sans-serif;
font-size: 16px;
z-index: 9999;
`;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
container.appendChild(timerDiv);
let remaining = totalDuration;
const interval = setInterval(() => {
remaining--;
timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
if (remaining <= 0) {
clearInterval(interval);
timerDiv.remove();
console.log("✅ TicketUpdates timer ended. Calling handleDuplicateRulestype(4).");
handleDuplicateRulestype(4);
}
}, 1000);
}
if (
storedvalue1.creationTotal === 0 ||
storedvalue1.hourlyTotal === 0 ||
storedvalue1.updateTotal === 0
) {
await initializeDatabase();
}
if(containerid === "Ticketcreation" && storedvalue1.creationTotal === 0){
handleDuplicateRulestype(1);
} else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0){
handleDuplicateRulestype(3);
}else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0)
{
handleDuplicateRulestype(4);
}
if (containerid === "Ticketcreation" &&
Number(storedvalue1.creationTotal) === 0 &&
storedvalue1.stored === true
)
{
handleDuplicateRulestype(1);
} else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0 && storedvalue1.stored === true){
handleDuplicateRulestype(3);
}else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0 && storedvalue1.stored === true)
{
handleDuplicateRulestype(4);
}
} catch (error) {
if (error.status === 404) {
console.warn("⚠️ RulesDB not found, assuming first-time install.");
const button = document.querySelector("fw-button");
if (button) {
button.disabled = true;
}
} else {
console.error("❌ Error retrieving stored value from RulesDB:", error);
}
}
}
how these both runs
Great question! You’ve presented two different functions — the original checkAndSetButtonState and the new checkAndSetButtonState1 — that both seem concerned with checking the state of some stored rules data and updating UI or timers accordingly.
Let's explain how these two functions work individually, and then how they could operate together or be used in the component’s lifecycle.
1. Original checkAndSetButtonState (from your main component)
What it does:
Checks if a global "RulesDB" readiness flag exists in client DB.
Updates React state variables isRulesDBReady (boolean) and loadingBannerVisible (flag to show spinner/message).
Sets up or clears a polling interval (runs every 60 seconds) to periodically re-check readiness.
Designed to control when the UI can allow users to fetch or interact with rule data.
React-based: mainly updates state to inform component rendering logic.
When it runs:
Called once on component mount in useEffect.
Polls every 60 seconds if DB not ready.
Stops polling as soon as storedvalue1.stored is true.
2. New checkAndSetButtonState1(data, containerid) function (your added function)
What it does:
Accepts a data argument (likely a rules DB snapshot or storedvalue1 from the DB).
Accepts a containerid (string like "Ticketcreation", "HourlyTriggers", or "TicketUpdates").
Saves data and containerid to localStorage for persistence.
Logs various fields from the data to console for diagnostics.
Based on containerid and data totals (creationTotal, hourlyTotal, updateTotal), it:
Shows a loader UI (showLoader(containerid)).
Calculates a duration with some helper getDurationForTotal.
Creates a visible timer overlay DIV attached to the container element with a countdown message.
Runs a countdown interval, updating timer text every second.
When timer expires, removes the DOM timer element and calls handleDuplicateRulestype() function with numeric arg corresponding to the container ID (1 for creation, 3 for hourly, 4 for update).
If any of the totals in the data are zero, it calls initializeDatabase() (to presumably refresh or initialize the DB).
Has defensive checks to skip if timers already run or containers missing.
Handles 404 errors by disabling buttons and logs errors.
When it runs:
Appears to run after fetching or loading data to control user messaging about data processing states.
Runs for specific container types independently.
Directly manipulates DOM elements (timers in containers).
How do these two functions run together or relate?
Your first function:
checkAndSetButtonState is like a global readiness checker for your entire rules database.
Controls overall loading spinner and enables/disables UI based on DB readiness.
Manages polling so the app periodically rechecks until DB is ready.
Your second function:
**checkAndSetButtonState1 acts per-container, per-automation-type, managing timers/messages for the user inside specific UI sections.
It depends on data results (how many records are pending for processing in each category).
Shows timed messages/countdowns when the data is being processed asynchronously.
Calls further functions (handleDuplicateRulestype) once timer ends to proceed with next stages.
Typical usage scenario (How they complement):
App loads:
checkAndSetButtonState runs initially.
It tries to read the global RulesDB status.
If not ready, shows loading banner and starts polling DB every minute.
Once rules DB is ready:
UI enables start fetching data.
When data for each container (Ticketcreation, HourlyTriggers, TicketUpdates) is processed next or at some point after fetch:
You call checkAndSetButtonState1(data, containerid) — passing the specific totals data for that container.
checkAndSetButtonState1 controls the UI feedback inside that container only, showing a countdown timer telling users "processing... please wait".
When the timer countdown expires:
The timer is removed.
The function handleDuplicateRulestype is invoked per container to kick off duplicate rule detection or further processing.
If any totals are zero (meaning no pending data):
checkAndSetButtonState1 immediately calls handleDuplicateRulestype with corresponding id, skipping timer.
Error Handling:
Both functions handle error conditions gracefully - disabling buttons, logging errors, or stopping polling.
LocalStorage:
checkAndSetButtonState1 also stores data and containerid into localStorage to persist context or facilitate debugging.
Summary
Function
Purpose
Triggered When
State/Element Updated
checkAndSetButtonState
Check global readiness status of all rules DB
On Component mount + Poll every 60s
React state isRulesDBReady, loadingBannerVisible
checkAndSetButtonState1
Manage per-container timers/messages for data processing
checkAndSetButtonState is your global checker and poller informing the whole component whether rules DB is ready.
checkAndSetButtonState1 is your per-container UI timer controller that shows wait messages and triggers next processing steps.
How you could integrate them in your React component flow:
useEffect(() => {
// Global check on mount
checkAndSetButtonState();
}, []);
useEffect(() => {
// Assume you receive latest storedvalue1 and containerId from fetched data or state
if (storedvalue1 && containerId) {
checkAndSetButtonState1(storedvalue1, containerId);
}
}, [storedvalue1, containerId]);
Notes:
Your checkAndSetButtonState1 is not React state driven — it directly manipulates DOM, so it should be used carefully in React environment to avoid conflicts.
Consider integrating it more React-idiomatic way by managing timers inside components and controlling visibility via React states, but this depends on your actual UI framework and restrictions.
If you want, I can help refactor checkAndSetButtonState1 to be more React-friendly or clarify where exactly to call it inside your component lifecycle!
Certainly! Below is a React-friendly refactor of your checkAndSetButtonState1 function and an example of how you can integrate the timer display properly with React state and effects instead of manipulating the DOM directly.
React-friendly approach to your timer logic
Key points:
Use React state to track timers (remaining seconds, visibility).
Use useEffect for timer countdown side effect.
Render timer UI declaratively.
Avoid direct DOM manipulation like createElement or appendChild.
Still receive data and containerId as props or parameters to know what to show.
Step 1: Create a reusable Timer component
import React, { useEffect, useState } from "react";
const ProcessingTimer = ({ duration, containerId, onTimerEnd }) => {
const [remaining, setRemaining] = useState(duration);
useEffect(() => {
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
return;
}
setRemaining(duration);
const interval = setInterval(() => {
setRemaining((r) => {
if (r <= 1) {
clearInterval(interval);
onTimerEnd(containerId);
return 0;
}
return r - 1;
});
}, 1000);
return () => clearInterval(interval);
}, [duration, containerId, onTimerEnd]);
if (remaining <= 0) {
return null; // don't show anything after timer ends
}
// Style can be adjusted as needed or replaced with your component/UI library elements
return (
<div
style={{
position: "fixed",
top: "63%",
left: "50%",
transform: "translateX(-50%)",
color: "black",
padding: "10px 20px",
borderRadius: "5px",
fontFamily: "sans-serif",
fontSize: "16px",
zIndex: 9999,
backgroundColor: "white",
boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
}}
role="alert"
aria-live="assertive"
>
The app is currently processing the data. Please refresh the page or revisit the app after {remaining} sec...
</div>
);
};
export default ProcessingTimer;
Step 2: Refactor your checkAndSetButtonState1 logic into a hook or handler:
Example hook to manage timer state per container:
import React, { useState } from "react";
import ProcessingTimer from "./ProcessingTimer"; // import the component above
const useProcessingTimer = () => {
const [timerState, setTimerState] = useState({
containerId: null,
duration: 0,
visible: false,
});
const startTimer = (data, containerId, handleDuplicateRulestypeCallback, getDurationForTotal) => {
if (!data) return;
const { creationTotal, hourlyTotal, updateTotal, stored } = data;
console.log("Starting timer logic for container:", containerId);
let duration = 0;
if (containerId === "Ticketcreation" && creationTotal > 0) {
duration = getDurationForTotal(creationTotal);
} else if (containerId === "HourlyTriggers" && hourlyTotal > 0) {
duration = getDurationForTotal(creationTotal) + getDurationForTotal(hourlyTotal);
} else if (containerId === "TicketUpdates" && updateTotal > 0) {
duration =
getDurationForTotal(creationTotal) +
getDurationForTotal(hourlyTotal) +
getDurationForTotal(updateTotal);
}
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
// No duration or zero, call handleDuplicateRulestype immediately
if (stored) {
console.log("No timer needed, directly calling handleDuplicateRulestype");
switch (containerId) {
case "Ticketcreation":
handleDuplicateRulestypeCallback(1);
break;
case "HourlyTriggers":
handleDuplicateRulestypeCallback(3);
break;
case "TicketUpdates":
handleDuplicateRulestypeCallback(4);
break;
}
}
setTimerState({ containerId: null, duration: 0, visible: false });
return;
}
// If timer already running for this container, ignore (you could extend logic to track that)
if (timerState.visible && timerState.containerId === containerId) {
console.log("Timer already running for", containerId);
return;
}
setTimerState({ containerId, duration, visible: true });
};
// Function called when timer finishes
const handleTimerEnd = (containerId) => {
console.log(`Timer ended for container ${containerId}`);
setTimerState({ containerId: null, duration: 0, visible: false });
switch (containerId) {
case "Ticketcreation":
// Call your duplicate handler with code 1
handleDuplicateRulestype(1);
break;
case "HourlyTriggers":
handleDuplicateRulestype(3);
break;
case "TicketUpdates":
handleDuplicateRulestype(4);
break;
default:
break;
}
};
return {
timerState,
startTimer,
handleTimerEnd,
};
};
You’d import and use this useProcessingTimer in your component, passing in the current data and container as needed.
Step 3: Example usage inside your main component
import React, { useEffect } from "react";
import ProcessingTimer from "./ProcessingTimer";
import { useProcessingTimer } from "./useProcessingTimer"; // Adjust import as needed
const AutomationTabs = ({ ...props }) => {
// Assuming you have storedvalue1 in your state - your rules DB data snapshot
// And you know what container you're working with, e.g. for the activeTab
const storedvalue1 = ...; // Comes from your data fetching
const activeTab = ...; // your current tab key, like "Ticketcreation"
const { timerState, startTimer, handleTimerEnd } = useProcessingTimer();
// helper function, could be the one you already have
const getDurationForTotal = (total) => {
// implement your logic
return total * 5; // example: 5 seconds per item
};
useEffect(() => {
if (!storedvalue1 || !activeTab) return;
// Start timer for the current tab/container
startTimer(storedvalue1, activeTab, (code) => {
// this callback calls your existing handler
handleDuplicateRulestype(code);
}, getDurationForTotal);
}, [storedvalue1, activeTab]);
return (
<>
{/* Your UI rendering... */}
{/* Conditionally show the timer if visible for the current container */}
{timerState.visible && timerState.containerId === activeTab && (
<ProcessingTimer
duration={timerState.duration}
containerId={timerState.containerId}
onTimerEnd={handleTimerEnd}
/>
)}
</>
);
};
Summary
Your timers are now managed by React state/effect hooks.
The UI is declarative and reflects the timer countdown in a React component, no DOM manipulation.
The global component controls when timers start based on data updates.
The countdown timer calls the appropriate handler when finished.
This approach integrates better in React’s render lifecycle, avoids DOM conflicts, and is easier to maintain.
If you want, I can also help you fully integrate this with your existing complex component code, or convert other logic similarly!
Certainly! Below is a full React component example that refactors your checkAndSetButtonState1 logic into React state and effects, integrating the timer UI declaratively and invoking your duplicate handler accordingly.
What this example includes:
The ProcessingTimer component (renders countdown UI)
The useProcessingTimer custom hook (controls timer logic and state)
The main AutomationTabs component (uses the above, simulating data and tab)
Integration of your handleDuplicateRulestype and getDurationForTotal functions (placeholder versions; replace as needed)
Full working example:
import React, { useState, useEffect } from "react";
// === ProcessingTimer (Countdown UI) ===
const ProcessingTimer = ({ duration, containerId, onTimerEnd }) => {
const [remaining, setRemaining] = useState(duration);
useEffect(() => {
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
return;
}
setRemaining(duration);
const interval = setInterval(() => {
setRemaining((r) => {
if (r <= 1) {
clearInterval(interval);
onTimerEnd(containerId);
return 0;
}
return r - 1;
});
}, 1000);
return () => clearInterval(interval);
}, [duration, containerId, onTimerEnd]);
if (remaining <= 0) return null;
return (
<div
style={{
position: "fixed",
top: "63%",
left: "50%",
transform: "translateX(-50%)",
backgroundColor: "white",
color: "black",
padding: "10px 20px",
borderRadius: "5px",
fontFamily: "sans-serif",
fontSize: "16px",
zIndex: 9999,
boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
}}
role="alert"
aria-live="assertive"
>
The app is currently processing the data. Please refresh the page or revisit the app after {remaining} sec...
</div>
);
};
// === Custom Hook for Timer Logic ===
const useProcessingTimer = (handleDuplicateRulestype, getDurationForTotal) => {
const [timerState, setTimerState] = useState({
containerId: null,
duration: 0,
visible: false,
});
const startTimer = (data, containerId) => {
if (!data) return;
const { creationTotal = 0, hourlyTotal = 0, updateTotal = 0, stored = false } = data;
console.log("Starting timer logic for container:", containerId, data);
let duration = 0;
switch (containerId) {
case "Ticketcreation":
if (creationTotal > 0) duration = getDurationForTotal(creationTotal);
break;
case "HourlyTriggers":
if (hourlyTotal > 0)
duration = getDurationForTotal(creationTotal) + getDurationForTotal(hourlyTotal);
break;
case "TicketUpdates":
if (updateTotal > 0)
duration =
getDurationForTotal(creationTotal) +
getDurationForTotal(hourlyTotal) +
getDurationForTotal(updateTotal);
break;
default:
break;
}
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
// No timer needed: immediately call duplicate handler if stored is true
if (stored) {
console.log("No timer needed, directly calling handleDuplicateRulestype");
switch (containerId) {
case "Ticketcreation":
handleDuplicateRulestype(1);
break;
case "HourlyTriggers":
handleDuplicateRulestype(3);
break;
case "TicketUpdates":
handleDuplicateRulestype(4);
break;
default:
break;
}
}
// Clear timer state
setTimerState({ containerId: null, duration: 0, visible: false });
return;
}
// If timer already visible for this container, ignore starting another
if (timerState.visible && timerState.containerId === containerId) {
console.log("Timer already running for", containerId);
return;
}
// Start/show timer
setTimerState({ containerId, duration, visible: true });
};
const handleTimerEnd = (containerId) => {
console.log(`Timer ended for container ${containerId}`);
setTimerState({ containerId: null, duration: 0, visible: false });
switch (containerId) {
case "Ticketcreation":
handleDuplicateRulestype(1);
break;
case "HourlyTriggers":
handleDuplicateRulestype(3);
break;
case "TicketUpdates":
handleDuplicateRulestype(4);
break;
default:
break;
}
};
return { timerState, startTimer, handleTimerEnd };
};
// === Example main component using the hook and timer ===
const AutomationTabs = () => {
// Simulated data, replace loading real data or via props/state
const [storedvalue1, setStoredvalue1] = useState({
creationTotal: 2,
hourlyTotal: 1,
updateTotal: 0,
stored: true,
});
// Simulated active tab/container, could come from your tabs
const [activeTab, setActiveTab] = useState("Ticketcreation");
// Your existing functions (replace or connect to real ones)
const handleDuplicateRulestype = (typeId) => {
alert(`handleDuplicateRulestype called for type ${typeId}`);
// Your logic here ...
};
// Dummy duration calculator (seconds per item),
// implement your real logic as needed
const getDurationForTotal = (total) => {
return total * 5;
};
// Use the timer hook with the handlers
const { timerState, startTimer, handleTimerEnd } = useProcessingTimer(
handleDuplicateRulestype,
getDurationForTotal
);
useEffect(() => {
// Start timer logic whenever data or active tab changes
if (storedvalue1 && activeTab) {
startTimer(storedvalue1, activeTab);
}
}, [storedvalue1, activeTab, startTimer]);
return (
<div style={{ padding: 20 }}>
<h2>Automation Tabs (example)</h2>
<div style={{ marginBottom: 15 }}>
<button onClick={() => setActiveTab("Ticketcreation")}>Ticket Creation</button>
<button onClick={() => setActiveTab("HourlyTriggers")}>Hourly Triggers</button>
<button onClick={() => setActiveTab("TicketUpdates")}>Ticket Updates</button>
</div>
<div style={{ marginTop: 20 }}>
<p>Active Tab: <b>{activeTab}</b></p>
<p>Stored Data: {JSON.stringify(storedvalue1)}</p>
</div>
{/* Conditionally show timer UI */}
{timerState.visible && timerState.containerId === activeTab && (
<ProcessingTimer
duration={timerState.duration}
containerId={timerState.containerId}
onTimerEnd={handleTimerEnd}
/>
)}
</div>
);
};
export default AutomationTabs;
How to use:
Replace the simulated storedvalue1 and activeTab states with your real application data and tab controls.
Replace the handleDuplicateRulestype and getDurationForTotal dummy implementations with your actual logic.
This example manages timer display purely inside React and calls handleDuplicateRulestype when timers finish or when no timer is needed.
Buttons switch active tabs; timer logic adapts accordingly.
Benefits of this React refactor:
No direct DOM manipulation (like createElement).
Clean separation of UI (timer message) and logic (timer countdown).
Easy to maintain and integrate into larger React app.
Accessible timer: announces count down to screen readers with aria-live="assertive".
If you want me to help adjust the bigger component you posted earlier to use this or handle more features, just ask!
Certainly! I'll break down the full solution into separate parts/components/hooks with explanations to help you understand better.
1. ProcessingTimer Component
This component displays the countdown timer with a message and updates every second.
import React, { useEffect, useState } from "react";
/**
* Shows a countdown timer with processing message.
* When timer ends, calls onTimerEnd callback.
*/
const ProcessingTimer = ({ duration, containerId, onTimerEnd }) => {
const [remaining, setRemaining] = useState(duration);
useEffect(() => {
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
return;
}
// Initialize remaining time
setRemaining(duration);
// Countdown interval - reduce remaining every second
const interval = setInterval(() => {
setRemaining((r) => {
if (r <= 1) {
clearInterval(interval);
onTimerEnd(containerId); // Notify that timer ended
return 0;
}
return r - 1;
});
}, 1000);
// Cleanup interval on unmount or change
return () => clearInterval(interval);
}, [duration, containerId, onTimerEnd]);
// Don't render if timer ended
if (remaining <= 0) return null;
return (
<div
style={{
position: "fixed",
top: "63%",
left: "50%",
transform: "translateX(-50%)",
backgroundColor: "white",
color: "black",
padding: "10px 20px",
borderRadius: "5px",
fontFamily: "sans-serif",
fontSize: "16px",
zIndex: 9999,
boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
}}
role="alert"
aria-live="assertive"
>
The app is currently processing the data. Please refresh the page or revisit the app after {remaining} sec...
</div>
);
};
export default ProcessingTimer;
2. useProcessingTimer Hook
This hook manages the timer state, starts the timer based on the data and container, and calls your duplicate rule handler when the timer ends.
import { useState } from "react";
/**
* Custom hook to manage processing timers per container.
* Handles logic if to show timer or immediately call handler.
*
* @param {function} handleDuplicateRulestype - function to call when timer ends
* @param {function} getDurationForTotal - function to get timer duration for given total
*/
const useProcessingTimer = (handleDuplicateRulestype, getDurationForTotal) => {
const [timerState, setTimerState] = useState({
containerId: null,
duration: 0,
visible: false,
});
/**
* Starts timer based on data and containerId.
* If no duration needed or data zero, calls handler immediately.
*/
const startTimer = (data, containerId) => {
if (!data) return;
const { creationTotal = 0, hourlyTotal = 0, updateTotal = 0, stored = false } = data;
console.log("Starting timer logic for container:", containerId, data);
let duration = 0;
switch (containerId) {
case "Ticketcreation":
if (creationTotal > 0) duration = getDurationForTotal(creationTotal);
break;
case "HourlyTriggers":
if (hourlyTotal > 0)
duration = getDurationForTotal(creationTotal) + getDurationForTotal(hourlyTotal);
break;
case "TicketUpdates":
if (updateTotal > 0)
duration =
getDurationForTotal(creationTotal) +
getDurationForTotal(hourlyTotal) +
getDurationForTotal(updateTotal);
break;
default:
break;
}
if (typeof duration !== "number" || isNaN(duration) || duration <= 0) {
// No timer needed: call handler immediately if stored true
if (stored) {
console.log("No timer needed, calling handleDuplicateRulestype immediately");
switch (containerId) {
case "Ticketcreation":
handleDuplicateRulestype(1);
break;
case "HourlyTriggers":
handleDuplicateRulestype(3);
break;
case "TicketUpdates":
handleDuplicateRulestype(4);
break;
}
}
setTimerState({ containerId: null, duration: 0, visible: false });
return;
}
// Prevent starting new timer if one running for same container
if (timerState.visible && timerState.containerId === containerId) {
console.log("Timer already running for", containerId);
return;
}
setTimerState({ containerId, duration, visible: true });
};
/**
* Called when timer ends.
* Resets timer state and calls duplicate handler.
*/
const handleTimerEnd = (containerId) => {
console.log(`Timer ended for container ${containerId}`);
setTimerState({ containerId: null, duration: 0, visible: false });
switch (containerId) {
case "Ticketcreation":
handleDuplicateRulestype(1);
break;
case "HourlyTriggers":
handleDuplicateRulestype(3);
break;
case "TicketUpdates":
handleDuplicateRulestype(4);
break;
}
};
return { timerState, startTimer, handleTimerEnd };
};
export default useProcessingTimer;
3. Example Usage in Your Component
This component simulates the data and uses above hook and timer component. Replace simulated data and handlers with your actual app logic!
import React, { useState, useEffect } from "react";
import ProcessingTimer from "./ProcessingTimer";
import useProcessingTimer from "./useProcessingTimer";
const AutomationTabs = () => {
// Simulated data, replace with real fetched data/state
const [storedvalue1, setStoredvalue1] = useState({
creationTotal: 2,
hourlyTotal: 1,
updateTotal: 0,
stored: true,
});
// Simulated active tab/container; in real app, get this from user tab selection
const [activeTab, setActiveTab] = useState("Ticketcreation");
// Your existing handler - replace or implement your rule handling logic here
const handleDuplicateRulestype = (typeId) => {
alert(`handleDuplicateRulestype called for type ${typeId}`);
// Your duplicate rule processing logic here
};
// Dummy timer duration calculator (seconds per item)
const getDurationForTotal = (total) => {
return total * 5; // Example: 5 seconds per item - replace with your real logic
};
// Get the timer state and handlers from hook
const { timerState, startTimer, handleTimerEnd } = useProcessingTimer(
handleDuplicateRulestype,
getDurationForTotal
);
useEffect(() => {
if (storedvalue1 && activeTab) {
startTimer(storedvalue1, activeTab);
}
}, [storedvalue1, activeTab, startTimer]);
return (
<div style={{ padding: 20 }}>
<h2>Automation Tabs (example)</h2>
<div style={{ marginBottom: 15 }}>
<button onClick={() => setActiveTab("Ticketcreation")}>Ticket Creation</button>
<button onClick={() => setActiveTab("HourlyTriggers")}>Hourly Triggers</button>
<button onClick={() => setActiveTab("TicketUpdates")}>Ticket Updates</button>
</div>
<div>
<p>
<b>Active Tab:</b> {activeTab}
</p>
<p>
<b>Stored Data:</b> {JSON.stringify(storedvalue1)}
</p>
</div>
{/* Render timer if visible for the active tab */}
{timerState.visible && timerState.containerId === activeTab && (
<ProcessingTimer
duration={timerState.duration}
containerId={timerState.containerId}
onTimerEnd={handleTimerEnd}
/>
)}
</div>
);
};
export default AutomationTabs;
Summary of usage:
Put ProcessingTimer.jsx and useProcessingTimer.js in separate files.
Import them into your main component file.
Pass your real storedvalue1 data and activeTab state (or similar variables).
Replace dummy handlers (handleDuplicateRulestype, getDurationForTotal) with your actual functions.
The timer displays automatically as state changes trigger starting or finishing timers.
When the timer finishes, the duplicate rule handler is invoked accordingly.
If you want me to help you integrate this with your full initial big component or help with anything else, feel free to ask!
in this return how to add this functionality you provided
Great! To integrate the React timer functionality (ProcessingTimer + useProcessingTimer) into your existing return JSX structure, here’s how and where to add it properly inside your component's render method.
What we want to add?
The ProcessingTimer component that displays a countdown message.
It must show only when the timer is active and for the current active tab.
The timer state and handlers come from the useProcessingTimer hook.
Steps to add:
Use the useProcessingTimer hook in your main component.
You will already have handleDuplicateRulestype and getDurationForTotal implemented or imported.
Trigger startTimer in a useEffect when relevant data or active tab changes (not shown here, but should be in your component).
Render <ProcessingTimer /> somewhere inside your return JSX, preferably near your main panel area or container, but outside tab panels to avoid being re-mounted unnecessarily.
How to inject ProcessingTimer in your existing return JSX
Add the timer render just inside your main return fragment (<>…</>) above or below the core UI content. For example, just before <FwToast /> for it to appear over UI but persistently:
return (
<>
{errorMessage ? (
// ... your existing error UI ...
) : (
<>
{/* Your headers, banners, buttons, tabs and panels */}
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
{/* your buttons and FwTabs here */}
</div>
)}
</>
)}
{/* === Insert ProcessingTimer here === */}
{timerState.visible && (
<ProcessingTimer
duration={timerState.duration}
containerId={timerState.containerId}
onTimerEnd={handleTimerEnd}
/>
)}
<FwToast />
</>
);
Why here?
Placing it close to the root level ensures the timer overlay remains visible regardless of which tab is active, yet its content can depend on state.
The overlay uses CSS position: fixed, so it visually floats over everything.
timerState.visible controls whether timer is shown, so it won't display unless a timer is active.
Additional notes for your integration:
Make sure your component imports ProcessingTimer and the useProcessingTimer hook and initializes them.
The startTimer() call should happen in a useEffect inside your component (triggered by relevant data and activeTab changes):