diff --git a/js/dataManager.js b/js/dataManager.js index e50cb6a..b146d7c 100644 --- a/js/dataManager.js +++ b/js/dataManager.js @@ -180,6 +180,15 @@ const DataManager = (() => { return results; }; + /** + * Get a specific meal entry by date + * @param {string} dateString - Date in YYYY-MM-DD format + * @returns {Object|undefined} - Meal entry or undefined if not found + */ + const getMealByDate = (dateString) => { + return appData.meals.find(meal => meal.date === dateString); + }; + /** * Add a meal entry * @param {Object} entry - Meal entry {date, breakfast, lunch, dinner, otherMeals} @@ -417,6 +426,7 @@ const DataManager = (() => { addMeal, deleteMeal, getMeals, + getMealByDate, exportData, importData, exportCSV, diff --git a/js/ui.js b/js/ui.js index 11edcc0..a7fd183 100644 --- a/js/ui.js +++ b/js/ui.js @@ -34,6 +34,9 @@ const UI = (() => { // Initialize form submissions initForms(); + + // Populate meal form for the initial date (today) + populateMealFormForDate(document.getElementById('meal-date').value); // Initialize data import/export initDataManagement(); @@ -67,11 +70,28 @@ const UI = (() => { // Activate the selected tab tabs[tabKey].btn.classList.add('active'); tabs[tabKey].content.classList.add('active'); + + // If switching to meals tab, ensure form is populated for the current meal date + if (tabKey === 'meals') { + populateMealFormForDate(document.getElementById('meal-date').value); + } }; /** * Initialize form submissions */ + /** + * Populate the meal form fields based on data for the given date. + * @param {string} dateString - The date (YYYY-MM-DD) to load data for. + */ + const populateMealFormForDate = (dateString) => { + const mealData = DataManager.getMealByDate(dateString); + document.getElementById('breakfast').value = mealData?.breakfast || ''; + document.getElementById('lunch').value = mealData?.lunch || ''; + document.getElementById('dinner').value = mealData?.dinner || ''; + document.getElementById('other-meals').value = mealData?.otherMeals || ''; + }; + const initForms = () => { // Weight form submission forms.weight.addEventListener('submit', (e) => { @@ -112,6 +132,10 @@ const UI = (() => { }); // Meal form submission + document.getElementById('meal-date').addEventListener('change', (e) => { + populateMealFormForDate(e.target.value); + }); + forms.meal.addEventListener('submit', (e) => { e.preventDefault(); @@ -127,11 +151,8 @@ const UI = (() => { if (DataManager.addMeal(mealEntry)) { Utils.showNotification('Meal entries saved successfully', 'success'); - // Reset form except for date - document.getElementById('breakfast').value = ''; - document.getElementById('lunch').value = ''; - document.getElementById('dinner').value = ''; - document.getElementById('other-meals').value = ''; + // Refresh form with current date's data (which might have just been updated) + populateMealFormForDate(mealEntry.date); // Refresh table renderMealTable();