let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let toggleContainer = container.querySelector('.toggle-container');
if (!fieldNameContainer) {
fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
container.appendChild(fieldNameContainer);
}
if (!choicesContainer) {
choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
container.appendChild(choicesContainer);
}
const eventContainer = container.closest('.event-container');
if (eventContainer) {
const modal = document.getElementById('composition');
if (modal) {
modal.setAttribute('is-open', 'true');
modal.querySelector('fw-modal-title').innerHTML = `<span>Delete Event</span>`;
modal.querySelector('fw-modal-content').innerHTML = `
<span>Are you sure you want to delete this event?</span>
`;
modal.addEventListener(
'fwSubmit',
() => {
eventContainer.remove();
console.log("Event container successfully removed from DOM.");
if (Array.isArray(ticketworkflowconditions)) {
ticketworkflowconditions.splice(ruleIndex, 1);
console.log(`Event at index ${ruleIndex} successfully removed from ticketworkflowconditions array.`);
} else if (ticketworkflowconditions[ruleIndex]) {
delete ticketworkflowconditions[ruleIndex];
console.log(`Event at index ${ruleIndex} successfully removed from ticketworkflowconditions object.`);
}
console.log("Updated ticketworkflowconditions:", JSON.stringify(ticketworkflowconditions, null, 2));
showSuccessToast("Event successfully deleted!");
modal.removeAttribute('is-open');
},
{ once: true }
);
}
}
});
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
let data = {
...ticketworkflowconditions[ruleIndex]
};
ticketworkflowconditions[ruleIndex] = {
...data,
checked: isChecked
};
code
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log(`Updated ticketworkflowconditions after toggle change: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
why combination occurs duplicates it should not please fix this code
The issue seems to arise because the combination array is being updated in multiple places in your code without sufficient checks for duplication. Specifically, when updating the combination array in the event handlers (e.g., for dropdown changes), you're overwriting or appending values without ensuring that you're not duplicating existing entries. This causes multiple copies of the same object to be added to the combination array.
Here is a cleaned-up and modified approach to ensure the combination array does not get duplicated:
Fix Explanation:
Prevent Duplicates in combination: Before adding or updating an entry in the combination array, ensure it doesn't already exist for the given fieldName.
Avoid Multiple splice Operations: Ensure that you're not inadvertently modifying the combination array every time dropdown values change, unless it's absolutely necessary.
Centralize Updating Logic: Have a centralized function to update the combination array, making it easier to filter out duplicates and keep state consistent.
Updated Code:
Here's the updated version of the code with fixes:
javascript
async function initializeEventDropdown(container, obj, ruleIndex) {
console.log("container, obj, ruleIndex", container, obj, ruleIndex);
// Initial variables
const eventSelect = container.querySelector('.event-name-dropdown');
const selectedEventValue = eventSelect.value;
console.log(`initializeEventDropdown - Initial selected event: ${selectedEventValue}`);
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let toggleContainer = container.querySelector('.toggle-container');
// Ensure necessary containers are present
if (!fieldNameContainer) {
fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
container.appendChild(fieldNameContainer);
}
if (!choicesContainer) {
choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
container.appendChild(choicesContainer);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '-20px';
container.appendChild(buttonContainer);
}
if (!toggleContainer) {
toggleContainer = document.createElement('div');
toggleContainer.classList.add('col-md-2', 'toggle-container');
toggleContainer.style.position = 'absolute';
toggleContainer.style.right = '5px';
container.style.position = 'relative';
container.appendChild(toggleContainer);
}
toggleContainer.style.display = 'flex';
toggleContainer.style.flexDirection = 'column';
toggleContainer.style.alignItems = 'center';
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.checked = obj ? obj.checked : true;
toggleContainer.appendChild(toggleSwitch);
const deleteButton = document.createElement('fw-button');
deleteButton.textContent = 'Delete Event';
deleteButton.setAttribute('color', 'danger');
deleteButton.style.marginTop = '25px';
toggleContainer.appendChild(deleteButton);
// Process the existing fields and their combinations
if (obj && obj.event.combination.length > 0) {
const fields = obj.event.combination;
// Iterate through each combination and ensure no duplicates
for (let index = 0; index < fields.length; index++) {
const element = fields[index];
// Process each field in the combination
for (const [fieldName, fieldValue] of Object.entries(element)) {
await fieldschoosingvalues(
selectedEventValue,
fieldNameContainer,
choicesContainer,
buttonContainer,
container,
fieldName,
Array.isArray(fieldValue) ? fieldValue : [fieldValue], // Ensure fieldValue is always an array
obj,
ruleIndex,
index
);
}
}
}
updateDropdownAccessibility(toggleSwitch.checked);
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(selectedEventValue, isChecked);
});
deleteButton.addEventListener('click', () => {
console.log("Delete Event button clicked.");
const eventContainer = container.closest('.event-container');
if (eventContainer) {
const modal = document.getElementById('composition');
if (modal) {
modal.setAttribute('is-open', 'true');
modal.querySelector('fw-modal-title').innerHTML = `<span>Delete Event</span>`;
modal.querySelector('fw-modal-content').innerHTML = `
<span>Are you sure you want to delete this event?</span>
`;
modal.addEventListener(
'fwSubmit',
() => {
eventContainer.remove();
console.log("Event container successfully removed from DOM.");
// Remove the rule from the array/object
if (Array.isArray(ticketworkflowconditions)) {
ticketworkflowconditions.splice(ruleIndex, 1);
} else if (ticketworkflowconditions[ruleIndex]) {
delete ticketworkflowconditions[ruleIndex];
}
console.log("Updated ticketworkflowconditions:", JSON.stringify(ticketworkflowconditions, null, 2));
showSuccessToast("Event successfully deleted!");
modal.removeAttribute('is-open');
},
{ once: true }
);
}
}
});
function updateDropdownAccessibility(isChecked) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isChecked;
});
const buttonContainers = container.querySelectorAll('.button-container');
buttonContainers.forEach(buttonContainer => {
const buttons = buttonContainer.querySelectorAll('button, fw-button');
buttons.forEach(button => {
button.disabled = !isChecked;
});
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
// Update the specific rule's enabled state
ticketworkflowconditions[ruleIndex] = {
...ticketworkflowconditions[ruleIndex],
checked: isChecked,
};
console.log(`Toggle for "${selectedEventValue}" set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log("Updated ticketworkflowconditions:", JSON.stringify(ticketworkflowconditions, null, 2));
}
}
// This function ensures that a combination for a particular field is unique
function updateCombination(ruleIndex, fieldName, fieldValue) {
const currentRule = ticketworkflowconditions[ruleIndex];
if (!currentRule) return;
const existingCombination = currentRule.event.combination || [];
const existingFieldIndex = existingCombination.findIndex((element) => element[fieldName]);
if (existingFieldIndex !== -1) {
// If the field already exists, update the value
existingCombination[existingFieldIndex][fieldName] = fieldValue;
} else {
// Otherwise, add a new field-value pair
existingCombination.push({ [fieldName]: fieldValue });
}
// Ensure there are no duplicate entries overall
currentRule.event.combination = existingCombination.filter(
(value, index, self) =>
index === self.findIndex((t) => JSON.stringify(t) === JSON.stringify(value))
);
console.log(`Updated combination for ruleIndex ${ruleIndex}:`, currentRule.event.combination);
}
Key Changes:
updateCombination Function:
Ensures that entries in the combination array are unique.
Updates existing combinations instead of blindly adding new ones.
Centralized Logic:
The logic to handle combinations now works in one place, reducing duplication chances.
Debugging:
Enhanced debugging output to validate logic more easily.
Now, the combination array will only have unique entries, preventing duplication when fields or values are updated.
The issue is that updating the combination object for the event and the duplicate updates of the combination key in your main structure (ticketworkflowconditions) are not synchronized. This causes duplicates in the keys that represent combinations.
Problem Summary
In your example, the duplicate combination happens because:
Both event.combination and combination in the main structure (ticketworkflowconditions) are defined separately, and updates may lead to inconsistencies or duplicates.
The updates to the combination array are done without sufficient checks for existing fields or entries, so a duplicate entry gets created even if it already exists.
Updated and Fixed Code
We will fix this by:
Removing the duplicate combination keys in the structure (it makes no sense to keep both event.combination and a combination directly outside of the event).
Centralizing the logic to update the combination (or event.combination), preventing duplicate entries from being added.
Here is the corrected code:
javascript
function updateCombination(ruleIndex, fieldName, fieldValue) {
// Access the current rule
let currentRule = ticketworkflowconditions[ruleIndex];
if (!currentRule || !currentRule.event) {
console.error("Rule or event not found for the given index:", ruleIndex);
return;
}
// Access the current combination array from event
let eventCombination = currentRule.event.combination || [];
// Check if a field with the same name already exists in the combination
let existingFieldIndex = eventCombination.findIndex(item => item.hasOwnProperty(fieldName));
if (existingFieldIndex !== -1) {
// If the field exists, update its value (ensure fieldValue is always an array)
eventCombination[existingFieldIndex][fieldName] = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
} else {
// If the field doesn't exist, add a new entry
eventCombination.push({ [fieldName]: Array.isArray(fieldValue) ? fieldValue : [fieldValue] });
}
// Remove any duplicates in the combination (just to be thorough)
currentRule.event.combination = eventCombination.filter(
(obj, index, self) =>
index === self.findIndex(item => JSON.stringify(item) === JSON.stringify(obj))
);
// Update the ticketworkflowconditions structure with the modified combination
ticketworkflowconditions[ruleIndex] = {
...currentRule,
event: {
...currentRule.event
}
};
console.log(`Updated combination for rule ${ruleIndex}:`, JSON.stringify(ticketworkflowconditions[ruleIndex], null, 2));
}
Changes
Avoiding Deep Duplication:
The function now carefully checks for existing fields using findIndex and replaces the existing value if the field is already present, instead of pushing a new one.
Removed Duplicate combination Keys:
The duplicate combination (outside event) is unnecessary and may lead to inconsistent state. We rely solely on event.combination.
Deduplication Check:
The filter function ensures that identical combinations (objects with the same field and value) are prevented from being duplicated.
Integration in Your Flow
Modify your fieldschoosingvalues and showingitschoices functions to use this centralized updateCombination method whenever there's a change in the combination.
For example:
Updating fieldschoosingvalues:
Within the fwChange event listener of the choices dropdown:
javascript
fieldDropdown.addEventListener("fwChange", async (event) => {
const newSelectedFieldName = event.target.value;
const newSelectedField = fields.find((field) => field.name === newSelectedFieldName);
if (newSelectedField) {
const selectedChoices = []; // Initialize selected choices to empty for the new field
updateCombination(ruleIndex, newSelectedFieldName, selectedChoices);
await showingitschoices(
choicesContainer,
newSelectedField,
selectedEventValue,
newSelectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices,
obj,
ruleIndex,
fieldIndex
);
console.log(`Field changed to: ${newSelectedFieldName}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error("Field not found in the Dropdown");
}
});
Updating showingitschoices:
Within the fwChange listener for the choices dropdown:
Always rely on event.combination and remove duplicate entries at the point of modification.
Centralizing the logic in updateCombination ensures that the array remains consistent across all fields.
I apologize for any confusion earlier. Let us carefully arrange the implementation to fix your issue, ensuring no duplicate entries in the combination key of your ticketworkflowconditions object.
The plan here is to focus on:
Avoiding repeated or unnecessary updates to the combination array.
Centralizing logic for adding, updating, and preventing duplication in the combination array.
There are two combination objects in the state, i.e., event.combination and another at the root level (outside the event object).
Updating one does not synchronize correctly with the other.
The fix involves removing the duplicate combination key at the root level and ensuring updates are correctly done at only one source (event.combination).
Effective Fix: Code Cleanup & Deduplication
Here is the comprehensive fix for your issue.
1. Centralized updateCombination Function
This function will:
Prevent duplication in the combination array by checking for existing fields before modification.
Add, update, or handle field-value pairs in event.combination consistently.
Ensure there is only one combination—inside event.
javascript
function updateCombination(ruleIndex, fieldName, fieldValues) {
// Access the current rule
const currentRule = ticketworkflowconditions[ruleIndex];
if (!currentRule || !currentRule.event) {
console.error("Rule or event not found for the given index:", ruleIndex);
return;
}
// Access or initialize the combination array inside `event`
const eventCombination = currentRule.event.combination || [];
// Find if the field (fieldName) already exists in the combination
const existingFieldIndex = eventCombination.findIndex((item) => item.hasOwnProperty(fieldName));
if (existingFieldIndex !== -1) {
// If the field exists, update its values (ensure `fieldValues` is an array)
eventCombination[existingFieldIndex][fieldName] = Array.isArray(fieldValues) ? fieldValues : [fieldValues];
} else {
// If the field does not exist, add it as a new entry
eventCombination.push({ [fieldName]: Array.isArray(fieldValues) ? fieldValues : [fieldValues] });
}
// Remove any duplicate objects from the combination array
currentRule.event.combination = eventCombination.filter(
(item, index, self) =>
index === self.findIndex((t) => JSON.stringify(t) === JSON.stringify(item))
);
// Ensure the root-level `combination` key is removed (keep only `event.combination`)
delete currentRule.combination;
// Save updates back to the main `ticketworkflowconditions`
ticketworkflowconditions[ruleIndex] = { ...currentRule };
console.log(`Updated ticketworkflowconditions for rule ${ruleIndex}:`, JSON.stringify(ticketworkflowconditions[ruleIndex], null, 2));
}
How updateCombination Works:
Checks whether the given fieldName exists in the combination. If it does, updates it instead of adding a new one.
Verifies that no duplicate objects exist within the combination array after the updates.
Centralizes logic for updates, ensuring only event.combination is used as the data source.
Removes the root-level duplicate combination key (if it exists).
2. Using updateCombination in Dropdown or Field Changes
In your existing dropdown and field-handling functions (such as fieldschoosingvalues and showingitschoices), replace direct updates to combination with calls to the centralized updateCombination function.
Example for showingitschoices:
Ensure that every time a dropdown changes, the updateCombination function is used to update the combination array.
javascript
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = [], // array of pre-selected choices, if any
obj,
ruleIndex,
fieldIndex
) {
// Reset the choices container
choicesContainer.innerHTML = '';
// Create the choices dropdown
const choicesDropdown = document.createElement('fw-select');
choicesDropdown.classList.add('choices-dropdown');
choicesDropdown.setAttribute('label', `${selectedFieldName}`);
choicesDropdown.setAttribute('required', 'true');
choicesDropdown.setAttribute('placeholder', `Choose ${selectedFieldName}`);
choicesDropdown.setAttribute('hint-text', 'Select singular or multiple options');
choicesDropdown.setAttribute('multiple', 'true');
// Populate choices dropdown with field choices
selectedField.choices.forEach((choice) => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select values if they already exist in selectedChoices
if (selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Event listener for changes in the choices dropdown
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceIds = Array.isArray(event.target.value)
? event.target.value
: [event.target.value]; // Ensure selection is always an array
// Update combination using the centralized logic
updateCombination(ruleIndex, selectedFieldName, selectedChoiceIds);
console.log(`Updated combination for field "${selectedFieldName}" with values: ${selectedChoiceIds}`);
});
}
3. Example for fieldschoosingvalues
Inside any of your fieldschoosingvalues or dropdown initialization functions, you can rely on updateCombination for proper synchronization.
Make sure to remove redundant code that modifies both event.combination and the (now-removed) root combination key.
For instance:
javascript
fieldDropdown.addEventListener("fwChange", async (event) => {
const newSelectedFieldName = event.target.value;
const newSelectedField = fields.find((field) => field.name === newSelectedFieldName);
if (newSelectedField) {
// Initialize an empty array for newly selected choices
const selectedChoices = [];
updateCombination(ruleIndex, newSelectedFieldName, selectedChoices);
// Re-render the choices for the newly selected field
await showingitschoices(
choicesContainer,
newSelectedField,
selectedEventValue,
newSelectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices,
obj,
ruleIndex,
fieldIndex
);
console.log(`Field changed to: ${newSelectedFieldName}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error("Field not found in the Dropdown");
}
});
Testing the Fix
Define a ticketworkflowconditions example for debugging:
I hope this centralized approach cleans up your issue effectively! Let me know if you experience any further issues.
Apologies for the frustration caused, and thank you for your patience so far. Let's investigate and resolve this issue properly. From what you've described, redundant updates to your combination array (and duplicate entries) are still occurring.
The likely causes are:
The combination array (inside event.combination) is being updated multiple times due to various event listeners, leading to repeated entries.
The logic to remove duplicates or update the data isn't covering all scenarios.
To fix this issue comprehensively:
Remove duplicate updates and ensure clean, consistent state management.
Ensure deduplication logic works in all possible scenarios.
Fix: Step-by-Step Approach
We'll clean the logic for maintaining the combination array. Here’s the full solution:
1. Central State Management: Single combination Array
Ensure only one source of truth (event.combination) exists in the JSON, and remove the external combination property. This means:
To prevent duplicates, define a deduplication helper function. It ensures that fields in combination are unique based on their fieldName. If fieldName already exists, its value is updated instead of adding a new entry.
javascript
function deduplicateCombination(combination) {
const uniqueCombination = [];
// Iterate through combination and filter to remove duplicates
combination.forEach((item) => {
const fieldName = Object.keys(item)[0]; // Extract the field name
const existingIndex = uniqueCombination.findIndex((entry) => entry[fieldName] !== undefined);
if (existingIndex !== -1) {
// If field already exists, update its value
uniqueCombination[existingIndex][fieldName] = item[fieldName];
} else {
// Else, push the new field-value pair
uniqueCombination.push(item);
}
});
return uniqueCombination;
}
3. Update Combination Logic
Update the logic for adding/updating the combination to ensure it uses the deduplication function.
Central updateCombination Function:
This function ensures that for every update:
Existing fields (fieldName) are overwritten.
The final combination remains free from duplicates.
javascript
function updateCombination(ruleIndex, fieldName, fieldValue) {
// Access the rule
const currentRule = ticketworkflowconditions[ruleIndex];
if (!currentRule || !currentRule.event) {
console.error("Rule or event not found for the given index:", ruleIndex);
return;
}
// Access or initialize combination
let combination = currentRule.event.combination || [];
// Add or update the field in combination
const fieldEntry = { [fieldName]: Array.isArray(fieldValue) ? fieldValue : [fieldValue] };
combination.push(fieldEntry);
// Remove duplicates and update the state
currentRule.event.combination = deduplicateCombination(combination);
// Save back into ticketworkflowconditions
ticketworkflowconditions[ruleIndex] = { ...currentRule };
// Debug: Output current state
console.log(`Updated combination for rule ${ruleIndex}:`, JSON.stringify(ticketworkflowconditions[ruleIndex], null, 2));
}
4. Integrate Into Event Listeners
Replace all direct modifications of the combination with calls to updateCombination. This includes:
When a new field is added or selected.
When choices for a field are modified.
When fields are removed.
Example Listener for Dropdown Changes:
Here’s how the dropdown for field values (choicesDropdown) should use updateCombination:
javascript
choicesDropdown.addEventListener("fwChange", (event) => {
const selectedChoices = Array.isArray(event.target.value) ? event.target.value : [event.target.value];
// Update the combination with new choices
updateCombination(ruleIndex, selectedFieldName, selectedChoices);
console.log(`Updated choices for field "${selectedFieldName}":`, selectedChoices);
});
5. Handle Field Removal
When a field is removed, the combination should delete the corresponding field entry.
Updated Field Removal Logic:
javascript
function removeField(ruleIndex, fieldName) {
const currentRule = ticketworkflowconditions[ruleIndex];
if (!currentRule || !currentRule.event) {
console.error("Rule or event not found for the given index:", ruleIndex);
return;
}
// Remove the field from the combination
currentRule.event.combination = currentRule.event.combination.filter((item) => !item.hasOwnProperty(fieldName));
// Save back into ticketworkflowconditions
ticketworkflowconditions[ruleIndex] = { ...currentRule };
console.log(`Field "${fieldName}" removed from combination in rule ${ruleIndex}.`);
}
Example Listener for Field Removal:
Call the removeField function when a field is deleted.
javascript
deleteButton.addEventListener("click", () => {
removeField(ruleIndex, selectedFieldName);
console.log(`Field "${selectedFieldName}" has been removed.`);
});
6. Testing Final Result
Here's a scenario to test and ensure no duplicates:
updateCombination(0, "source", ["3"]);
updateCombination(0, "status", ["4"]);
updateCombination(0, "source", ["5"]); // Should update `source`, not duplicate it
updateCombination(0, "priority", ["1"]);
updateCombination(0, "status", ["2"]); // Should update `status`, not duplicate it