I need JavaScript code that powers a Forex Checklist Analyzer web application. This app…
- User
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.
- 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:
-
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:
- 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.
- The UI should reflect changes immediately without requiring a page refresh. For example:
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).
the javascript will crafted for this html css:
html { height: 100%; background: linear-gradient(to bottom, var(--gradient-start), var(--gradient-middle), var(--gradient-end)); background-attachment: fixed; font-size: 16px; }
body { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; font-family: var(--font-primary); color: var(--text-primary); background: transparent; line-height: 1.6; font-weight: 400; margin: 0; padding: 0; box-sizing: border-box; transition: var(--transition-main); }
button, input, textarea { font-family: var(--font-primary); border-radius: var(--border-radius); padding: 10px 15px; transition: background-color 0.3s, transform 0.3s; }
button { background: linear-gradient(45deg, var(--button-gradient-start), var(--button-gradient-end)); border: none; box-shadow: var(--shadow); cursor: pointer; color: white; font-weight: 500; text-transform: uppercase; letter-spacing: 1px; }
button:hover, button:focus { transform: var(--transition-scale); }
input[type="checkbox"] { appearance: none; width: 24px; height: 24px; border: 2px solid var(--button-gradient-end); border-radius: 4px; cursor: pointer; position: relative; }
input[type="checkbox"]:checked { background-color: var(--button-gradient-start); border-color: var(--button-gradient-start); }
input[type="checkbox"]:checked::after { content: ''; position: absolute; left: 7px; top: 3px; width: 6px; height: 12px; border: solid white; border-width: 0 3px 3px 0; transform: rotate(45deg); }
.container { max-width: 700px; margin: 20px; background: var(--container-bg); border-radius: var(--border-radius); padding: 40px; box-shadow: var(--shadow); border: 1px solid rgba(255, 255, 255, 0.1); }
.container div[id^="item-"] { background: var(--item-bg); padding: 20px; margin-bottom: 20px; box-shadow: var(--shadow); border: 1px solid rgba(255, 255, 255, 0.1); transition: var(--transition-main); display: flex; align-items: center; justify-content: space-between; }
.container div[id^="item-"] button { background: linear-gradient(45deg, var(--button-gradient-end), var(--button-gradient-start)); box-shadow: var(--shadow); }
.container { margin: 10px; padding: 20px; }}
.container h1 { font-weight: 700; color: var(--button-gradient-end); text-align: center; margin-bottom: 30px; }
.checklist-item textarea { font-size: 1.6em; border: 2px solid var(--border-radius); background: rgba(255, 255, 255, 0.1); outline: none; cursor: text; width: calc(100% - 40px); text-align: start; padding: 10px 20px; color: var(--text-primary); font-family: 'Vazir', 'Roboto', sans-serif; direction: rtl; resize: none; overflow: auto; min-height: 50px; white-space: pre-wrap; transition: height 0.3s ease; overflow: auto; scrollbar-width: none; -ms-overflow-style: none; } .checklist-item textarea::-webkit-scrollbar { display: none; }
.checklist-item textarea:focus { height: auto; min-height: 50px; }
.checklist-item button { margin-left: 10px; vertical-align: top; }
@media (max-width: 768px) { .checklist-item textarea { font-size: 1.4em; width: calc(100% - 30px); } }
.image-upload-button { display: inline-block; margin-left: 10px; cursor: pointer; color: white; background: linear-gradient(to right, var(--button-gradient-start), var(--button-gradient-end)); padding: 10px 15px; border-radius: var(--border-radius); border: none; box-shadow: var(--shadow); font-weight: 500; text-transform: uppercase; }
.slider-background { background-color: #f2f2f2; height: 40px; border-radius: 20px; position: relative; margin: 30px 0; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15); }
.slider-fill { background: linear-gradient(to right, #4a90e2, #82c4e8); height: 100%; border-radius: 20px; transition: width 0.4s ease; }
.numerical-label { color: #333; font-size: 1.2em; font-weight: 700; position: absolute; top: 50%; transform: translate(-50%, -50%); transition: left 0.4s ease; background: #ffffff; border: 2px solid #4a90e2; border-radius: 15px; padding: 6px 12px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.25); text-shadow: none; }
.priority-box { background: linear-gradient(45deg, var(--button-gradient-end), var(--button-gradient-start)); color: white; padding: 3px 8px; border-radius: var(--border-radius); font-weight: bold; margin-left: 8px; }
-
- Assistant
Certainly! Below is the JavaScript code tailored to power your Forex Checklist Analyzer web application. This code encompasses all the functionalities you outlined, including checklist management, real-time progress calculation, persistent storage, data import/export, search functionality, and smooth drag-and-drop reordering.
Explanation:
-
Data Structure:
- Each checklist item is represented as an object with
id,name,priority, andactiveproperties. - The entire checklist is stored as an array in
localStorageunder a unique key for each section (e.g.,forexChecklist1).
- Each checklist item is represented as an object with
-
Core Functions:
- addCriteria: Adds a new criterion after validating user input.
- deleteCriteria: Removes a criterion by its unique
id. - toggleActive: Toggles the active state of a criterion.
- editPriority: Allows users to edit the priority of a criterion.
- updateName: Updates the name of a criterion based on user input in the textarea.
- renderChecklist: Renders the checklist items in the DOM.
- computeProgress: Calculates and updates the progress bar and numerical score.
- saveData / loadData: Handles saving to and loading from
localStorage. - exportChecklistData: Exports the current checklist as a JSON file.
- importChecklistData: Imports checklist data from a JSON file, with error handling.
- searchCriteria: Filters checklist items based on the search input.
-
Drag-and-Drop Functionality:
- Implements HTML5 Drag and Drop API to allow users to reorder checklist items.
- Updates the data order in
localStorageupon reordering.
-
Event Listeners:
- Various event listeners handle user interactions such as adding, deleting, editing, dragging, exporting, and importing criteria.
-
Initialization:
- Upon page load, the checklist is loaded from
localStorageand rendered. - Real-time updates ensure that the UI reflects any changes immediately without needing a page refresh.
- Upon page load, the checklist is loaded from
JavaScript Code:
<!DOCTYPE html> <html lang="en"> <head> <!-- (Your existing head content) --> <script> (function() { // Utility function to generate unique IDs function generateId() { return 'id-' + Date.now() + '-' + Math.floor(Math.random() * 1000); } // Function to load data from localStorage function loadData(section) { const data = localStorage.getItem(`forexChecklist${section}`); return data ? JSON.parse(data) : []; } // Function to save data to localStorage function saveData(section, data) { localStorage.setItem(`forexChecklist${section}`, JSON.stringify(data)); } // Function to compute and update the progress bar and numerical score function computeProgress(section) { const data = loadData(section); let total = 0; data.forEach(item => { if (item.active) { total += parseInt(item.priority, 10); } }); total = Math.min(total, 100); const sliderFill = document.getElementById(`sliderFillSection${section}`); const numericalLabel = document.getElementById(`numericalLabelSection${section}`); sliderFill.style.width = `${total}%`; numericalLabel.textContent = `${total}`; numericalLabel.style.left = `${total}%`; // Update total and active counts document.getElementById(`totalItemsSection${section}`).textContent = data.length; document.getElementById(`activeItemsSection${section}`).textContent = data.filter(item => item.active).length; } // Function to render the checklist function renderChecklist(section, filter = '') { const data = loadData(section); const container = document.getElementById(`checklistContainerSection${section}`); container.innerHTML = ''; // Clear existing items data.forEach((item, index) => { if (item.name.toLowerCase().includes(filter.toLowerCase())) { const itemDiv = document.createElement('div'); itemDiv.className = 'checklist-item'; itemDiv.id = item.id; itemDiv.draggable = true; itemDiv.setAttribute('data-id', item.id); // Checkbox const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = item.active; checkbox.onchange = () => toggleActive(section, item.id); checkbox.className = 'item-checkbox'; // Textarea for name const textarea = document.createElement('textarea'); textarea.value = item.name; textarea.onchange = () => updateName(section, item.id, textarea.value); textarea.className = 'item-name'; // Priority label const prioritySpan = document.createElement('span'); prioritySpan.className = 'priority-box'; prioritySpan.textContent = `Priority: ${item.priority}`; prioritySpan.onclick = () => editPriority(section, item.id); // Delete button const deleteButton = document.createElement('button'); deleteButton.textContent = 'Delete'; deleteButton.className = 'delete-button'; deleteButton.onclick = () => deleteCriteria(section, item.id); // Append elements to itemDiv itemDiv.appendChild(checkbox); itemDiv.appendChild(textarea); itemDiv.appendChild(prioritySpan); itemDiv.appendChild(deleteButton); // Drag and Drop event listeners itemDiv.addEventListener('dragstart', handleDragStart); itemDiv.addEventListener('dragover', handleDragOver); itemDiv.addEventListener('drop', handleDrop); itemDiv.addEventListener('dragend', handleDragEnd); container.appendChild(itemDiv); } }); computeProgress(section); } // Drag and Drop Handlers let draggedItem = null; function handleDragStart(e) { draggedItem = this; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/html', this.outerHTML); this.classList.add('dragging'); } function handleDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; return false; } function handleDrop(e) { e.stopPropagation(); if (draggedItem !== this) { const section = this.id.split('-')[1].replace('item', ''); const data = loadData(section); const draggedId = draggedItem.id; const targetId = this.id; const draggedIndex = data.findIndex(item => item.id === draggedId); const targetIndex = data.findIndex(item => item.id === targetId); if (draggedIndex > -1 && targetIndex > -1) { // Reorder the array const [removed] = data.splice(draggedIndex, 1); data.splice(targetIndex, 0, removed); saveData(section, data); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); } } return false; } function handleDragEnd(e) { this.classList.remove('dragging'); draggedItem = null; } // Function to add a new criterion window.addCriteria = function(section) { const name = prompt('Enter the name of the new criterion:'); 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 (number) of the new criterion:'); if (priorityInput === null) return; // User cancelled const priority = parseInt(priorityInput, 10); if (isNaN(priority) || priority < 0) { alert('Priority must be a non-negative number.'); return; } const data = loadData(section); const newItem = { id: generateId(), name: trimmedName, priority: priority, active: true }; data.push(newItem); saveData(section, data); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); } // Function to delete a criterion window.deleteCriteria = function(section, id) { if (!confirm('Are you sure you want to delete this criterion?')) return; let data = loadData(section); data = data.filter(item => item.id !== id); saveData(section, data); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); } // Function to toggle active state window.toggleActive = function(section, id) { const data = loadData(section); const item = data.find(item => item.id === id); if (item) { item.active = !item.active; saveData(section, data); computeProgress(section); } } // Function to edit priority window.editPriority = function(section, id) { const data = loadData(section); const item = data.find(item => item.id === id); if (item) { const newPriorityInput = prompt('Enter the new priority:', item.priority); if (newPriorityInput === null) return; // User cancelled const newPriority = parseInt(newPriorityInput, 10); if (isNaN(newPriority) || newPriority < 0) { alert('Priority must be a non-negative number.'); return; } item.priority = newPriority; saveData(section, data); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); } } // Function to update name from textarea window.updateName = function(section, id, newName) { const trimmedName = newName.trim(); if (trimmedName === '') { alert('Criterion name cannot be empty.'); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); return; } const data = loadData(section); const item = data.find(item => item.id === id); if (item) { item.name = trimmedName; saveData(section, data); computeProgress(section); } } // Function to export checklist data as JSON window.exportChecklistData = function(section) { const data = loadData(section); const dataStr = JSON.stringify(data, 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 = `forexChecklist_section${section}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); } // Function to import checklist data from JSON window.importChecklistData = function(section) { const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; input.onchange = 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 item importedData.forEach(item => { if (typeof item.id !== 'string' || typeof item.name !== 'string' || typeof item.priority !== 'number' || typeof item.active !== 'boolean') { throw new Error('Invalid item structure.'); } }); saveData(section, importedData); renderChecklist(section, document.getElementById(`searchBoxSection${section}`).value); alert('Checklist imported successfully.'); } catch (error) { alert('Failed to import checklist: ' + error.message); } } reader.readAsText(file); } input.click(); } // Function to search/filter criteria window.searchCriteria = function(section) { const filter = document.getElementById(`searchBoxSection${section}`).value; renderChecklist(section, filter); } // Initial rendering on page load window.onload = function() { const section = '1'; // Assuming section '1' based on your HTML renderChecklist(section); } })(); </script> <style> /* (Your existing CSS content) */ /* Additional styles for drag-and-drop feedback */ .checklist-item.dragging { opacity: 0.5; } .checklist-item:hover { background: #2E2E2E; } .checklist-item textarea { flex: 1; margin: 0 10px; } .delete-button { background: #E74C3C; border: none; color: white; cursor: pointer; } .delete-button:hover { background: #C0392B; } .add-button, .export-button, .import-button { margin: 5px; } .priority-box { cursor: pointer; } /* Responsive adjustments */ @media (max-width: 768px) { .checklist-item { flex-direction: column; align-items: flex-start; } .checklist-item textarea { width: 100%; margin: 10px 0; } .delete-button { align-self: flex-end; } } </style> </head> <body> <main class="container" id="containerSection1"> <header> <h1 class="editable-title" id="titleSection1" contenteditable="true">Essential Criteria</h1> <div class="slider-background"> <div id="sliderFillSection1" class="slider-fill"> <div id="numericalLabelSection1" class="numerical-label">0</div> </div> </div> <div class="item-count flex-container"> <label>Total:</label> <span id="totalItemsSection1">0</span> <label>Active:</label> <span id="activeItemsSection1">0</span> </div> <input type="text" id="searchBoxSection1" class="narrow-search-box" placeholder="Search criteria..." oninput="searchCriteria('1')"> </header> <section> <div id="checklistContainerSection1" class="checklist-container"></div> </section> <section class="button-container"> <button onclick="addCriteria('1')" class="add-button">Add</button> <button onclick="exportChecklistData('1')" class="export-button">Export</button> <button onclick="importChecklistData('1')" class="import-button">Import</button> </section> </main> </body> </html>Key Points:
-
Unique Identifiers: Each checklist item has a unique
idgenerated using the current timestamp and a random number to ensure uniqueness. -
Drag-and-Drop: The drag-and-drop functionality allows users to reorder criteria seamlessly. When an item is dropped in a new position, the underlying data structure is updated, and the new order is saved to
localStorage. -
Real-Time Updates: Any change to the checklist (addition, deletion, editing, toggling) immediately updates the UI and recalculates the progress bar without needing a page refresh.
-
Data Validation: User inputs for the criterion name and priority are validated to ensure that names are not empty and priorities are valid non-negative numbers.
-
Persistent Storage: All checklist data is saved in the browser's
localStorage, ensuring that the user's data persists across sessions. -
Import/Export with Error Handling: Users can export their checklist as a JSON file and import it back. The import function includes error handling to manage improperly formatted JSON files gracefully.
-
Search Functionality: The search bar filters the displayed criteria in real-time based on the user's input, making it easier to locate specific criteria.
Additional Recommendations:
-
Accessibility: Consider adding ARIA attributes and keyboard navigation support to enhance accessibility.
-
Enhanced Styling: You can further enhance the UI/UX by adding animations or more sophisticated styles during drag-and-drop operations.
-
Multiple Sections Support: If you plan to support multiple sections in the future, ensure that the JavaScript functions are adequately parameterized to handle different section IDs.
Feel free to integrate this script into your HTML file within the
<script>tag, and adjust styles as needed to fit your design preferences. This implementation should provide a robust and interactive Forex Checklist Analyzer that meets all your specified requirements. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.