feat: replace the food table by a better ui

This commit is contained in:
2025-09-03 21:03:46 -03:00
parent 5b62fd989f
commit 71564b1c80
5 changed files with 138 additions and 109 deletions
+108 -61
View File
@@ -3,6 +3,7 @@ import { getButtonById, getButtonListByClassName, getDivById, getInputById, show
import { FoodItem, FoodStorage } from './types.js';
import { AppwriteAuth, AppwriteDB } from './appwrite.js';
import swal from 'sweetalert';
import { Models } from 'appwrite';
// App state
let selectedDate = new Date();
@@ -11,6 +12,9 @@ let searchTimeout: number | null = null;
let selectedFood: FoodItem | null = null; // review here
let currentHighlightIndex: number = -1;
let currentResults: FoodItem[] = [];
let totalCaloriesToday: number = 0;
let totalGramsToday: number = 0;
let totalAlkalineToday: number = 0;
// Authentication state
let currentUser: any | null = null;
@@ -283,11 +287,20 @@ function hideLoading() {
// Clear application data
function clearAppData() {
getDivById('foodTableBody').innerHTML = '';
getDivById('caloriesCounter').textContent = '0';
getInputById('foodSearchInput').value = '';
getInputById('gramAmount').value = '100';
getDivById('foodCardsContainer').innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🍽️</div>
<div>No food items logged yet.</div>
<div style="margin-top: 8px; font-size: 14px; opacity: 0.7;">Add your first item to get started!</div>
</div>
`;
selectedFood = null;
totalCaloriesToday = 0;
totalGramsToday = 0;
totalAlkalineToday = 0;
}
const getFoodData = (grams: number, foodData: FoodItem): FoodItem => {
@@ -537,17 +550,65 @@ function hideSearchResults() {
currentHighlightIndex = -1;
}
function toggleCardHandler(e: Event) {
e.preventDefault();
e.stopPropagation();
const card = e.currentTarget as HTMLElement;
card.classList.toggle('expanded');
const cardDetails = card.nextElementSibling as HTMLElement;
if (cardDetails && cardDetails.classList.contains('card-details')) {
cardDetails.classList.toggle('expanded');
}
}
function deleteCardHandler(e: Event) {
e.preventDefault();
e.stopPropagation();
const card = e.currentTarget as HTMLElement;
const foodId = card.getAttribute('data-food-id');
if (foodId) {
handleDeleteFood(foodId);
}
}
function editCardHandler(e: Event) {
e.preventDefault();
e.stopPropagation();
const card = e.currentTarget as HTMLElement;
const foodId = card.getAttribute('data-food-id');
if (foodId) {
// FIXME: Implement edit functionality
// handleEditFood(foodId);
window.alert('Edit functionality is not implemented yet.');
}
}
const addDeleteEvents = () => {
const elements = getButtonListByClassName('delete-food-entry');
Array.from(elements).forEach((el: HTMLButtonElement) => {
el.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
const row = target.closest('tr');
const entryId = row?.querySelector('.hidden-column')?.textContent;
if (entryId && row) {
handleDeleteFood(entryId);
}
});
// Setup toggle show cards events
const cards = getButtonListByClassName('card-header-toggle');
Array.from(cards).forEach((card: HTMLElement) => {
card.removeEventListener('click', toggleCardHandler);
card.addEventListener('click', toggleCardHandler);
});
// Setup delete card events
const deleteCards = getButtonListByClassName('btn-delete');
Array.from(deleteCards).forEach((card: HTMLElement) => {
card.removeEventListener('click', deleteCardHandler);
card.addEventListener('click', deleteCardHandler);
});
// Setup edit card events
const editCards = getButtonListByClassName('btn-edit');
Array.from(editCards).forEach((card: HTMLElement) => {
card.removeEventListener('click', editCardHandler);
card.addEventListener('click', editCardHandler);
});
}
@@ -611,7 +672,7 @@ const addFood = async () => {
addFoodToTable(entry, savedEntry.$id);
// Update totals
updateTotalCalories();
updateTotalCalories([savedEntry]);
// Update total macros
const proteinDiv: HTMLElement = getDivById('proteinValue');
@@ -655,7 +716,6 @@ async function loadFoodEntries(date: Date) {
const entries = await AppwriteDB.getFoodEntries(date);
// Clear current table
getDivById('foodTableBody').innerHTML = '';
getDivById('foodCardsContainer').innerHTML = '';
// Add each entry to table
@@ -691,7 +751,7 @@ async function loadFoodEntries(date: Date) {
addDeleteEvents();
// Update total calories
updateTotalCalories();
updateTotalCalories(entries);
// Update counters
let totalCalories = 0;
@@ -783,7 +843,6 @@ async function handleDeleteFood(documentId: string) {
await AppwriteDB.deleteFoodEntry(documentId);
selectDate(selectedDate);
} catch (error) {
console.error('Delete food error:', error);
swal('Oh no!', 'Failed to delete food entry: ' + error.message, 'error');
@@ -794,36 +853,18 @@ async function handleDeleteFood(documentId: string) {
// Add food to table (existing function - update to use document ID)
function addFoodToTable(foodData: FoodStorage, documentId: string) {
const tableBody = document.getElementById('foodTableBody');
const row = document.createElement('tr');
row.innerHTML = `
<td class="hidden-column">${documentId}</td>
<td>${foodData.time || new Date().toLocaleTimeString()}</td>
<td>${foodData.name}</td>
<td>${foodData.grams}</td>
<td>${foodData.calories}</td>
<td>${foodData.protein}</td>
<td>${foodData.fat}</td>
<td>${foodData.carbs}</td>
<td>${foodData.fiber}</td>
<td><button class="delete-btn delete-food-entry">Delete</button></td>
<td class="hidden-column">${foodData.alkaline}</td>
`;
tableBody?.appendChild(row);
// Setup Delete events
addDeleteEvents();
// New Food card
const container = document.getElementById('foodCardsContainer');
const container = getDivById('foodCardsContainer');
const card = document.createElement('div');
card.className = 'food-card';
card.setAttribute('data-id', documentId);
if (container.innerHTML.includes('empty-state')) {
container.innerHTML = '';
}
card.innerHTML = `
<div class="card-header" onclick="toggleCard(${documentId})">
<div class="card-header card-header-toggle">
<div class="card-main-info">
<div class="food-name-time">
<div class="food-name">${foodData.name}</div>
@@ -854,42 +895,45 @@ function addFoodToTable(foodData: FoodStorage, documentId: string) {
</div>
</div>
<div class="card-actions">
<button class="btn btn-edit" onclick="editFood(${documentId})">Edit</button>
<button class="btn btn-delete" onclick="deleteFood(${documentId})">Delete</button>
<button class="btn btn-edit" data-food-id="${documentId}">Edit</button>
<button class="btn btn-delete" data-food-id="${documentId}">Delete</button>
</div>
</div>
</div>
`;
container?.appendChild(card);
// Setup Delete events
addDeleteEvents();
}
// Update total calories
function updateTotalCalories() {
const caloriesCells = document.querySelectorAll('#foodTableBody td:nth-child(5)'); // 5th column is calories
let total = 0;
caloriesCells.forEach((cell: Element) => {
total += parseInt(cell.innerHTML) || 0;
function updateTotalCalories(entries: Models.DefaultDocument[]) {
let total = totalCaloriesToday;
entries.forEach((entry: Models.DefaultDocument) => {
total += entry.calories || 0;
});
getDivById('caloriesCounter').textContent = total.toString();
totalCaloriesToday = total;
// FIX ME: alkaline count
// Update alkaline level
const gramsCell = document.querySelectorAll('#foodTableBody td:nth-child(4)'); // 4th is grams
let totalGrams = 0;
let totalGrams = totalGramsToday;
let indexMap: {index: number, grams: number}[] = [];
gramsCell.forEach((cell: Element, key: number) => {
totalGrams += parseInt(cell.innerHTML) || 0;
entries.forEach((entry: Models.DefaultDocument, key: number) => {
totalGrams += entry.grams || 0;
indexMap.push({
index: key,
grams: parseInt(cell.innerHTML) || 0
grams: entry.grams || 0
});
});
const alkalineCell = document.querySelectorAll('#foodTableBody td:nth-child(11)'); // 11th is alkaline
let totalAlkaline = 0;
alkalineCell.forEach((cell: Element, key: number) => {
if (cell.innerHTML === 'true') {
let totalAlkaline = totalAlkalineToday;
entries.forEach((entry: Models.DefaultDocument, key: number) => {
if (entry.alkaline) {
for (let ob of indexMap) {
if (ob.index === key) {
totalAlkaline += ob.grams;
@@ -916,6 +960,9 @@ const nextMonth = () => {
const selectDate = async (date: Date) => {
selectedDate = date;
totalCaloriesToday = 0;
totalGramsToday = 0;
totalAlkalineToday = 0;
updateCurrentDate();
await loadFoodEntries(date);
renderCalendar();
@@ -1028,16 +1075,16 @@ function createDayElement(day: number, isOtherMonth: boolean, year: number, mont
return dayElement;
}
function toggleCard(id) {
function toggleCard(id: string) {
const card = document.querySelector(`[data-id="${id}"]`);
card.classList.toggle('expanded');
card?.classList.toggle('expanded');
}
function deleteFood(id) {
function deleteFood(id: string) {
handleDeleteFood(id);
}
function editFood(id) {
function editFood(id: string) {
alert(`Edit functionality for food item ${id} would be implemented here`);
}