Last active
March 13, 2024 12:22
-
-
Save amitworx/19b4657b9db0def21296a5f7ffcb35a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ajaxURL, wppdURL, restURL,user, loginURL,signUpURL} from './variables.js'; | |
import screenTripPlanningPage from './screens/tripPlanningPage.js'; | |
import renderSignup from './signup.js'; | |
// import renderInit from './init.js'; | |
import renderEditTripPlanningPage from './editTripPlanningPage.js'; | |
import renderTripPlanningPageAfterLogin from './tripPlanningPageAfterLogin.js'; | |
// rIcon | |
import {rIcon} from './components/icon.js'; | |
// helpers | |
// import {generateUniqueID,stepBack, showAjaxMessage, showMessage} from './helper.js'; | |
async function renderTripPlanningPage(approot, planner,user) { | |
// clear the approot | |
approot.innerHTML = ''; | |
// get plannerData from session storage and if not null or empty | |
if(sessionStorage.getItem('plannerData') !== null && sessionStorage.getItem('plannerData') !== ''){ | |
planner.load(); | |
} | |
// show loading spinner | |
// add show class to wppd__app-spinner | |
document.querySelector('.wppd__app-spinner').classList.add('show'); | |
// fetch data from rest api | |
let id = ''; | |
if(user){ | |
id=planner.userTemplateID; | |
}else{ | |
id=planner.adminTemplateID; | |
} | |
// if planner has packingList and packingListIcon, packingListName and packingListItems | |
if(planner.packingList && planner.packingList.packingListIcon && planner.packingList.packingListName && planner.packingList.packingListItems){ | |
// hide loading spinner | |
// remove show class from wppd__app-spinner | |
document.querySelector('.wppd__app-spinner').classList.remove('show'); | |
// get the list from template screen html and inject the list from template screen html | |
approot.innerHTML = screenTripPlanningPage(planner); | |
// get the list from template screen | |
let screen = document.querySelector('[data-wppd-step="trip-planning"]'); | |
// attach event handlers | |
attachEventHandlers(approot,screen, planner); | |
}else{ | |
// fetch admin templates by id | |
fetch(`${restURL}/templates/${id}`, { | |
method: 'GET', | |
headers: { | |
'Content-Type': 'application/json', | |
// 'X-WP-Nonce': nonce, | |
} | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
//planner.update('packingListFromTemplate', data); | |
// planner.update('packingListItems', data); | |
planner.update('packingListIcon', data.icon); | |
planner.update('packingListName', data.title); | |
planner.update('packingListItems', data._packing_list); | |
// hide loading spinner | |
// remove show class from wppd__app-spinner | |
document.querySelector('.wppd__app-spinner').classList.remove('show'); | |
// get the list from template screen html and inject the list from template screen html | |
approot.innerHTML = screenTripPlanningPage(planner); | |
// get the list from template screen | |
let screen = document.querySelector('[data-wppd-step="trip-planning"]'); | |
// attach event handlers | |
attachEventHandlers(approot,screen, planner); | |
}) | |
} | |
} | |
// function attachEventHandlersListFromTemplate(screen, planner, renderSignup, renderInit){ | |
function attachEventHandlers(approot,screen, planner){ | |
let data = []; | |
data = planner.packingList.packingListItems; | |
let expandedCategories = {}; | |
// function addNewItem(catIndex) { | |
// let newItemName = document.getElementById(`newItemName${catIndex}`).value.trim(); | |
// if (!newItemName) { | |
// alert("Please enter an item name."); | |
// return; | |
// } | |
// // Construct new item object | |
// let newItem = { | |
// "item_name": newItemName, | |
// "item_quantity": "1", | |
// "gear_recommendation": "", | |
// "item_owned": "1" | |
// }; | |
// // Add to the appropriate category | |
// // Add to the appropriate category | |
// data[catIndex].items.push(newItem); | |
// // Update UI | |
// updateCategories(); | |
// } | |
// function updateGearContainer(){ | |
// // gearContainer | |
// data.forEach((category, catIndex) => { | |
// if(category.type == 'Grocery'){ | |
// return; | |
// } | |
// if (!category || typeof category !== 'object' || Object.keys(category).length === 0) { | |
// console.error('Invalid category data:', category); | |
// return; // Skip this iteration | |
// } | |
// let categoryDiv = document.createElement('div'); | |
// categoryDiv.classList.add('category', 'category__table'); | |
// let categoryName = category.category_name; | |
// let categoryID = category.id; | |
// // add all item_quantity in category[categoryName] | |
// let total = 0; | |
// category.items.forEach(function (el) { | |
// if(el.item_owned) return; | |
// total += parseInt(el.item_quantity); | |
// }); | |
// categoryDiv.innerHTML = `<div class = "category__table-row category__table-head"> | |
// <div class="category__table-col category__table-title"> | |
// <span class='name'>${categoryName}</span> | |
// <span class='menu'> | |
// <span class="toggle toggle__collapsed hide">+</span> | |
// <span class="toggle toggle__expanded">-</span> | |
// </span> | |
// </div> | |
// <div class="category__table-col category__table-col-qty">${total}</div> | |
// <div class="category__table-col"></div> | |
// </div> | |
// `; | |
// let itemsDiv = document.createElement('div'); | |
// itemsDiv.classList.add('items-container','category__table-body'); | |
// category.items.forEach((item, itemIndex) => { | |
// if(item.item_owned) return; | |
// let itemDiv = document.createElement('div'); | |
// itemDiv.classList.add('item'); | |
// // Displaying the value of "item_name" | |
// let itemName = item.item_name; | |
// let recommendationURL = item.gear_recommendation; | |
// let radioName = `acquisition_type_${categoryName}_${itemName}_${categoryID}`; | |
// // itemDiv.textContent = itemName; | |
// itemDiv.innerHTML = `<div class = "category__table-row"> | |
// <div class="category__table-col"> | |
// ${recommendationURL ? rIcon(recommendationURL, wppdURL) : ''} | |
// ${itemName} | |
// </div> | |
// <div class="category__table-col category__table-col-qty"><span class="qty">${item.item_quantity}</span></div> | |
// <div class="category__table-col acquisition__type"> | |
// <label><input type="radio" name="${radioName}" value="Bought"><span>Bought</span></label> <span class="sep">|</span> | |
// <label><input type="radio" name="${radioName}" value="Borrowed" ${item.item_packed == "1" ? 'checked' : '' }><span>Borrowed</span></label> | |
// </div> | |
// </div> | |
// `; | |
// itemsDiv.appendChild(itemDiv); | |
// }); | |
// categoryDiv.appendChild(itemsDiv); | |
// gearContainer.appendChild(categoryDiv); | |
// // Add category to gear container | |
// }); | |
// // add event listeners to items | |
// gearContainer.querySelectorAll(".toggle__collapsed").forEach(function (el) { | |
// el.addEventListener("click", function (e) { | |
// e.preventDefault(); | |
// // add hide class to element | |
// el.classList.toggle("hide"); | |
// // get parent .menu and find .toggle__expanded | |
// el.closest(".menu").querySelector(".toggle__expanded").classList.toggle("hide"); | |
// // get parent category__table and find category__table-body and toggle close class | |
// el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
// }); | |
// }); | |
// // add event listeners to items | |
// gearContainer.querySelectorAll(".toggle__expanded").forEach(function (el) { | |
// el.addEventListener("click", function (e) { | |
// e.preventDefault(); | |
// // add hide class to element | |
// el.classList.toggle("hide"); | |
// // get parent .menu and find .toggle__collapsed | |
// el.closest(".menu").querySelector(".toggle__collapsed").classList.toggle("hide"); | |
// // get parent category__table and find category__table-body and toggle close class | |
// el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
// }); | |
// }); | |
// } | |
// groceryContainer | |
// function updateGroceryContainer(){ | |
// // gearContainer | |
// data.forEach((category, catIndex) => { | |
// if(category.type == 'Grocery'){ | |
// if (!category || typeof category !== 'object' || Object.keys(category).length === 0) { | |
// console.error('Invalid category data:', category); | |
// return; // Skip this iteration | |
// } | |
// let categoryDiv = document.createElement('div'); | |
// categoryDiv.classList.add('category', 'category__table'); | |
// let categoryName = category.category_name; | |
// // add all item_quantity in category[categoryName] | |
// let total = 0; | |
// category.items.forEach(function (el) { | |
// total += parseInt(el.item_quantity); | |
// // total += parseInt(el.item_quantity); | |
// }); | |
// // split categoryName by ____ and get the first element | |
// categoryDiv.innerHTML = `<div class = "category__table-row category__table-head"> | |
// <div class="category__table-col category__table-title"> | |
// <span class='name'>${categoryName}</span> | |
// <span class='menu'> | |
// <span class="toggle toggle__collapsed hide">+</span> | |
// <span class="toggle toggle__expanded">-</span> | |
// </span> | |
// </div> | |
// <div class="category__table-col category__table-col-qty">${total}</div> | |
// <div class="category__table-col"></div> | |
// </div> | |
// `; | |
// let itemsDiv = document.createElement('div'); | |
// itemsDiv.classList.add('items-container','category__table-body'); | |
// category.items.forEach((item, itemIndex) => { | |
// let itemDiv = document.createElement('div'); | |
// itemDiv.classList.add('item'); | |
// // Displaying the value of "item_name" | |
// let itemName = item.item_name; | |
// // itemDiv.textContent = itemName; | |
// itemDiv.innerHTML = `<div class = "category__table-row"> | |
// <div class="category__table-col"> | |
// ${itemName} | |
// </div> | |
// <div class="category__table-col category__table-col-qty"><span class="qty">${item.item_quantity}</span></div> | |
// <div class="category__table-col own__toggle"> | |
// <label><input type="checkbox" ${item.item_packed == "1" ? ` checked ` : `` } class="own__item" disabled ><span></span></label> | |
// </div> | |
// </div> | |
// `; | |
// itemsDiv.appendChild(itemDiv); | |
// }); | |
// categoryDiv.appendChild(itemsDiv); | |
// groceryContainer.appendChild(categoryDiv); | |
// // Add category to grocery container | |
// } | |
// // add event listeners to items | |
// }); | |
// groceryContainer.querySelectorAll(".toggle__collapsed").forEach(function (el) { | |
// el.addEventListener("click", function (e) { | |
// e.preventDefault(); | |
// // add hide class to element | |
// el.classList.toggle("hide"); | |
// // get parent .menu and find .toggle__expanded | |
// el.closest(".menu").querySelector(".toggle__expanded").classList.toggle("hide"); | |
// // get parent category__table and find category__table-body and toggle close class | |
// el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
// }); | |
// }); | |
// // add event listeners to items | |
// groceryContainer.querySelectorAll(".toggle__expanded").forEach(function (el) { | |
// el.addEventListener("click", function (e) { | |
// e.preventDefault(); | |
// // add hide class to element | |
// el.classList.toggle("hide"); | |
// // get parent .menu and find .toggle__collapsed | |
// el.closest(".menu").querySelector(".toggle__collapsed").classList.toggle("hide"); | |
// // get parent category__table and find category__table-body and toggle close class | |
// el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
// }); | |
// }); | |
// } | |
function updateCategories() { | |
let container = document.getElementById('categoriesContainer'); | |
const gearContainer = document.getElementById('gearContainer'); | |
const groceryContainer = document.getElementById('groceryContainer'); | |
// gears to acquire list | |
const gearsToAcquire = []; | |
const groceryToAcquire = []; | |
gearContainer.innerHTML = ''; | |
groceryContainer.innerHTML = ''; | |
// Store the expanded states before clearing the container | |
document.querySelectorAll('.category').forEach(cat => { | |
const catIndex = cat.getAttribute('data-cat-index'); | |
const isExpanded = !cat.querySelector('.category__table-body').classList.contains('close'); | |
expandedCategories[catIndex] = isExpanded; | |
}); | |
// Clear the container | |
container.innerHTML = ''; | |
data.forEach((category, catIndex) => { | |
if (!category || typeof category !== 'object' || Object.keys(category).length === 0) { | |
console.error('Invalid category data:', category); | |
return; // Skip this iteration | |
} | |
// console.log('category'); | |
// console.log(category); | |
let categoryDiv = document.createElement('div'); | |
categoryDiv.classList.add('category', 'category__table'); | |
categoryDiv.draggable = true; | |
categoryDiv.setAttribute('data-cat-index', catIndex); | |
let categoryName = category.category_name; | |
let total = 0; | |
category.items.forEach(function (el) { | |
total += parseInt(el.item_quantity); | |
}); | |
// total number of items in category | |
let categoryItemsNumber = category.items.length; | |
// total number of items owned in category | |
let categoryItemsPacked = 0; | |
category.items.forEach(function (el) { | |
if(el.item_packed) categoryItemsPacked++; | |
}); | |
// percentage of items owned in category | |
let percentOwned = Math.round((categoryItemsPacked / categoryItemsNumber) * 100); | |
categoryDiv.innerHTML = `<div class = "category__table-row category__table-head"> | |
<div class="category__table-col category__table-title"> | |
<span class='name'>${categoryName}</span> | |
<span class='menu'> | |
<span class="toggle toggle__collapsed hide">+</span> | |
<span class="toggle toggle__expanded">-</span> | |
</span> | |
</div> | |
<div class="category__table-col category__table-col-qty">${total}</div> | |
<div class="category__table-col flex-justify-center">${percentOwned}%</div> | |
</div> | |
`; | |
let itemsDiv = document.createElement('div'); | |
itemsDiv.classList.add('items-container','category__table-body'); | |
category.items.forEach((item, itemIndex) => { | |
let itemDiv = document.createElement('div'); | |
itemDiv.classList.add('item'); | |
itemDiv.draggable = true; | |
itemDiv.setAttribute('data-item-index', itemIndex); | |
itemDiv.setAttribute('data-cat-index', catIndex); | |
// collect gear to acquire | |
if( category.type !=="Grocery" && item.item_owned == "0"){ | |
// we capture category, cat index, item, item index, so that if the categor name is same it creates an array of array for item and item index like [ {categoryName : category , catIndex : catindex, items: [[item1, item1index], [item2, item2index]...]}] ] | |
// Find the category object in the array or create a new one | |
let categoryObject = gearsToAcquire.find(category => category.categoryName === categoryName); | |
if (!categoryObject) { | |
// If the category doesn't exist, create a new one | |
categoryObject = { | |
categoryName: categoryName, | |
catIndex: catIndex, | |
categoryID: category.id, | |
items: [] | |
}; | |
// Add the new category object to the array | |
gearsToAcquire.push(categoryObject); | |
} | |
// Push the item details as an array to the items array of the category item_name, itemIndex, item_quantity, item_packed, gear_recommendation, item_acquisition_type | |
// console.log("item"); | |
// console.log(item); | |
categoryObject.items.push([item.item_name, itemIndex, item.item_quantity, item.item_packed, item.gear_recommendation , item.item_acquisition_type]); | |
} | |
// collect grocery to acquire | |
if( category.type =="Grocery" && item.item_owned == "0"){ | |
// we capture category, cat index, item, item index, so that if the categor name is same it creates an array of array for item and item index like [ {categoryName : category , catIndex : catindex, items: [[item1, item1index], [item2, item2index]...]}] ] | |
// Find the category object in the array or create a new one | |
let categoryObject = groceryToAcquire.find(category => category.categoryName === categoryName); | |
if (!categoryObject) { | |
// If the category doesn't exist, create a new one | |
categoryObject = { | |
categoryName: categoryName, | |
catIndex: catIndex, | |
categoryID: category.id, | |
items: [] | |
}; | |
// Add the new category object to the array | |
groceryToAcquire.push(categoryObject); | |
} | |
// Push the item details as an array to the items array of the category item_name, itemIndex, item_quantity, item_packed, gear_recommendation, item_acquisition_type | |
// console.log("item"); | |
// console.log(item); | |
categoryObject.items.push([item.item_name, itemIndex, item.item_quantity, item.item_owned, item.gear_recommendation , item.item_acquisition_type]); | |
} | |
// Displaying the value of "item_name" | |
let itemName = item.item_name; | |
// itemDiv.textContent = itemName; | |
itemDiv.innerHTML = `<div class = "category__table-row"> | |
<div class="category__table-col"> | |
${itemName} | |
</div> | |
<div class="category__table-col category__table-col-qty"><span class="decrement">-</span><input type ="text" name="qty" class="qty" value="${item.item_quantity}" min="1"><span class="increment">+</span></div> | |
<div class="category__table-col own__toggle"> | |
<label><input type="checkbox" ${item.item_packed == "1" ? ` checked ` : `` } class="own__item" ><span></span></label> | |
</div> | |
</div> | |
`; | |
itemsDiv.appendChild(itemDiv); | |
}); | |
// Add input field | |
// let newItemInput = document.createElement('input'); | |
// newItemInput.type = 'text'; | |
// newItemInput.placeholder = 'Enter new item name'; | |
// newItemInput.id = `newItemName${catIndex}`; | |
// Add button | |
// let addButton = document.createElement('button'); | |
// addButton.textContent = 'Add Item'; | |
// addButton.addEventListener('click', () => addNewItem(catIndex)); | |
// Append input and button to the category div | |
// let newItemDiv = document.createElement('div'); | |
// newItemDiv.classList.add('add__new-item'); | |
// newItemDiv.appendChild(newItemInput); | |
// newItemDiv.appendChild(addButton); | |
categoryDiv.appendChild(itemsDiv); | |
// categoryDiv.appendChild(newItemDiv); | |
container.appendChild(categoryDiv); | |
console.log('gearsToAcquire'); | |
console.log(gearsToAcquire); | |
}); | |
// lets populate gearContainer | |
gearContainer.innerHTML = ''; | |
gearsToAcquire.forEach((category) => { | |
let categoryDiv = document.createElement('div'); | |
categoryDiv.classList.add('category', 'category__table'); | |
categoryDiv.setAttribute('data-cat-index', category.catIndex); | |
let categoryName = category.categoryName; | |
let categoryID = category.categoryID; | |
let total = 0; | |
category.items.forEach(function (el) { | |
total += parseInt(el[2]); | |
}); | |
// total number of items in category | |
let categoryItemsNumber = category.items.length; | |
// total number of items owned in category | |
// let categoryItemsOwned = 0; | |
// category.items.forEach(function (el) { | |
// if(el.item_owned) categoryItemsOwned++; | |
// }); | |
// // percentage of items owned in category | |
// let percentOwned = Math.round((categoryItemsOwned / categoryItemsNumber) * 100); | |
categoryDiv.innerHTML = `<div class = "category__table-row category__table-head"> | |
<div class="category__table-col category__table-title"> | |
<span class='name'>${categoryName}</span> | |
<span class='menu'> | |
<span class="toggle toggle__collapsed hide">+</span> | |
<span class="toggle toggle__expanded">-</span> | |
</span> | |
</div> | |
<div class="category__table-col category__table-col-qty">${total}</div> | |
<div class="category__table-col flex-justify-center"></div> | |
</div> | |
`; | |
let itemsDiv = document.createElement('div'); | |
itemsDiv.classList.add('items-container','category__table-body'); | |
category.items.forEach((item, itemIndex) => { | |
let itemDiv = document.createElement('div'); | |
itemDiv.classList.add('item'); | |
// itemDiv.draggable = true; | |
itemDiv.setAttribute('data-item-index', item[1]); | |
itemDiv.setAttribute('data-cat-index', category.catIndex); | |
// Displaying the value of "item_name" | |
// Displaying the value of "item_name" | |
let itemName = item[0]; | |
// trim itemName | |
let itemNameRadio = itemName.trim(); | |
// replace space with _ in itemName | |
itemNameRadio = itemName.replace(/\s/g, '_'); | |
let categoryNameRadio = categoryName.trim(); | |
// replace space with _ in categoryName | |
categoryNameRadio = categoryName.replace(/\s/g, '_'); | |
let recommendationURL = item[4]; | |
let radioName = `acquisition_type_${categoryNameRadio}_${itemNameRadio}_${categoryID}`; | |
// itemDiv.textContent = itemName; | |
itemDiv.innerHTML = `<div class = "category__table-row"> | |
<div class="category__table-col"> | |
${recommendationURL ? rIcon(recommendationURL, wppdURL) : ''} | |
${itemName} | |
</div> | |
<div class="category__table-col category__table-col-qty"><span class="qty">${item[2]}</span></div> | |
<div class="category__table-col acquisition__type"> | |
<label><input type="radio" name="${radioName}" value="Bought"><span>Bought</span></label> <span class="sep">|</span> | |
<label><input type="radio" name="${radioName}" value="Borrowed" ${item[3] == "1" ? 'checked' : '' }><span>Borrowed</span></label> | |
</div> | |
</div> | |
`; | |
itemsDiv.appendChild(itemDiv); | |
}); | |
categoryDiv.appendChild(itemsDiv); | |
// categoryDiv.appendChild(newItemDiv); | |
gearContainer.appendChild(categoryDiv); | |
// Event listener for all .own__item checkboxes | |
document.querySelector("#gearContainer").addEventListener("change", function (e){ | |
if (e.target.matches(".acquisition__type input[type='radio']")) { // More specific selector | |
// get the previous value of the radio button | |
console.log("Change event triggered:", e.target.name, e.target.value); | |
} | |
// // get raddio value and name | |
// let radioValue = el.value; | |
// let radioName = el.name; | |
// console.log(radioValue); | |
// console.log(radioName); | |
// // if radioValue is Bought, then show dialog to user if they want it mark it as owned, if yes the item will be removed from the gearto acquire list, if user selects yes proceed, if no, do nothing return | |
// // if(radioValue == 'Borrowed'){ | |
// // // we continue | |
// // } | |
// if(radioValue == 'Bought'){ | |
// // we confirm if user wants to mark item as owned | |
// let confirmOwned = confirm("Do you want to mark this item as owned?"); | |
// // if user cancels, we return and reset the radio button to Borrowed | |
// console.log(confirmOwned); | |
// if(!confirmOwned){ | |
// el.checked = false; | |
// return; | |
// } | |
// } | |
// Get parent .item element | |
// let item = el.closest(".item"); | |
// if (item) { | |
// // Update item_owned in data | |
// let itemIndex = parseInt(item.getAttribute('data-item-index')); | |
// let catIndex = parseInt(item.getAttribute('data-cat-index')); | |
// if (!isNaN(itemIndex) && !isNaN(catIndex)) { | |
// data[catIndex].items[itemIndex].item_acquisition_type = radioValue; | |
// if(radioValue == 'Bought'){ | |
// data[catIndex].items[itemIndex].item_owned = 1; | |
// } | |
// if(radioValue == 'Borrowed'){ | |
// data[catIndex].items[itemIndex].item_owned = 0; | |
// data[catIndex].items[itemIndex].item_packed = 1; | |
// } | |
// // updateCategories(); | |
// planner.update('packingListItems', data); | |
// planner.save(); | |
// console.log("planner after update - acquisition type"); | |
// console.log(planner); | |
// updateCategories(); | |
// } | |
// } | |
}); | |
}); | |
// lets populate groceryContainer | |
groceryContainer.innerHTML = ''; | |
groceryToAcquire.forEach((category) => { | |
let categoryDiv = document.createElement('div'); | |
categoryDiv.classList.add('category', 'category__table'); | |
categoryDiv.setAttribute('data-cat-index', category.catIndex); | |
let categoryName = category.categoryName; | |
let total = 0; | |
category.items.forEach(function (el) { | |
total += parseInt(el[2]); | |
}); | |
// // total number of items in category | |
// let categoryItemsNumber = category.items.length; | |
// // total number of items owned in category | |
// let categoryItemsPacked = 0; | |
// category.items.forEach(function (el) { | |
// if(el[3]) categoryItemsPacked++; | |
// }); | |
// // percentage of items owned in category | |
// let percentOwned = Math.round((categoryItemsPacked / categoryItemsNumber) * 100); | |
categoryDiv.innerHTML = `<div class = "category__table-row category__table-head"> | |
<div class="category__table-col category__table-title"> | |
<span class='name'>${categoryName}</span> | |
<span class='menu'> | |
<span class="toggle toggle__collapsed hide">+</span> | |
<span class="toggle toggle__expanded">-</span> | |
</span> | |
</div> | |
<div class="category__table-col category__table-col-qty">${total}</div> | |
<div class="category__table-col flex-justify-center"></div> | |
</div> | |
`; | |
let itemsDiv = document.createElement('div'); | |
itemsDiv.classList.add('items-container','category__table-body'); | |
category.items.forEach((item, itemIndex) => { | |
let itemDiv = document.createElement('div'); | |
itemDiv.classList.add('item'); | |
// itemDiv.draggable = true; | |
itemDiv.setAttribute('data-item-index', item[1]); | |
itemDiv.setAttribute('data-cat-index', category.catIndex); | |
// Displaying the value of "item_name" | |
let itemName = item[0]; | |
// itemDiv.textContent = itemName; | |
itemDiv.innerHTML = `<div class = "category__table-row"> | |
<div class="category__table-col"> | |
${itemName} | |
</div> | |
<div class="category__table-col category__table-col-qty"><span class="qty">${item[2]}</span></div> | |
<div class="category__table-col own__toggle"> | |
<label><input type="checkbox" ${item[3] == "1" ? ` checked ` : `` } class="purchased__item" ><span></span></label> | |
</div> | |
</div> | |
`; | |
itemsDiv.appendChild(itemDiv); | |
}); | |
categoryDiv.appendChild(itemsDiv); | |
// categoryDiv.appendChild(newItemDiv); | |
groceryContainer.appendChild(categoryDiv); | |
// Event listener for all .own__item checkboxes | |
groceryContainer.querySelectorAll(".purchased__item").forEach(function (el) { | |
el.addEventListener("change", function (e) { | |
// get raddio value and name | |
let purchasedValue = el.checked ? 1 : 0; | |
// console.log(purchasedValue); | |
// Get parent .item element | |
let item = el.closest(".item"); | |
if (item) { | |
// Update item_owned in data | |
let itemIndex = parseInt(item.getAttribute('data-item-index')); | |
let catIndex = parseInt(item.getAttribute('data-cat-index')); | |
if (!isNaN(itemIndex) && !isNaN(catIndex)) { | |
data[catIndex].items[itemIndex].item_owned = purchasedValue; | |
// updateCategories(); | |
planner.update('packingListItems', data); | |
planner.save(); | |
console.log("planner after update - acquisition type"); | |
console.log(planner); | |
updateCategories(); | |
} | |
} | |
}); | |
}); | |
}); | |
// Restore expanded states after rebuilding categories | |
document.querySelectorAll('.category').forEach(cat => { | |
const catIndex = cat.getAttribute('data-cat-index'); | |
if (expandedCategories[catIndex]) { | |
cat.querySelector('.category__table-body').classList.remove('close'); | |
cat.querySelector('.toggle__collapsed').classList.add('hide'); | |
cat.querySelector('.toggle__expanded').classList.remove('hide'); | |
} | |
}); | |
// add event listeners to items | |
document.querySelectorAll(".toggle__collapsed").forEach(function (el) { | |
el.addEventListener("click", function (e) { | |
e.preventDefault(); | |
// add hide class to element | |
el.classList.toggle("hide"); | |
// get parent .menu and find .toggle__expanded | |
el.closest(".menu").querySelector(".toggle__expanded").classList.toggle("hide"); | |
// get parent category__table and find category__table-body and toggle close class | |
el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
}); | |
}); | |
// add event listeners to items | |
document.querySelectorAll(".toggle__expanded").forEach(function (el) { | |
el.addEventListener("click", function (e) { | |
e.preventDefault(); | |
// add hide class to element | |
el.classList.toggle("hide"); | |
// get parent .menu and find .toggle__collapsed | |
el.closest(".menu").querySelector(".toggle__collapsed").classList.toggle("hide"); | |
// get parent category__table and find category__table-body and toggle close class | |
el.closest(".category__table").querySelector(".category__table-body").classList.toggle("close"); | |
}); | |
}); | |
document.querySelectorAll(".increment").forEach(function (el) { | |
el.addEventListener("click", function (e) { | |
e.preventDefault(); | |
// get parent .menu and find .toggle__expanded | |
let qty = el.closest(".category__table-col-qty").querySelector(".qty"); | |
qty.value = parseInt(qty.value) + 1; | |
// update item_quantity in data | |
let itemIndex = parseInt(el.closest(".item").getAttribute('data-item-index')); | |
let catIndex = parseInt(el.closest(".item").getAttribute('data-cat-index')); | |
data[catIndex].items[itemIndex].item_quantity = parseInt(qty.value); | |
// get all the category__table-col-qty of the parent category__table and add them together and display in the category__table-col-qty of the parent category__table | |
let total = 0; | |
el.closest(".category__table").querySelectorAll(".category__table-col-qty .qty").forEach(function (el) { | |
total += parseInt(el.value); | |
}); | |
el.closest(".category__table").querySelector(".category__table-col-qty").textContent = total; | |
updateCategories(); | |
}); | |
}); | |
// add eventlistener to number input .qty | |
screen.querySelectorAll(".qty").forEach(function (el) { | |
el.addEventListener("change", function (e) { | |
e.preventDefault(); | |
// get value of input | |
let qty = parseInt(el.value); | |
// update item_quantity in data | |
let itemIndex = parseInt(el.closest(".item").getAttribute('data-item-index')); | |
let catIndex = parseInt(el.closest(".item").getAttribute('data-cat-index')); | |
data[catIndex].items[itemIndex].item_quantity = qty; | |
// get all the category__table-col-qty of the parent category__table and add them together and display in the category__table-col-qty of the parent category__table | |
let total = 0; | |
el.closest(".category__table").querySelectorAll(".category__table-col-qty .qty").forEach(function (el) { | |
total += parseInt(el.value); | |
}); | |
el.closest(".category__table").querySelector(".category__table-col-qty").textContent = total; | |
updateCategories(); | |
}); | |
}); | |
document.querySelectorAll(".decrement").forEach(function (el) { | |
el.addEventListener("click", function (e) { | |
e.preventDefault(); | |
// get parent .menu and find .toggle__expanded | |
let qty = el.closest(".category__table-col-qty").querySelector(".qty"); | |
if (parseInt(qty.value) > 1) { | |
qty.value = parseInt(qty.value) - 1; | |
// update item_quantity in data | |
let itemIndex = parseInt(el.closest(".item").getAttribute('data-item-index')); | |
let catIndex = parseInt(el.closest(".item").getAttribute('data-cat-index')); | |
data[catIndex].items[itemIndex].item_quantity = qty.value; | |
// get all the category__table-col-qty of the parent category__table and add them together and display in the category__table-col-qty of the parent category__table | |
let total = 0; | |
el.closest(".category__table").querySelectorAll(".category__table-col-qty .qty").forEach(function (el) { | |
total += parseInt(el.value); | |
}); | |
el.closest(".category__table").querySelector(".category__table-col-qty").textContent = total; | |
updateCategories(); | |
} | |
}); | |
}); | |
// document.querySelectorAll(".remove").forEach(function (el) { | |
// el.addEventListener("click", function (e) { | |
// e.preventDefault(); | |
// // get parent .menu and find .toggle__expanded | |
// let item = el.closest(".item"); | |
// // remove item from DOM | |
// // remove item from data | |
// let itemIndex = item.getAttribute('data-item-index'); | |
// let catIndex = item.getAttribute('data-cat-index'); | |
// data[catIndex].items.splice(itemIndex, 1); | |
// item.remove(); | |
// // data[catIndex][Object.keys(data[catIndex])[0]].splice(itemIndex, 1); | |
// updateCategories(); | |
// }); | |
// }); | |
document.querySelectorAll(".item").forEach(function (el) { | |
let startX; | |
let dist; | |
let threshold = 100; // Adjust this value as needed | |
el.addEventListener("touchstart", function (e) { | |
let touch = e.changedTouches[0]; | |
startX = touch.pageX; | |
dist = 0; | |
}); | |
el.addEventListener("touchmove", function (e) { | |
if (startX) { | |
let touch = e.changedTouches[0]; | |
dist = touch.pageX - startX; | |
} | |
}); | |
el.addEventListener("touchend", function (e) { | |
if (dist > threshold) { | |
// Right swipe detected, ask for confirmation before removing the item | |
let confirmDelete = confirm("Are you sure you want to delete this item?"); | |
if (confirmDelete) { | |
let item = el; | |
// Get category index and item index from data attributes | |
let catIndex = item.getAttribute('data-cat-index'); | |
let itemIndex = item.getAttribute('data-item-index'); | |
// Check if the category and item indexes are valid | |
if (catIndex !== null && itemIndex !== null) { | |
// Remove the item from the data structure | |
data[catIndex].items.splice(itemIndex, 1); | |
// Remove the item from the DOM | |
item.remove(); | |
// Update your categories or do any other necessary updates | |
updateCategories(); | |
} else { | |
console.error("Invalid data attributes."); | |
} | |
} | |
} | |
}); | |
}); | |
// // event listener for all .own__item checkboxes | |
// Event listener for all .own__item checkboxes | |
document.querySelectorAll(".own__item").forEach(function (el) { | |
el.addEventListener("change", function (e) { | |
// Get parent .item element | |
let item = el.closest(".item"); | |
if (item) { | |
// Update item_owned in data | |
let itemIndex = parseInt(item.getAttribute('data-item-index')); | |
let catIndex = parseInt(item.getAttribute('data-cat-index')); | |
if (!isNaN(itemIndex) && !isNaN(catIndex)) { | |
data[catIndex].items[itemIndex].item_packed = el.checked ? 1 : 0; | |
// item_acquisition_type, if item_owned is not 1 | |
if(data[catIndex].items[itemIndex].item_owned != 1){ | |
data[catIndex].items[itemIndex].item_acquisition_type = el.checked ? 'Borrowed' : ''; | |
} | |
updateCategories(); | |
} | |
} | |
}); | |
}); | |
// event listener for all .category__table-title .menu .context__menu - to display content menu as popup created by js on click of ⋯ to change the name of the category and also to delete the category and reorder the category starting from 0 | |
// function createContextPopup(catIndex) { | |
// // Create the popup element | |
// let popup = document.createElement('div'); | |
// popup.classList.add('context-popup'); | |
// // Create a close button for the popup | |
// let closeButton = document.createElement('button'); | |
// closeButton.textContent = 'Close'; | |
// closeButton.onclick = () => popup.remove(); | |
// closeButton.style.position = 'absolute'; | |
// closeButton.style.top = '5px'; | |
// closeButton.style.right = '5px'; | |
// // Add options for renaming and deleting | |
// let renameOption = document.createElement('div'); | |
// //add className = "context__menu-rename" | |
// renameOption.classList.add('context__menu-rename'); | |
// renameOption.textContent = 'Rename Category'; | |
// renameOption.onclick = () => { | |
// renameCategory(catIndex); | |
// popup.remove(); // Close the popup after action | |
// }; | |
// let deleteOption = document.createElement('div'); | |
// //add className = "context__menu-delete" | |
// deleteOption.classList.add('context__menu-delete'); | |
// deleteOption.textContent = 'Delete Category'; | |
// deleteOption.onclick = () => { | |
// deleteCategory(catIndex); | |
// popup.remove(); // Close the popup after action | |
// }; | |
// // Append options and close button to the popup | |
// popup.appendChild(closeButton); | |
// popup.appendChild(renameOption); | |
// popup.appendChild(deleteOption); | |
// // Append the popup to the body | |
// document.body.appendChild(popup); | |
// // Position the popup (adjust as needed for your layout) | |
// popup.style.left = event.clientX + 'px'; | |
// popup.style.top = event.clientY + 'px'; | |
// } | |
// function renameCategory(catIndex) { | |
// let newName = prompt("Enter new category name:"); | |
// if (newName) { | |
// // Update the category name in the data array | |
// // let categoryName = Object.keys(data[catIndex])[0]; | |
// // data[catIndex][newName] = data[catIndex][categoryName]; | |
// // delete data[catIndex][categoryName]; | |
// // updateCategories(); // Re-render categories | |
// // updateCategories(); | |
// if (newName) { | |
// // Update the category name in the data array | |
// data[catIndex].category_name = newName; // Update the category name | |
// updateCategories(); // Re-render categories | |
// } | |
// } | |
// } | |
// function deleteCategory(catIndex) { | |
// if (confirm("Are you sure you want to delete this category?")) { | |
// // Remove the category from the data array | |
// data.splice(catIndex, 1); | |
// updateCategories(); // Re-render categories | |
// } | |
// } | |
// Add event listeners to context menu icons | |
// document.querySelectorAll('.context__menu').forEach((element, index) => { | |
// element.addEventListener('click', (event) => { | |
// event.stopPropagation(); // Prevent the click from closing the popup immediately | |
// createContextPopup(index); | |
// }); | |
// }); | |
// updateGearContainer(); | |
planner.update('packingListItems', data); | |
planner.save(); | |
console.log("planner after update - updateCategories"); | |
console.log(planner); | |
} | |
// function handleCategoryDrop(e) { | |
// e.preventDefault(); | |
// // Find the closest category element from the drop target | |
// let dropTargetCategory = e.target.closest('.category'); | |
// if (!dropTargetCategory) { | |
// alert('Invalid drop target'); | |
// return; // Exit if the drop target is not a category | |
// } | |
// let originData = JSON.parse( e.dataTransfer.getData('text/plain')); | |
// // | |
// let originIndex = parseInt(originData.catIndex); | |
// let targetIndex = parseInt(dropTargetCategory.getAttribute('data-cat-index')); | |
// // Validate indices | |
// if (isNaN(originIndex) || isNaN(targetIndex) || originIndex < 0 || targetIndex < 0 || originIndex >= data.length || targetIndex >= data.length) { | |
// alert('Invalid origin or target index'); | |
// return; // Exit function | |
// } | |
// let temp = data[originIndex]; | |
// data.splice(originIndex, 1); | |
// data.splice(targetIndex, 0, temp); | |
// updateCategories(); | |
// } | |
// function handleItemDrop(e) { | |
// e.preventDefault(); | |
// // Find the closest .item to the event target | |
// let dropTarget = e.target.closest('.item'); | |
// // Exit if the drop target is not an item | |
// if (!dropTarget) { | |
// return; | |
// } | |
// let originData = JSON.parse(e.dataTransfer.getData('text/plain')); | |
// let targetData = { | |
// catIndex: dropTarget.getAttribute('data-cat-index'), | |
// itemIndex: dropTarget.getAttribute('data-item-index') | |
// }; | |
// if (originData.catIndex === targetData.catIndex) { | |
// let items = data[originData.catIndex].items; // Access items directly | |
// let temp = items[originData.itemIndex]; | |
// items.splice(originData.itemIndex, 1); | |
// items.splice(targetData.itemIndex, 0, temp); | |
// } | |
// // if (originData.catIndex === targetData.catIndex) { | |
// // let items = data[originData.catIndex][Object.keys(data[originData.catIndex])[0]]; | |
// // let temp = items[originData.itemIndex]; | |
// // items.splice(originData.itemIndex, 1); | |
// // items.splice(targetData.itemIndex, 0, temp); | |
// // } | |
// updateCategories(); | |
// } | |
// function handleDragStart(e) { | |
// let dragTarget = e.target.closest('.category, .item'); | |
// if (dragTarget) { | |
// let catIndex = dragTarget.getAttribute('data-cat-index'); | |
// let itemIndex = dragTarget.getAttribute('data-item-index'); | |
// // Set different data based on whether it's a category or item | |
// if (dragTarget.classList.contains('category')) { | |
// e.dataTransfer.setData('text/plain', JSON.stringify({ type: 'category', catIndex: catIndex })); | |
// // Set custom drag image for category | |
// // let dragImage = createCustomDragImage(dragTarget.textContent); | |
// // e.dataTransfer.setDragImage(dragImage, 0, 0); | |
// } else if (dragTarget.classList.contains('item')) { | |
// e.dataTransfer.setData('text/plain', JSON.stringify({ type: 'item', catIndex: catIndex, itemIndex: itemIndex })); | |
// // Set custom drag image for item | |
// // let dragImage = createCustomDragImage(dragTarget.textContent); | |
// // e.dataTransfer.setDragImage(dragImage, 0, 0); | |
// } | |
// } | |
// } | |
// function createCustomDragImage(text) { | |
// let dragImage = document.createElement('div'); | |
// dragImage.style.position = 'absolute'; | |
// dragImage.style.top = '-99999px'; // Position off-screen | |
// dragImage.textContent = text; | |
// document.body.appendChild(dragImage); | |
// return dragImage; | |
// } | |
// function handleDrop(e) { | |
// e.preventDefault(); | |
// let data = JSON.parse(e.dataTransfer.getData('text/plain')); | |
// if (data.type === 'category') { | |
// // Handle category drop logic | |
// handleCategoryDrop(e); | |
// } else if (data.type === 'item') { | |
// // Handle item drop logic | |
// handleItemDrop(e); | |
// } | |
// } | |
// document.addEventListener('dragstart', handleDragStart); | |
// document.addEventListener('drop', handleDrop); | |
// document.addEventListener('dragover', function(e) { e.preventDefault(); }); | |
updateCategories(); | |
// document.getElementById('addNewCategory').addEventListener('click', function() { | |
// let newCategoryName = document.getElementById('newCategoryName').value.trim(); | |
// let isGroceryItem = document.getElementById('isGroceryItem').checked; // Get checkbox state | |
// // Check if the category name is empty or already exists | |
// if (!newCategoryName) { | |
// alert("Please enter a category name."); | |
// return; | |
// } | |
// if (data.some(category => category.hasOwnProperty(newCategoryName))) { | |
// alert("This category name already exists. Please choose a different name."); | |
// return; | |
// } | |
// // Add new category to data array | |
// let newCategory = {}; | |
// newCategory.category_name = newCategoryName; | |
// // newCategoryName = newCategoryName; | |
// // newCategory[newCategoryName] = []; // Initialize with an empty array for items | |
// if (isGroceryItem) { | |
// newCategory.type = 'Grocery'; // Add type property for grocery items | |
// } else { | |
// newCategory.type = 'Regular'; // Add type property for regular items | |
// } | |
// newCategory.id = generateUniqueID(); | |
// newCategory.items = []; | |
// data.push(newCategory); | |
// // Clear the input field | |
// document.getElementById('newCategoryName').value = ''; | |
// document.getElementById('isGroceryItem').checked = false; // Reset checkbox | |
// // Update categories display | |
// updateCategories(); | |
// }); | |
// Tab elements | |
const packingListTab = document.querySelector('.wppp__packing-list-tab'); | |
const packingGearTab = document.querySelector('.wppp__packing-gear-tab'); | |
const packingGroceryTab = document.querySelector('.wppp__packing-grocery-tab'); | |
// Panel elements | |
const packingListPanel = document.querySelector('.wppp__packing-list-panel'); | |
const packingGearPanel = document.querySelector('.wppp__packing-gear-panel'); | |
const packingGroceryPanel = document.querySelector('.wppp__packing-grocery-panel'); | |
// Event listener for Packing List tab | |
packingListTab.addEventListener('click', function() { | |
packingListTab.classList.add('active'); | |
packingGearTab.classList.remove('active'); | |
packingGroceryTab.classList.remove('active'); | |
packingListPanel.classList.add('show'); | |
packingGearPanel.classList.remove('show'); | |
packingGroceryPanel.classList.remove('show'); | |
}); | |
// Event listener for Gear To Acquire tab | |
packingGearTab.addEventListener('click', function() { | |
packingGearTab.classList.add('active'); | |
packingListTab.classList.remove('active'); | |
packingGroceryTab.classList.remove('active'); | |
packingGearPanel.classList.add('show'); | |
packingListPanel.classList.remove('show'); | |
packingGroceryPanel.classList.remove('show'); | |
}); | |
// Event listener for Grocery List tab | |
packingGroceryTab.addEventListener('click', function() { | |
packingGroceryTab.classList.add('active'); | |
packingListTab.classList.remove('active'); | |
packingGearTab.classList.remove('active'); | |
packingGroceryPanel.classList.add('show'); | |
packingListPanel.classList.remove('show'); | |
packingGearPanel.classList.remove('show'); | |
}); | |
// Initialize with the Packing List tab active | |
packingListTab.click(); | |
// save | |
screen.querySelector('.save').addEventListener('click', async function(e){ | |
// prevent default | |
e.preventDefault(); | |
// update planner.packingList.packingListItems | |
planner.update('packingListItems', data); | |
// planner.update('') = data; | |
planner.save(); | |
// check if the user is not logged in | |
if(planner.user.loggedin){ | |
// save trip | |
// alert('save trip'); | |
renderTripPlanningPageAfterLogin(approot, planner); | |
}else{ | |
// if so show sign up screen | |
if(!planner.steps.includes('wppd-signup')){ | |
planner.steps.push('wppd-signup'); | |
} | |
planner.save(); | |
await renderSignup(approot, planner); | |
} | |
}); | |
// edit | |
screen.querySelector('.edit').addEventListener('click', async function(e){ | |
// prevent default | |
e.preventDefault(); | |
// update steps | |
if(!planner.steps.includes('edit-trip-planning')){ | |
planner.steps.push('edit-trip-planning'); | |
planner.save(); | |
} | |
await renderEditTripPlanningPage(approot, planner); | |
}); | |
// save and exit | |
// screen.querySelector('.exit').addEventListener('click', async function(e){ | |
// // prevent default | |
// e.preventDefault(); | |
// document.querySelector('.wppd__app-spinner').classList.add('show'); | |
// let formData = new FormData(); | |
// formData.append('action', 'save_trip'); | |
// formData.append('planner', JSON.stringify(planner)); | |
// let xhr = new XMLHttpRequest(); | |
// xhr.open('POST', ajaxURL, true); | |
// xhr.onload = function () { | |
// // hide loading spinner | |
// // remove show class from wppd__app-spinner | |
// document.querySelector('.wppd__app-spinner').classList.remove('show'); | |
// // do something to response | |
// let response = JSON.parse(this.responseText); | |
// if(response){ | |
// showAjaxMessage(screen, response); | |
// setTimeout(function(){ | |
// // update planner | |
// // empty planner.steps array and put 1 | |
// planner.steps = []; | |
// planner.steps.push('1'); | |
// // set plannerData in sessionStorage to empty object | |
// sessionStorage.setItem('plannerData', JSON.stringify({})); | |
// renderInit(approot, planner) | |
// }, 2000); | |
// }else{ | |
// e.preventDefault(); | |
// showMessage(screen, '<p class="error"> Something went wrong </p>'); | |
// } | |
// }; | |
// xhr.send(formData); | |
// // check if redirect is set | |
// }); | |
// back | |
// screen.querySelector('.back').addEventListener('click', async function(){ | |
// // pop last item from planner.steps | |
// planner.steps.pop(); | |
// // get last item from planner.steps | |
// let lastStep = planner.steps[planner.steps.length - 1]; | |
// if(lastStep == 'new-category'){ | |
// await renderNewCategoryScreen(); | |
// } | |
// if(lastStep == '3'){ | |
// await renderThirdScreen(); | |
// } | |
// }); | |
// packing_list | |
// on change [name="packing_list"] input event, get value and update planner.tripTitle | |
// screen.querySelector('[name="packing_list"]').addEventListener('input', function(e){ | |
// let value = e.target.value; | |
// planner.packingList.packingListName = value; | |
// }); | |
console.log("planner in trip planning page"); | |
console.log(planner); | |
} | |
export default renderTripPlanningPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment