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:
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:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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).
Certainly! Below is the JavaScript code that fulfills all the specified requirements for the Forex Checklist Analyzer web application. This script manages checklist items, handles real-time progress calculations, supports drag-and-drop reordering, ensures data persistence using LocalStorage, provides import/export functionality, includes a search feature, and ensures real-time UI updates.
JavaScript Code:
javascript
<script>
// Immediately Invoked Function Expression (IIFE) to avoid global scope pollution
(function() {
// Wait for the DOM to fully load
document.addEventListener('DOMContentLoaded', function() {
const sectionId = '1'; // Assuming single section; adjust if multiple sections exist
const STORAGE_KEY = `checklistData-${sectionId}`;
// Initialize the checklist data
let checklistData = [];
// DOM Elements
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const addButton = document.querySelector(`button.add-button`);
const exportButton = document.querySelector(`button.export-button`);
const importButton = document.querySelector(`button.import-button`);
const searchBox = document.getElementById(`searchBoxSection${sectionId}`);
const sliderFill = document.getElementById(`sliderFillSection${sectionId}`);
const numericalLabel = document.getElementById(`numericalLabelSection${sectionId}`);
const totalItemsLabel = document.getElementById(`totalItemsSection${sectionId}`);
const activeItemsLabel = document.getElementById(`activeItemsSection${sectionId}`);
// Load data from LocalStorage
loadData();
// Render the initial checklist
renderChecklist();
// Attach event listeners to buttons
addButton.addEventListener('click', function() {
addCriteria(sectionId);
});
exportButton.addEventListener('click', function() {
exportChecklistData(sectionId);
});
importButton.addEventListener('click', function() {
importChecklistData(sectionId);
});
// Function to load data from LocalStorage
function loadData() {
const data = localStorage.getItem(STORAGE_KEY);
if (data) {
try {
checklistData = JSON.parse(data);
} catch (e) {
console.error('Error parsing checklist data from LocalStorage:', e);
checklistData = [];
localStorage.removeItem(STORAGE_KEY);
}
}
}
// Function to save data to LocalStorage
function saveData() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(checklistData));
}
// Function to render the checklist
function renderChecklist(filter = '') {
// Clear existing items
checklistContainer.innerHTML = '';
// Filter data based on search term
const filteredData = checklistData.filter(item => item.name.toLowerCase().includes(filter.toLowerCase()));
// Update total and active items count
totalItemsLabel.textContent = checklistData.length;
activeItemsLabel.textContent = checklistData.filter(item => item.active).length;
// Iterate over each criterion and create DOM elements
filteredData.forEach((item, index) => {
const itemDiv = document.createElement('div');
itemDiv.classList.add('checklist-item');
itemDiv.setAttribute('draggable', 'true');
itemDiv.setAttribute('data-id', item.id);
itemDiv.id = `item-${item.id}`;
// Checkbox
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = item.active;
checkbox.addEventListener('change', function() {
toggleActive(item.id);
});
// Text Area for Name
const textArea = document.createElement('textarea');
textArea.value = item.name;
textArea.addEventListener('input', function() {
updateName(item.id, textArea.value);
});
// Priority Label
const priorityLabel = document.createElement('span');
priorityLabel.classList.add('priority-box');
priorityLabel.textContent = `Priority: ${item.priority}`;
priorityLabel.title = "Click to edit priority";
priorityLabel.style.cursor = 'pointer';
priorityLabel.addEventListener('click', function() {
editPriority(item.id);
});
// Delete Button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('delete-button');
deleteButton.addEventListener('click', function() {
deleteCriteria(item.id);
});
// Append elements to the 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);
// Attach drag event listeners
attachDragEvents(itemDiv);
// Append the itemDiv to the checklist container
checklistContainer.appendChild(itemDiv);
});
// Update progress bar and numerical label
updateProgress();
// Save data to LocalStorage
saveData();
}
// Function to attach drag-and-drop event listeners to an item
function attachDragEvents(itemDiv) {
itemDiv.addEventListener('dragstart', handleDragStart);
itemDiv.addEventListener('dragover', handleDragOver);
itemDiv.addEventListener('drop', handleDrop);
itemDiv.addEventListener('dragend', handleDragEnd);
}
let dragSrcEl = null;
function handleDragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
this.classList.add('dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation(); // Stops some browsers from redirecting.
}
if (dragSrcEl !== this) {
// Get the IDs of the dragged and dropped items
const draggedId = dragSrcEl.getAttribute('data-id');
const droppedId = this.getAttribute('data-id');
// Find their indices in the checklistData array
const draggedIndex = checklistData.findIndex(item => item.id == draggedId);
const droppedIndex = checklistData.findIndex(item => item.id == droppedId);
// Swap their positions
checklistData.splice(droppedIndex, 0, checklistData.splice(draggedIndex, 1)[0]);
// Re-render the checklist
renderChecklist(searchBox.value);
}
return false;
}
function handleDragEnd(e) {
this.classList.remove('dragging');
}
// Function to add a new criterion
window.addCriteria = function(sectionId) {
const name = prompt('Enter the criterion name:');
if (name === null) return; // User cancelled
const trimmedName = name.trim();
if (trimmedName === '') {
alert('Criterion name cannot be empty.');
return;
}
const priorityInput = prompt('Enter the priority (a number):');
if (priorityInput === null) return; // User cancelled
const priority = parseFloat(priorityInput);
if (isNaN(priority) || priority < 0) {
alert('Please enter a valid non-negative number for priority.');
return;
}
// Create a new criterion object
const newCriterion = {
id: Date.now(), // Unique ID based on timestamp
name: trimmedName,
priority: priority,
active: true
};
// Add to the checklistData array
checklistData.push(newCriterion);
// Re-render the checklist
renderChecklist(searchBox.value);
};
// Function to delete a criterion
function deleteCriteria(id) {
const confirmDelete = confirm('Are you sure you want to delete this criterion?');
if (!confirmDelete) return;
checklistData = checklistData.filter(item => item.id !== id);
renderChecklist(searchBox.value);
}
// Function to toggle active status
function toggleActive(id) {
const item = checklistData.find(item => item.id === id);
if (item) {
item.active = !item.active;
renderChecklist(searchBox.value);
}
}
// Function to update the name of a criterion
function updateName(id, newName) {
const trimmedName = newName.trim();
if (trimmedName === '') {
alert('Criterion name cannot be empty.');
renderChecklist(searchBox.value); // Revert changes
return;
}
const item = checklistData.find(item => item.id === id);
if (item) {
item.name = trimmedName;
saveData();
}
}
// Function to edit the priority of a criterion
function editPriority(id) {
const item = checklistData.find(item => item.id === id);
if (!item) return;
const priorityInput = prompt('Enter the new priority (a number):', item.priority);
if (priorityInput === null) return; // User cancelled
const newPriority = parseFloat(priorityInput);
if (isNaN(newPriority) || newPriority < 0) {
alert('Please enter a valid non-negative number for priority.');
return;
}
item.priority = newPriority;
renderChecklist(searchBox.value);
}
// Function to update the progress bar and numerical label
function updateProgress() {
const totalScore = checklistData
.filter(item => item.active)
.reduce((sum, item) => sum + item.priority, 0);
const cappedScore = Math.min(totalScore, 100); // Cap at 100
// Update the slider fill width
sliderFill.style.width = `${cappedScore}%`;
// Position the numerical label
numericalLabel.textContent = cappedScore;
numericalLabel.style.left = `${cappedScore}%`;
// Adjust label position if it exceeds the container boundaries
if (cappedScore < 10) {
numericalLabel.style.transform = 'translate(-50%, -50%)';
} else if (cappedScore > 90) {
numericalLabel.style.transform = 'translate(-100%, -50%)';
} else {
numericalLabel.style.transform = 'translate(-50%, -50%)';
}
}
// Function to save and load data automatically within renderChecklist and other functions
// Function to export checklist data as JSON
window.exportChecklistData = function(sectionId) {
const dataStr = JSON.stringify(checklistData, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
// Create a temporary link to trigger download
const a = document.createElement('a');
a.href = url;
a.download = `checklist-data-section-${sectionId}.json`;
document.body.appendChild(a);
a.click();
// Clean up
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
// Function to import checklist data from JSON
window.importChecklistData = function(sectionId) {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.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 the imported data structure
if (!Array.isArray(importedData)) {
throw new Error('Invalid data format: Expected an array.');
}
importedData.forEach(item => {
if (typeof item.id !== 'number' ||
typeof item.name !== 'string' ||
typeof item.priority !== 'number' ||
typeof item.active !== 'boolean') {
throw new Error('Invalid data format for one or more items.');
}
});
// Replace current checklist data with imported data
checklistData = importedData;
renderChecklist(searchBox.value);
alert('Checklist data imported successfully!');
} catch (error) {
console.error('Error importing checklist data:', error);
alert('Failed to import checklist data. Please ensure the file is properly formatted.');
}
};
reader.readAsText(file);
};
input.click();
};
// Function to search/filter criteria by name
window.searchCriteria = function(sectionId) {
const filter = searchBox.value.trim().toLowerCase();
renderChecklist(filter);
};
});
})();
</script>
Explanation of the JavaScript Code:
Initialization:
IIFE (Immediately Invoked Function Expression): Encapsulates the entire script to avoid polluting the global namespace.
DOMContentLoaded Event: Ensures that the script runs only after the entire DOM has been loaded.
Variables and Constants:
sectionId: Identifies the section (useful if multiple sections are added in the future).
STORAGE_KEY: A unique key for storing and retrieving data from LocalStorage.
checklistData: An array that holds all the checklist items.
DOM Elements:
References to various DOM elements are obtained using getElementById and querySelector for easy manipulation.
Data Persistence:
loadData(): Fetches checklist data from LocalStorage. If no data exists or parsing fails, it initializes an empty array.
saveData(): Saves the current checklistData array to LocalStorage in JSON format.
Rendering the Checklist:
renderChecklist(filter): Clears the existing checklist and repopulates it based on the current checklistData and any active search filter.
Creating Checklist Items: For each criterion, a div is created containing a checkbox, a textarea for the name, a priority label, and a delete button.
Event Listeners:
Checkbox: Toggles the active status of a criterion.
Textarea: Updates the name of the criterion in real-time.
Priority Label: Allows editing the priority via a prompt when clicked.
Delete Button: Removes the criterion from the checklist.
Drag-and-Drop: Each checklist item is made draggable, and event listeners handle the drag-and-drop functionality to reorder items.
Drag-and-Drop Functionality:
handleDragStart, handleDragOver, handleDrop, handleDragEnd: Manage the dragging process, swapping items in the array based on user interaction.
Additional Notes:
Unique Identification: Each criterion has a unique id generated using Date.now(), ensuring that even rapid additions have distinct identifiers.
Styling Enhancements: The priority label changes cursor to a pointer to indicate it's clickable for editing.
Accessibility Considerations: Confirmation prompts prevent accidental deletions, and draggable items provide visual feedback during the drag operation.
Extensibility: The use of sectionId allows for easy expansion if multiple checklist sections are needed in the future.
Integration with HTML:
Ensure that this script is placed within the <script> tags in your HTML file, replacing the comment --note this:script that you will craft will pasted her--.
html
<script>
// JavaScript code goes here (as provided above)
</script>
Final Thoughts:
This JavaScript code provides a robust foundation for the Forex Checklist Analyzer web application, incorporating all the functionalities you outlined. It ensures a seamless user experience with real-time updates, data persistence, and user-friendly interactions.
If you have further customization needs or encounter any issues, feel free to reach out!
addCriteria(sectionId): Prompts the user to input a name and priority for a new criterion. Validates the input and adds the new criterion to checklistData.
Deleting a Criterion:
deleteCriteria(id): Confirms with the user before removing a criterion from checklistData.
Toggling Active Status:
toggleActive(id): Toggles the active state of a criterion and updates the progress.
Editing the Name and Priority:
updateName(id, newName): Updates the name of a criterion in real-time as the user types.
editPriority(id): Allows the user to change the priority of a criterion via a prompt.
Progress Bar and Numerical Label:
updateProgress(): Calculates the cumulative score based on active criteria, updates the width of the progress bar (sliderFill), and positions the numerical label accordingly. The score is capped at 100 to fit within the progress bar.
Import and Export Functionality:
exportChecklistData(sectionId): Converts the checklistData array to a JSON string and triggers a download of the file.
importChecklistData(sectionId): Allows the user to upload a JSON file, parses it, validates the structure, and replaces the current checklistData with the imported data.
Search Functionality:
searchCriteria(sectionId): Filters the displayed checklist items based on the user's search input in real-time.
Real-Time Updates:
The checklist UI updates instantly in response to any changes, such as adding, deleting, editing, or reordering criteria.
Data Validation and Error Handling:
Ensures that user inputs for names and priorities are valid.
Handles errors gracefully during JSON import, alerting the user if the file format is incorrect.