I need JavaScript code that powers a Forex Checklist Analyzer web application. This app should allow users (traders) to manage, prioritize, and track their trading strategies using an interactive checklist. Here's what I need the JavaScript to handle:
Core Functionalities:
Checklist Management:
Add new criteria: The user should be able to add a new criterion by entering a name and a priority (via a prompt). Each criterion consists of:
A checkbox to mark the item as active or inactive.
A text area to edit the criterion's name.
A priority label to display the item's priority.
Delete criteria: The user should be able to delete any criterion.
Drag-and-drop: Users should be able to drag and reorder criteria within the list. The order of items in the data should be updated accordingly.
Real-Time Progress Calculation:
A progress bar should reflect the cumulative score of active criteria. Each active criterion contributes its priority value to the total score.
A numerical label next to the progress bar updates in real time, reflecting the total score. The score should be capped at 100 to avoid exceeding the bar's width.
When criteria are re-ordered or a new criterion is added, the progress bar and numerical score should update dynamically.
Checkbox and Priority Interaction:
Checkbox toggle: When a criterion’s checkbox is toggled (checked/unchecked), update the progress bar and numerical score accordingly.
Priority editing: The priority value for each criterion should be editable via a prompt. When the priority is updated, the numerical score and progress bar should adjust in real time.
Persistent Data Storage:
LocalStorage: The checklist data should be saved to the browser's LocalStorage so that the user's progress and checklist items persist even after the page is refreshed or closed.
Save and load: On page load, the checklist should automatically load from LocalStorage. On any changes (e.g., adding, deleting, re-ordering items), the data should be saved to LocalStorage.
Data Import/Export:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Export: The user should be able to export their checklist data as a JSON file. This should include the criteria names, their priorities, and whether they are active or not.
Import: The user should be able to import a JSON file to restore their checklist. When imported, the checklist data should replace the current list and update the progress bar and numerical score.
Search Functionality:
The app should include a search bar that allows users to filter criteria by name. As the user types, the list should dynamically show or hide items that match the search term.
Real-Time Updates:
The UI should reflect changes immediately without requiring a page refresh. For example:
When a criterion is added, it should appear instantly.
When a checkbox is toggled, the progress bar and numerical score should update immediately.
When an item is deleted, it should be removed from the list, and the changes should be reflected in the stored data.
Additional Considerations:
The app should handle data validation during user input. For example, when adding a new criterion, ensure the user provides a valid name and priority (e.g., a number for the priority).
Ensure that items can be dragged and dropped smoothly, and that the reordering is reflected in the saved data.
When importing JSON data, handle any errors gracefully (e.g., if the file is not properly formatted, show an alert).
Here's the JavaScript code that fulfills all the specified requirements when used with the provided HTML and CSS:
<script>
let checklistData = {}; // To store data for different sections
document.addEventListener('DOMContentLoaded', function() {
loadData('1');
});
function loadData(sectionId) {
let storedData = localStorage.getItem('checklistData' + sectionId);
if (storedData) {
checklistData[sectionId] = JSON.parse(storedData);
} else {
checklistData[sectionId] = [];
}
renderChecklist(sectionId);
updateProgress(sectionId);
}
function saveData(sectionId) {
localStorage.setItem('checklistData' + sectionId, JSON.stringify(checklistData[sectionId]));
}
function renderChecklist(sectionId) {
const container = document.getElementById('checklistContainerSection' + sectionId);
container.innerHTML = '';
checklistData[sectionId].forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.className = 'checklist-item';
itemDiv.setAttribute('draggable', 'true');
itemDiv.dataset.id = item.id;
// Checkbox
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = item.checked;
checkbox.addEventListener('change', function() {
item.checked = checkbox.checked;
saveData(sectionId);
updateProgress(sectionId);
});
// Text area for name
const textarea = document.createElement('textarea');
textarea.value = item.name;
textarea.addEventListener('input', function() {
item.name = textarea.value;
saveData(sectionId);
});
// Priority label
const priorityLabel = document.createElement('span');
priorityLabel.className = 'priority-box';
priorityLabel.textContent = 'Priority: ' + item.priority;
priorityLabel.style.cursor = 'pointer';
priorityLabel.addEventListener('click', function() {
editPriority(item.id, sectionId);
});
// Delete button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', function() {
deleteCriteria(item.id, sectionId);
});
// Append elements to itemDiv
const leftDiv = document.createElement('div');
leftDiv.style.display = 'flex';
leftDiv.style.alignItems = 'center';
leftDiv.appendChild(checkbox);
leftDiv.appendChild(textarea);
const rightDiv = document.createElement('div');
rightDiv.style.display = 'flex';
rightDiv.style.alignItems = 'center';
rightDiv.appendChild(priorityLabel);
rightDiv.appendChild(deleteButton);
itemDiv.appendChild(leftDiv);
itemDiv.appendChild(rightDiv);
// Append itemDiv to container
container.appendChild(itemDiv);
});
// Add drag-and-drop functionality
addDragAndDrop(sectionId);
}
function updateProgress(sectionId) {
const totalScore = checklistData[sectionId].reduce((total, item) => {
return item.checked ? total + item.priority : total;
}, 0);
let cappedScore = totalScore > 100 ? 100 : totalScore; // Cap at 100
const sliderFill = document.getElementById('sliderFillSection' + sectionId);
const numericalLabel = document.getElementById('numericalLabelSection' + sectionId);
// Update width of sliderFill based on cappedScore
sliderFill.style.width = cappedScore + '%';
// Update numericalLabel position and text
numericalLabel.textContent = totalScore;
numericalLabel.style.left = cappedScore + '%';
}
function addCriteria(sectionId) {
const name = prompt('Enter criterion name:');
if (!name) {
alert('Criterion name cannot be empty.');
return;
}
const priorityStr = prompt('Enter criterion priority (number):');
const priority = parseFloat(priorityStr);
if (isNaN(priority) || priority <= 0) {
alert('Please enter a valid positive number for priority.');
return;
}
const newItem = {
id: Date.now(), // unique id
name: name,
priority: priority,
checked: false
};
if (!checklistData[sectionId]) {
checklistData[sectionId] = [];
}
checklistData[sectionId].push(newItem);
saveData(sectionId);
renderChecklist(sectionId);
updateProgress(sectionId);
}
function deleteCriteria(itemId, sectionId) {
const index = checklistData[sectionId].findIndex(item => item.id == itemId);
if (index !== -1) {
checklistData[sectionId].splice(index, 1);
saveData(sectionId);
renderChecklist(sectionId);
updateProgress(sectionId);
}
}
function editPriority(itemId, sectionId) {
const item = checklistData[sectionId].find(item => item.id == itemId);
if (item) {
const newPriorityStr = prompt('Enter new priority (number):', item.priority);
const newPriority = parseFloat(newPriorityStr);
if (isNaN(newPriority) || newPriority <= 0) {
alert('Please enter a valid positive number for priority.');
return;
}
item.priority = newPriority;
saveData(sectionId);
renderChecklist(sectionId);
updateProgress(sectionId);
}
}
function searchCriteria(sectionId) {
const searchBox = document.getElementById('searchBoxSection' + sectionId);
const searchTerm = searchBox.value.toLowerCase();
const container = document.getElementById('checklistContainerSection' + sectionId);
const items = container.getElementsByClassName('checklist-item');
for (let itemDiv of items) {
const textarea = itemDiv.querySelector('textarea');
const name = textarea.value.toLowerCase();
if (name.includes(searchTerm)) {
itemDiv.style.display = '';
} else {
itemDiv.style.display = 'none';
}
}
}
function exportChecklistData(sectionId) {
const dataStr = JSON.stringify(checklistData[sectionId]);
const dataBlob = new Blob([dataStr], {type: 'application/json'});
const url = URL.createObjectURL(dataBlob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = 'checklistData' + sectionId + '.json';
downloadLink.click();
}
function importChecklistData(sectionId) {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.json,application/json';
fileInput.onchange = function(event) {
const file = event.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const importedData = JSON.parse(e.target.result);
// Validate imported data
if (Array.isArray(importedData) && importedData.every(validateItem)) {
checklistData[sectionId] = importedData;
saveData(sectionId);
renderChecklist(sectionId);
updateProgress(sectionId);
} else {
alert('Invalid data format in imported file.');
}
} catch (err) {
alert('Error reading imported file: ' + err.message);
}
};
reader.readAsText(file);
};
fileInput.click();
}
function validateItem(item) {
return item.hasOwnProperty('id') &&
item.hasOwnProperty('name') &&
item.hasOwnProperty('priority') &&
item.hasOwnProperty('checked') &&
typeof item.id === 'number' &&
typeof item.name === 'string' &&
typeof item.priority === 'number' &&
typeof item.checked === 'boolean';
}
function addDragAndDrop(sectionId) {
const container = document.getElementById('checklistContainerSection' + sectionId);
let dragSrcEl = null;
function handleDragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', null); // Firefox requires this
this.classList.add('dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary for drop to fire
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (dragSrcEl !== this) {
const srcId = dragSrcEl.dataset.id;
const targetId = this.dataset.id;
const srcIndex = checklistData[sectionId].findIndex(item => item.id == srcId);
const targetIndex = checklistData[sectionId].findIndex(item => item.id == targetId);
if (srcIndex >= 0 && targetIndex >= 0) {
const [movedItem] = checklistData[sectionId].splice(srcIndex, 1);
checklistData[sectionId].splice(targetIndex, 0, movedItem);
saveData(sectionId);
renderChecklist(sectionId);
updateProgress(sectionId);
}
}
return false;
}
function handleDragEnd(e) {
this.classList.remove('dragging');
let items = container.querySelectorAll('.checklist-item');
items.forEach(function (item) {
item.classList.remove('over');
});
}
let items = container.querySelectorAll('.checklist-item');
items.forEach(function (item) {
item.addEventListener('dragstart', handleDragStart, false);
item.addEventListener('dragenter', handleDragEnter, false);
item.addEventListener('dragover', handleDragOver, false);
item.addEventListener('dragleave', handleDragLeave, false);
item.addEventListener('drop', handleDrop, false);
item.addEventListener('dragend', handleDragEnd, false);
});
}
</script>
This script includes all the requested functionalities:
Checklist Management: Users can add, delete, and reorder criteria using drag-and-drop.
Real-Time Progress Calculation: The progress bar and numerical score update dynamically.
Persistent Data Storage: Data is saved and loaded from LocalStorage.
Data Import/Export: Users can import and export checklist data as JSON files.
Search Functionality: The search bar filters criteria by name in real-time.
Real-Time Updates: All changes reflect immediately in the UI.
Error Handling and Validation: User inputs are validated, and errors are handled gracefully.
Just place this script within the <script> tags in your HTML file, and ensure it follows the </style> tag as shown in your template. The application should function as per your specifications.