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).
Certainly! Below is the JavaScript code tailored to your Forex Checklist Analyzer web application. This script handles all the functionalities you've outlined, including checklist management, real-time progress calculation, data persistence, import/export features, search functionality, and smooth drag-and-drop interactions.
JavaScript Code
Paste the following JavaScript code into the <script> section of your HTML file where indicated:
html
<script>
// Forex Checklist Analyzer JavaScript
document.addEventListener('DOMContentLoaded', () => {
const sectionId = '1'; // Adjust if you have multiple sections
// Initialize the checklist application
ChecklistApp.init(sectionId);
});
const ChecklistApp = (() => {
// Utility function to generate unique IDs
const generateId = () => `item-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
// Initialize the application for a given section
const init = (sectionId) => {
const app = new ChecklistSection(sectionId);
app.loadData();
app.render();
app.setupEventListeners();
};
// Constructor for each checklist section
class ChecklistSection {
constructor(sectionId) {
this.sectionId = sectionId;
this.storageKey = `forexChecklistSection${sectionId}`;
this.criteria = [];
this.filteredCriteria = [];
this.draggedItemId = null;
// DOM Elements
this.container = document.getElementById(`checklistContainerSection${sectionId}`);
this.progressBar = document.getElementById(`sliderFillSection${sectionId}`);
this.numericalLabel = document.getElementById(`numericalLabelSection${sectionId}`);
this.totalItemsLabel = document.getElementById(`totalItemsSection${sectionId}`);
this.activeItemsLabel = document.getElementById(`activeItemsSection${sectionId}`);
this.searchBox = document.getElementById(`searchBoxSection${sectionId}`);
}
// Load data from LocalStorage
loadData() {
const data = localStorage.getItem(this.storageKey);
if (data) {
try {
this.criteria = JSON.parse(data);
} catch (e) {
console.error('Error parsing checklist data from LocalStorage:', e);
this.criteria = [];
}
} else {
this.criteria = [];
}
this.filteredCriteria = [...this.criteria];
}
// Save data to LocalStorage
saveData() {
localStorage.setItem(this.storageKey, JSON.stringify(this.criteria));
}
// Render the checklist UI
render() {
// Clear the container
this.container.innerHTML = '';
// Render each criterion
this.filteredCriteria.forEach(criterion => {
const itemDiv = document.createElement('div');
itemDiv.classList.add('checklist-item');
itemDiv.setAttribute('draggable', 'true');
itemDiv.id = `item-${criterion.id}`;
itemDiv.dataset.id = criterion.id;
// Checkbox
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = criterion.active;
checkbox.addEventListener('change', () => this.toggleActive(criterion.id));
// Textarea for name
const textarea = document.createElement('textarea');
textarea.value = criterion.name;
textarea.addEventListener('input', (e) => this.editName(criterion.id, e.target.value));
// Priority label
const priorityLabel = document.createElement('span');
priorityLabel.classList.add('priority-box');
priorityLabel.textContent = `Priority: ${criterion.priority}`;
priorityLabel.title = 'Click to edit priority';
priorityLabel.style.cursor = 'pointer';
priorityLabel.addEventListener('click', () => this.editPriority(criterion.id));
// Delete button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', () => this.deleteCriteria(criterion.id));
// Append elements to itemDiv
itemDiv.appendChild(checkbox);
itemDiv.appendChild(textarea);
itemDiv.appendChild(priorityLabel);
itemDiv.appendChild(deleteButton);
// Drag and Drop Event Listeners
itemDiv.addEventListener('dragstart', (e) => this.handleDragStart(e, criterion.id));
itemDiv.addEventListener('dragover', (e) => this.handleDragOver(e, criterion.id));
itemDiv.addEventListener('drop', (e) => this.handleDrop(e, criterion.id));
itemDiv.addEventListener('dragend', (e) => this.handleDragEnd(e));
// Append the item to the container
this.container.appendChild(itemDiv);
});
// Update progress and item counts
this.updateProgress();
this.updateItemCounts();
}
// Update the progress bar and numerical label
updateProgress() {
const totalActive = this.criteria
.filter(item => item.active)
.reduce((sum, item) => sum + Number(item.priority), 0);
const cappedTotal = Math.min(totalActive, 100);
this.progressBar.style.width = `${cappedTotal}%`;
this.numericalLabel.textContent = `${cappedTotal} / 100`;
// Position the numerical label
const positionPercentage = cappedTotal;
this.numericalLabel.style.left = `${positionPercentage}%`;
}
// Update item counts
updateItemCounts() {
this.totalItemsLabel.textContent = this.criteria.length;
const activeCount = this.criteria.filter(item => item.active).length;
this.activeItemsLabel.textContent = activeCount;
}
// Add a new criterion
addCriteria() {
const name = prompt('Enter the name of the new criterion:');
if (name === null) return; // Cancelled
const trimmedName = name.trim();
if (trimmedName === '') {
alert('Criterion name cannot be empty.');
return;
}
const priorityInput = prompt('Enter the priority (number) for this criterion:');
if (priorityInput === null) return; // Cancelled
const priority = Number(priorityInput);
if (isNaN(priority) || priority < 0) {
alert('Priority must be a valid non-negative number.');
return;
}
const newCriterion = {
id: generateId(),
name: trimmedName,
priority: priority,
active: true
};
this.criteria.push(newCriterion);
this.applySearchFilter();
this.saveData();
this.render();
}
// Delete a criterion by ID
deleteCriteria(id) {
if (!confirm('Are you sure you want to delete this criterion?')) return;
this.criteria = this.criteria.filter(item => item.id !== id);
this.applySearchFilter();
this.saveData();
this.render();
}
// Toggle the active state of a criterion
toggleActive(id) {
const criterion = this.criteria.find(item => item.id === id);
if (criterion) {
criterion.active = !criterion.active;
this.saveData();
this.updateProgress();
this.updateItemCounts();
}
}
// Edit the name of a criterion
editName(id, newName) {
const trimmedName = newName.trim();
if (trimmedName === '') {
alert('Criterion name cannot be empty.');
this.render(); // Re-render to reset the textarea
return;
}
const criterion = this.criteria.find(item => item.id === id);
if (criterion) {
criterion.name = trimmedName;
this.saveData();
this.applySearchFilter();
this.render();
}
}
// Edit the priority of a criterion
editPriority(id) {
const criterion = this.criteria.find(item => item.id === id);
if (!criterion) return;
const priorityInput = prompt('Enter the new priority (number) for this criterion:', criterion.priority);
if (priorityInput === null) return; // Cancelled
const priority = Number(priorityInput);
if (isNaN(priority) || priority < 0) {
alert('Priority must be a valid non-negative number.');
return;
}
criterion.priority = priority;
this.saveData();
this.render();
}
// Handle drag start
handleDragStart(e, id) {
this.draggedItemId = id;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', id);
e.target.classList.add('dragging');
}
// Handle drag over
handleDragOver(e, id) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const targetItem = document.getElementById(`item-${id}`);
targetItem.classList.add('drag-over');
}
// Handle drop
handleDrop(e, id) {
e.preventDefault();
const draggedId = this.draggedItemId;
if (draggedId === id) return;
const draggedIndex = this.criteria.findIndex(item => item.id === draggedId);
const targetIndex = this.criteria.findIndex(item => item.id === id);
if (draggedIndex === -1 || targetIndex === -1) return;
// Remove the dragged item and insert it before the target
const [draggedItem] = this.criteria.splice(draggedIndex, 1);
this.criteria.splice(targetIndex, 0, draggedItem);
this.applySearchFilter();
this.saveData();
this.render();
}
// Handle drag end
handleDragEnd(e) {
this.draggedItemId = null;
const items = this.container.querySelectorAll('.checklist-item');
items.forEach(item => {
item.classList.remove('dragging', 'drag-over');
});
}
// Export checklist data as JSON
exportChecklistData() {
const dataStr = JSON.stringify(this.criteria, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `forex_checklist_section_${this.sectionId}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Import checklist data from JSON
importChecklistData() {
// Create a hidden file input
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'application/json';
fileInput.style.display = 'none';
// Handle file selection
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const importedData = JSON.parse(event.target.result);
if (!Array.isArray(importedData)) throw new Error('Invalid data format.');
// Validate each criterion
importedData.forEach(item => {
if (typeof item.id !== 'string' ||
typeof item.name !== 'string' ||
typeof item.priority !== 'number' ||
typeof item.active !== 'boolean') {
throw new Error('Invalid criterion structure.');
}
});
// Replace current data
this.criteria = importedData;
this.applySearchFilter();
this.saveData();
this.render();
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 correctly formatted.');
}
};
reader.readAsText(file);
});
// Trigger the file input
fileInput.click();
}
// Search and filter criteria
searchCriteria(query) {
this.applySearchFilter(query);
this.render();
}
// Apply search filter based on the search box value
applySearchFilter(query = this.searchBox.value.trim().toLowerCase()) {
if (query === '') {
this.filteredCriteria = [...this.criteria];
} else {
this.filteredCriteria = this.criteria.filter(item =>
item.name.toLowerCase().includes(query)
);
}
}
// Setup event listeners for buttons and search
setupEventListeners() {
// Add Button
const addButton = document.querySelector(`#containerSection${this.sectionId} .add-button`);
addButton.addEventListener('click', () => this.addCriteria());
// Export Button
const exportButton = document.querySelector(`#containerSection${this.sectionId} .export-button`);
exportButton.addEventListener('click', () => this.exportChecklistData());
// Import Button
const importButton = document.querySelector(`#containerSection${this.sectionId} .import-button`);
importButton.addEventListener('click', () => this.importChecklistData());
// Search Box
this.searchBox.addEventListener('input', (e) => this.searchCriteria(e.target.value));
}
}
// Expose the init function
return { init };
})();
</script>
Explanation of Key Components
Initialization:
The script initializes the checklist application when the DOM content is fully loaded.
It targets a specific section (sectionId = '1') based on your HTML structure. If you have multiple sections in the future, you can adjust the sectionId accordingly.
Data Persistence:
LocalStorage is used to save and retrieve the checklist data.
Each section has a unique storage key to prevent data overlap.
Checklist Management:
Adding Criteria: Prompts the user for a criterion name and priority. Validates inputs before adding to the checklist.
Deleting Criteria: Allows users to delete individual criteria with a confirmation prompt.
Editing Criteria: Users can edit the name directly via the textarea and the priority by clicking on the priority label.
Real-Time Progress Calculation:
The progress bar dynamically updates based on the sum of active criteria's priorities, capped at 100.
A numerical label reflects the current total score.
Drag-and-Drop Functionality:
Implements HTML5 Drag and Drop API to allow users to reorder criteria.
The order is saved to LocalStorage to maintain consistency across sessions.
Import/Export Features:
Export: Converts the checklist data to a JSON file and triggers a download.
Import: Allows users to upload a JSON file to replace the current checklist. Includes validation to ensure data integrity.
Search Functionality:
A search bar filters the displayed criteria in real-time based on the user's input.
Real-Time Updates:
All changes (additions, deletions, edits, reordering) are immediately reflected in the UI and saved to LocalStorage without requiring a page refresh.
Data Validation and Error Handling:
Ensures that user inputs for names and priorities are valid.
Handles errors gracefully, especially during the import process, by providing user feedback.
Additional Notes
Customization for Multiple Sections: If you plan to have multiple checklist sections, ensure each section has a unique sectionId and corresponding HTML elements with matching IDs.
Styling: The script assumes that your CSS handles the appearance of elements like .checklist-item, .priority-box, .slider-fill, and .numerical-label. Ensure these classes are styled appropriately in your styles.css.
Accessibility: For improved accessibility, consider adding ARIA attributes and ensuring that all interactive elements are keyboard-navigable.
Performance: For very large checklists, you might want to optimize rendering by implementing techniques like virtualization.
Conclusion
This JavaScript implementation should comprehensively cover the functionalities you've described for the Forex Checklist Analyzer. Feel free to further customize and enhance the script to better fit your specific needs and preferences.