updateweb
This commit is contained in:
111
website/assets/js/api-client.js
Normal file
111
website/assets/js/api-client.js
Normal file
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* API Client
|
||||
* Centralized API communication with error handling
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
class APIClient {
|
||||
constructor(baseURL = "") {
|
||||
this.baseURL = baseURL;
|
||||
this.defaultHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
async request(endpoint, options = {}) {
|
||||
const url = `${this.baseURL}${endpoint}`;
|
||||
const config = {
|
||||
...options,
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...options.headers,
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
console.error(`API Error (${endpoint}):`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async get(endpoint, params = {}) {
|
||||
const queryString = new URLSearchParams(params).toString();
|
||||
const url = queryString ? `${endpoint}?${queryString}` : endpoint;
|
||||
return this.request(url, { method: "GET" });
|
||||
}
|
||||
|
||||
async post(endpoint, data = {}) {
|
||||
return this.request(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
async put(endpoint, data = {}) {
|
||||
return this.request(endpoint, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
async delete(endpoint) {
|
||||
return this.request(endpoint, { method: "DELETE" });
|
||||
}
|
||||
|
||||
// Product endpoints
|
||||
async getProducts(params = {}) {
|
||||
return this.get("/api/products", params);
|
||||
}
|
||||
|
||||
async getProduct(id) {
|
||||
return this.get(`/api/products/${id}`);
|
||||
}
|
||||
|
||||
async getCategories() {
|
||||
return this.get("/api/categories");
|
||||
}
|
||||
|
||||
// Menu endpoints
|
||||
async getMenu() {
|
||||
return this.get("/api/menu");
|
||||
}
|
||||
|
||||
// Homepage endpoints
|
||||
async getHomepageSettings() {
|
||||
return this.get("/api/homepage-settings");
|
||||
}
|
||||
}
|
||||
|
||||
// Create global instance
|
||||
window.API = window.API || new APIClient();
|
||||
|
||||
// Helper function for loading states
|
||||
window.withLoading = async function (element, asyncFn) {
|
||||
if (!element) return asyncFn();
|
||||
|
||||
element.classList.add("loading");
|
||||
element.setAttribute("aria-busy", "true");
|
||||
|
||||
try {
|
||||
return await asyncFn();
|
||||
} finally {
|
||||
element.classList.remove("loading");
|
||||
element.setAttribute("aria-busy", "false");
|
||||
}
|
||||
};
|
||||
})();
|
||||
62
website/assets/js/back-button-control.js
Normal file
62
website/assets/js/back-button-control.js
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Back Button Navigation Control - SIMPLIFIED & FIXED
|
||||
*
|
||||
* Problem: History manipulation (replaceState/pushState) changes URL without reloading page
|
||||
* Solution: Let browser handle navigation naturally, only intercept when necessary
|
||||
*
|
||||
* Requirements:
|
||||
* 1. Natural browser back/forward navigation (URL changes = page loads)
|
||||
* 2. Prevent going back past home page
|
||||
* 3. Ensure page is always interactive after navigation
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Configuration
|
||||
const HOME_PAGES = ["/", "/home.html", "/index.html"];
|
||||
const HOME_URL = "/home.html";
|
||||
|
||||
/**
|
||||
* Handle popstate (back/forward button) events
|
||||
* This fires AFTER the browser has already navigated (URL changed)
|
||||
*/
|
||||
function handlePopState(event) {
|
||||
// Get the NEW current path (browser already changed it)
|
||||
const currentPath = window.location.pathname;
|
||||
|
||||
// Ensure page is always interactive after back/forward
|
||||
document.body.classList.remove("page-transitioning");
|
||||
document.body.style.opacity = "1";
|
||||
sessionStorage.removeItem("page-transitioning");
|
||||
|
||||
// If we're on home page after a back navigation
|
||||
// prevent going back further by adding home to history
|
||||
if (HOME_PAGES.includes(currentPath)) {
|
||||
// Use setTimeout to avoid interfering with current popstate
|
||||
setTimeout(() => {
|
||||
window.history.pushState({ page: "home" }, "", HOME_URL);
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent going back past home page
|
||||
* Add an extra entry so back button stays on home
|
||||
*/
|
||||
function preventBackPastHome() {
|
||||
const currentPath = window.location.pathname;
|
||||
if (HOME_PAGES.includes(currentPath)) {
|
||||
// Add an extra home entry
|
||||
window.history.pushState({ page: "home", initial: true }, "", HOME_URL);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize: Add home history entry if on home page
|
||||
preventBackPastHome();
|
||||
|
||||
// Listen for popstate (back/forward button)
|
||||
// NOTE: Browser handles the actual navigation (page reload)
|
||||
// We just ensure interactivity and prevent going back past home
|
||||
window.addEventListener("popstate", handlePopState);
|
||||
})();
|
||||
155
website/assets/js/cart-functions.js
Normal file
155
website/assets/js/cart-functions.js
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Shared Cart and Wishlist Functions
|
||||
* Simple localStorage-based implementation that works on all pages
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Cart Functions
|
||||
window.addToCart = function (productId, name, price, imageurl) {
|
||||
try {
|
||||
const cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
const existingItem = cart.find((item) => item.id === productId);
|
||||
|
||||
if (existingItem) {
|
||||
existingItem.quantity = (existingItem.quantity || 1) + 1;
|
||||
} else {
|
||||
cart.push({
|
||||
id: productId,
|
||||
name,
|
||||
price: parseFloat(price),
|
||||
imageurl,
|
||||
quantity: 1,
|
||||
});
|
||||
}
|
||||
|
||||
localStorage.setItem("cart", JSON.stringify(cart));
|
||||
updateCartBadge();
|
||||
showNotification(`${name} added to cart!`, "success");
|
||||
} catch (e) {
|
||||
console.error("Cart error:", e);
|
||||
showNotification("Added to cart!", "success");
|
||||
}
|
||||
};
|
||||
|
||||
// Wishlist Functions
|
||||
window.addToWishlist = function (productId, name, price, imageurl) {
|
||||
try {
|
||||
const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
|
||||
const exists = wishlist.find((item) => item.id === productId);
|
||||
|
||||
if (!exists) {
|
||||
wishlist.push({
|
||||
id: productId,
|
||||
name,
|
||||
price: parseFloat(price),
|
||||
imageurl,
|
||||
});
|
||||
localStorage.setItem("wishlist", JSON.stringify(wishlist));
|
||||
updateWishlistBadge();
|
||||
showNotification(`${name} added to wishlist!`, "success");
|
||||
} else {
|
||||
showNotification("Already in wishlist!", "info");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Wishlist error:", e);
|
||||
showNotification("Added to wishlist!", "success");
|
||||
}
|
||||
};
|
||||
|
||||
// Update Badge Functions
|
||||
function updateCartBadge() {
|
||||
try {
|
||||
const cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
const badge = document.querySelector(".cart-badge");
|
||||
if (badge) {
|
||||
const total = cart.reduce((sum, item) => sum + (item.quantity || 1), 0);
|
||||
badge.textContent = total;
|
||||
badge.style.display = total > 0 ? "flex" : "none";
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Badge update error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
function updateWishlistBadge() {
|
||||
try {
|
||||
const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
|
||||
const badge = document.querySelector(".wishlist-badge");
|
||||
if (badge) {
|
||||
badge.textContent = wishlist.length;
|
||||
badge.style.display = wishlist.length > 0 ? "flex" : "none";
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Badge update error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Notification Function
|
||||
function showNotification(message, type = "info") {
|
||||
// Remove existing notifications
|
||||
document.querySelectorAll(".cart-notification").forEach((n) => n.remove());
|
||||
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `cart-notification notification-${type}`;
|
||||
notification.textContent = message;
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
right: 20px;
|
||||
background: ${
|
||||
type === "success"
|
||||
? "#10b981"
|
||||
: type === "error"
|
||||
? "#ef4444"
|
||||
: "#3b82f6"
|
||||
};
|
||||
color: white;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
z-index: 10000;
|
||||
animation: slideInFromRight 0.3s ease;
|
||||
`;
|
||||
|
||||
// Add animation styles if not already present
|
||||
if (!document.getElementById("notification-animations")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "notification-animations";
|
||||
style.textContent = `
|
||||
@keyframes slideInFromRight {
|
||||
from { transform: translateX(400px); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
@keyframes slideOutToRight {
|
||||
from { transform: translateX(0); opacity: 1; }
|
||||
to { transform: translateX(400px); opacity: 0; }
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
setTimeout(() => {
|
||||
notification.style.animation = "slideOutToRight 0.3s ease";
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Initialize badges on page load
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
updateCartBadge();
|
||||
updateWishlistBadge();
|
||||
});
|
||||
} else {
|
||||
updateCartBadge();
|
||||
updateWishlistBadge();
|
||||
}
|
||||
|
||||
// Expose update functions globally
|
||||
window.updateCartBadge = updateCartBadge;
|
||||
window.updateWishlistBadge = updateWishlistBadge;
|
||||
})();
|
||||
@@ -1,378 +1,319 @@
|
||||
// Sky Art Shop - Shopping Cart Functions
|
||||
|
||||
// Add item to cart
|
||||
function addToCart(id, name, price, imageUrl = null) {
|
||||
// Get existing cart from localStorage
|
||||
let cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
|
||||
// Check if item already exists
|
||||
const existingItem = cart.find((item) => item.id === id);
|
||||
|
||||
if (existingItem) {
|
||||
existingItem.quantity++;
|
||||
// Update imageUrl if it was null before
|
||||
if (!existingItem.imageUrl && imageUrl) {
|
||||
existingItem.imageUrl = imageUrl;
|
||||
}
|
||||
} else {
|
||||
cart.push({ id, name, price, quantity: 1, imageUrl });
|
||||
}
|
||||
|
||||
// Save cart
|
||||
localStorage.setItem("cart", JSON.stringify(cart));
|
||||
console.log("Cart updated:", cart);
|
||||
|
||||
// Show confirmation
|
||||
showCartNotification(`${name} added to cart!`);
|
||||
updateCartCount();
|
||||
}
|
||||
|
||||
// Remove item from cart
|
||||
function removeFromCart(id) {
|
||||
let cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
cart = cart.filter((item) => item.id !== id);
|
||||
localStorage.setItem("cart", JSON.stringify(cart));
|
||||
updateCartCount();
|
||||
}
|
||||
|
||||
// Update cart item quantity
|
||||
function updateCartQuantity(id, quantity) {
|
||||
let cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
const item = cart.find((item) => item.id === id);
|
||||
if (item) {
|
||||
item.quantity = quantity;
|
||||
if (quantity <= 0) {
|
||||
cart = cart.filter((item) => item.id !== id);
|
||||
}
|
||||
}
|
||||
localStorage.setItem("cart", JSON.stringify(cart));
|
||||
updateCartCount();
|
||||
}
|
||||
|
||||
// Get cart items
|
||||
function getCart() {
|
||||
return JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
}
|
||||
|
||||
// Get cart total
|
||||
function getCartTotal() {
|
||||
const cart = getCart();
|
||||
return cart.reduce((total, item) => total + item.price * item.quantity, 0);
|
||||
}
|
||||
|
||||
// Update cart count badge
|
||||
function updateCartCount() {
|
||||
const cart = getCart();
|
||||
const count = cart.reduce((total, item) => total + item.quantity, 0);
|
||||
|
||||
// Update old badge (if exists)
|
||||
const badge = document.getElementById("cart-count");
|
||||
if (badge) {
|
||||
badge.textContent = count;
|
||||
badge.style.display = count > 0 ? "inline" : "none";
|
||||
}
|
||||
|
||||
// Update navbar cart badge
|
||||
const navCartBadge = document.querySelector("#cartBtn .badge");
|
||||
if (navCartBadge) {
|
||||
navCartBadge.textContent = count;
|
||||
navCartBadge.style.display = count > 0 ? "block" : "none";
|
||||
}
|
||||
}
|
||||
|
||||
// Show cart notification
|
||||
function showCartNotification(message) {
|
||||
const notification = document.createElement("div");
|
||||
notification.className = "cart-notification";
|
||||
notification.textContent = message;
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
right: 20px;
|
||||
background: #4CAF50;
|
||||
color: white;
|
||||
padding: 15px 25px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.2);
|
||||
z-index: 10000;
|
||||
animation: slideInFromTop 0.3s ease;
|
||||
`;
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
setTimeout(() => {
|
||||
notification.style.animation = "slideOut 0.3s ease";
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Clear entire cart
|
||||
function clearCart() {
|
||||
localStorage.removeItem("cart");
|
||||
updateCartCount();
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Wishlist Functions
|
||||
// ====================================
|
||||
|
||||
// Add item to wishlist
|
||||
function addToWishlist(id, name, price, imageUrl) {
|
||||
let wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
|
||||
|
||||
const existingItem = wishlist.find((item) => item.id === id);
|
||||
|
||||
if (existingItem) {
|
||||
showWishlistNotification(`${name} is already in your wishlist!`);
|
||||
return;
|
||||
}
|
||||
|
||||
wishlist.push({ id, name, price, imageUrl });
|
||||
localStorage.setItem("wishlist", JSON.stringify(wishlist));
|
||||
console.log("Wishlist updated:", wishlist);
|
||||
|
||||
showWishlistNotification(`${name} added to wishlist!`);
|
||||
updateWishlistCount();
|
||||
}
|
||||
|
||||
// Remove item from wishlist
|
||||
function removeFromWishlist(id) {
|
||||
let wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
|
||||
wishlist = wishlist.filter((item) => item.id !== id);
|
||||
localStorage.setItem("wishlist", JSON.stringify(wishlist));
|
||||
updateWishlistCount();
|
||||
}
|
||||
|
||||
// Get wishlist items
|
||||
function getWishlist() {
|
||||
return JSON.parse(localStorage.getItem("wishlist") || "[]");
|
||||
}
|
||||
|
||||
// Update wishlist count badge
|
||||
function updateWishlistCount() {
|
||||
const wishlist = getWishlist();
|
||||
const count = wishlist.length;
|
||||
|
||||
const navWishlistBadge = document.querySelector("#wishlistBtn .badge");
|
||||
const wishlistIcon = document.querySelector("#wishlistBtn i");
|
||||
|
||||
if (navWishlistBadge) {
|
||||
navWishlistBadge.textContent = count;
|
||||
navWishlistBadge.style.display = count > 0 ? "block" : "none";
|
||||
}
|
||||
|
||||
// Change heart icon based on wishlist status
|
||||
if (wishlistIcon) {
|
||||
if (count > 0) {
|
||||
wishlistIcon.className = "bi bi-heart-fill";
|
||||
wishlistIcon.style.color = "#e74c3c";
|
||||
} else {
|
||||
wishlistIcon.className = "bi bi-heart";
|
||||
wishlistIcon.style.color = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show wishlist notification
|
||||
function showWishlistNotification(message) {
|
||||
const notification = document.createElement("div");
|
||||
notification.className = "wishlist-notification";
|
||||
notification.textContent = message;
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
right: 20px;
|
||||
background: #E91E63;
|
||||
color: white;
|
||||
padding: 15px 25px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.2);
|
||||
z-index: 10000;
|
||||
animation: slideInFromTop 0.3s ease;
|
||||
`;
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
setTimeout(() => {
|
||||
notification.style.animation = "slideOut 0.3s ease";
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Clear entire wishlist
|
||||
function clearWishlist() {
|
||||
localStorage.removeItem("wishlist");
|
||||
updateWishlistCount();
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Dropdown Functions
|
||||
// ====================================
|
||||
// Render cart dropdown
|
||||
function renderCartDropdown() {
|
||||
const cart = getCart();
|
||||
const cartItems = document.getElementById("cartItems");
|
||||
const cartTotal = document.getElementById("cartTotal");
|
||||
|
||||
if (!cartItems) return;
|
||||
|
||||
if (cart.length === 0) {
|
||||
cartItems.innerHTML = '<p class="empty-message">Your cart is empty</p>';
|
||||
if (cartTotal) cartTotal.textContent = "$0.00";
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Rendering cart:", cart);
|
||||
|
||||
cartItems.innerHTML = cart
|
||||
.map((item) => {
|
||||
const imgSrc = item.imageUrl || "/assets/images/placeholder.jpg";
|
||||
console.log("Cart item image URL:", imgSrc);
|
||||
return `
|
||||
<div class="dropdown-item">
|
||||
<img src="${imgSrc}" alt="${
|
||||
item.name
|
||||
}" class="dropdown-item-image" onerror="this.src='/assets/images/placeholder.jpg'">
|
||||
<div class="dropdown-item-info">
|
||||
<div class="dropdown-item-name">${item.name}</div>
|
||||
<div class="dropdown-item-details">
|
||||
<span class="dropdown-item-quantity">Qty: ${
|
||||
item.quantity
|
||||
}</span>
|
||||
<span class="dropdown-item-price">$${(
|
||||
item.price * item.quantity
|
||||
).toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="dropdown-item-remove" onclick="removeFromCartDropdown('${
|
||||
item.id
|
||||
}')">
|
||||
<i class="bi bi-x"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
if (cartTotal) {
|
||||
const total = getCartTotal();
|
||||
cartTotal.textContent = `$${total.toFixed(2)}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Render wishlist dropdown
|
||||
function renderWishlistDropdown() {
|
||||
const wishlist = getWishlist();
|
||||
const wishlistItems = document.getElementById("wishlistItems");
|
||||
|
||||
if (!wishlistItems) return;
|
||||
|
||||
if (wishlist.length === 0) {
|
||||
wishlistItems.innerHTML =
|
||||
'<p class="empty-message">Your wishlist is empty</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Rendering wishlist:", wishlist);
|
||||
|
||||
wishlistItems.innerHTML = wishlist
|
||||
.map((item) => {
|
||||
const imgSrc = item.imageUrl || "/assets/images/placeholder.jpg";
|
||||
console.log("Wishlist item image URL:", imgSrc);
|
||||
return `
|
||||
<div class="dropdown-item">
|
||||
<img src="${imgSrc}" alt="${
|
||||
item.name
|
||||
}" class="dropdown-item-image" onerror="this.src='/assets/images/placeholder.jpg'">
|
||||
<div class="dropdown-item-info">
|
||||
<div class="dropdown-item-name">${item.name}</div>
|
||||
<div class="dropdown-item-details">
|
||||
<span class="dropdown-item-price">$${item.price.toFixed(
|
||||
2
|
||||
)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="dropdown-item-remove" onclick="removeFromWishlistDropdown('${
|
||||
item.id
|
||||
}')">
|
||||
<i class="bi bi-x"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
// Remove from cart via dropdown
|
||||
function removeFromCartDropdown(id) {
|
||||
removeFromCart(id);
|
||||
renderCartDropdown();
|
||||
updateCartCount();
|
||||
}
|
||||
|
||||
// Remove from wishlist via dropdown
|
||||
function removeFromWishlistDropdown(id) {
|
||||
removeFromWishlist(id);
|
||||
renderWishlistDropdown();
|
||||
updateWishlistCount();
|
||||
}
|
||||
|
||||
// Toggle dropdown visibility
|
||||
function toggleDropdown(dropdownId) {
|
||||
const dropdown = document.getElementById(dropdownId);
|
||||
if (!dropdown) return;
|
||||
|
||||
// Close other dropdowns
|
||||
document.querySelectorAll(".icon-dropdown").forEach((d) => {
|
||||
if (d.id !== dropdownId) {
|
||||
d.classList.remove("show");
|
||||
}
|
||||
});
|
||||
|
||||
dropdown.classList.toggle("show");
|
||||
|
||||
// Render content when opening
|
||||
if (dropdown.classList.contains("show")) {
|
||||
if (dropdownId === "cartDropdown") {
|
||||
renderCartDropdown();
|
||||
} else if (dropdownId === "wishlistDropdown") {
|
||||
renderWishlistDropdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close cart/wishlist dropdowns when clicking outside
|
||||
document.addEventListener("click", function (e) {
|
||||
if (
|
||||
!e.target.closest(".dropdown-container") &&
|
||||
!e.target.closest(".nav-toggle")
|
||||
) {
|
||||
document.querySelectorAll(".icon-dropdown").forEach((d) => {
|
||||
d.classList.remove("show");
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize cart and wishlist count on page load
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
updateCartCount();
|
||||
updateWishlistCount();
|
||||
|
||||
// Add click handlers for dropdown toggles
|
||||
const cartBtn = document.getElementById("cartBtn");
|
||||
const wishlistBtn = document.getElementById("wishlistBtn");
|
||||
|
||||
if (cartBtn) {
|
||||
cartBtn.addEventListener("click", function (e) {
|
||||
e.preventDefault();
|
||||
toggleDropdown("cartDropdown");
|
||||
});
|
||||
}
|
||||
|
||||
if (wishlistBtn) {
|
||||
wishlistBtn.addEventListener("click", function (e) {
|
||||
e.preventDefault();
|
||||
toggleDropdown("wishlistDropdown");
|
||||
});
|
||||
}
|
||||
});
|
||||
/**
|
||||
* Shopping Cart Component
|
||||
* Handles cart dropdown, updates, and interactions
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
class ShoppingCart {
|
||||
constructor() {
|
||||
this.cartToggle = document.getElementById("cartToggle");
|
||||
this.cartPanel = document.getElementById("cartPanel");
|
||||
this.cartContent = document.getElementById("cartContent");
|
||||
this.cartClose = document.getElementById("cartClose");
|
||||
this.isOpen = false;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupEventListeners();
|
||||
this.render();
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
if (this.cartToggle) {
|
||||
this.cartToggle.addEventListener("click", () => this.toggle());
|
||||
}
|
||||
|
||||
if (this.cartClose) {
|
||||
this.cartClose.addEventListener("click", () => this.close());
|
||||
}
|
||||
|
||||
// Close when clicking outside
|
||||
document.addEventListener("click", (e) => {
|
||||
if (this.isOpen && !e.target.closest(".cart-dropdown-wrapper")) {
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for cart updates
|
||||
window.addEventListener("cart-updated", () => this.render());
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.isOpen ? this.close() : this.open();
|
||||
}
|
||||
|
||||
open() {
|
||||
if (this.cartPanel) {
|
||||
this.cartPanel.classList.add("active");
|
||||
this.cartPanel.setAttribute("aria-hidden", "false");
|
||||
this.isOpen = true;
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.cartPanel) {
|
||||
this.cartPanel.classList.remove("active");
|
||||
this.cartPanel.setAttribute("aria-hidden", "true");
|
||||
this.isOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.cartContent) return;
|
||||
|
||||
const cart = window.AppState.cart;
|
||||
|
||||
if (cart.length === 0) {
|
||||
this.cartContent.innerHTML =
|
||||
'<p class="empty-state">Your cart is empty</p>';
|
||||
this.updateFooter(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const html = cart.map((item) => this.renderCartItem(item)).join("");
|
||||
this.cartContent.innerHTML = html;
|
||||
|
||||
// Add event listeners to cart items
|
||||
this.setupCartItemListeners();
|
||||
|
||||
// Update footer with total
|
||||
this.updateFooter(window.AppState.getCartTotal());
|
||||
}
|
||||
|
||||
renderCartItem(item) {
|
||||
const imageUrl =
|
||||
item.imageUrl || item.image_url || "/assets/images/placeholder.jpg";
|
||||
const title = window.Utils.escapeHtml(
|
||||
item.title || item.name || "Product"
|
||||
);
|
||||
const price = window.Utils.formatCurrency(item.price || 0);
|
||||
const subtotal = window.Utils.formatCurrency(
|
||||
(item.price || 0) * item.quantity
|
||||
);
|
||||
|
||||
return `
|
||||
<div class="cart-item" data-id="${item.id}">
|
||||
<img src="${imageUrl}" alt="${title}" class="cart-item-image" loading="lazy">
|
||||
<div class="cart-item-details">
|
||||
<h4 class="cart-item-title">${title}</h4>
|
||||
<p class="cart-item-price">${price}</p>
|
||||
<div class="cart-item-quantity">
|
||||
<button class="quantity-btn quantity-minus" data-id="${item.id}" aria-label="Decrease quantity">
|
||||
<i class="bi bi-dash"></i>
|
||||
</button>
|
||||
<span class="quantity-value">${item.quantity}</span>
|
||||
<button class="quantity-btn quantity-plus" data-id="${item.id}" aria-label="Increase quantity">
|
||||
<i class="bi bi-plus"></i>
|
||||
</button>
|
||||
</div>
|
||||
<p class="cart-item-subtotal">${subtotal}</p>
|
||||
</div>
|
||||
<button class="cart-item-remove" data-id="${item.id}" aria-label="Remove from cart">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
setupCartItemListeners() {
|
||||
// Remove buttons
|
||||
this.cartContent.querySelectorAll(".cart-item-remove").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
window.AppState.removeFromCart(id);
|
||||
this.render();
|
||||
});
|
||||
});
|
||||
|
||||
// Quantity buttons
|
||||
this.cartContent.querySelectorAll(".quantity-minus").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
const item = window.AppState.cart.find((item) => item.id === id);
|
||||
if (item && item.quantity > 1) {
|
||||
window.AppState.updateCartQuantity(id, item.quantity - 1);
|
||||
this.render();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
this.cartContent.querySelectorAll(".quantity-plus").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
const item = window.AppState.cart.find((item) => item.id === id);
|
||||
if (item) {
|
||||
window.AppState.updateCartQuantity(id, item.quantity + 1);
|
||||
this.render();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
updateFooter(total) {
|
||||
const footer = this.cartPanel?.querySelector(".dropdown-foot");
|
||||
if (!footer) return;
|
||||
|
||||
if (total === null) {
|
||||
footer.innerHTML =
|
||||
'<a href="/shop" class="btn-outline">Continue Shopping</a>';
|
||||
} else {
|
||||
footer.innerHTML = `
|
||||
<div class="cart-total">
|
||||
<span>Total:</span>
|
||||
<strong>${window.Utils.formatCurrency(total)}</strong>
|
||||
</div>
|
||||
<a href="/shop" class="btn-text">Continue Shopping</a>
|
||||
<button class="btn-primary-full" onclick="alert('Checkout coming soon!')">
|
||||
Proceed to Checkout
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wishlist Component
|
||||
class Wishlist {
|
||||
constructor() {
|
||||
this.wishlistToggle = document.getElementById("wishlistToggle");
|
||||
this.wishlistPanel = document.getElementById("wishlistPanel");
|
||||
this.wishlistContent = document.getElementById("wishlistContent");
|
||||
this.wishlistClose = document.getElementById("wishlistClose");
|
||||
this.isOpen = false;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupEventListeners();
|
||||
this.render();
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
if (this.wishlistToggle) {
|
||||
this.wishlistToggle.addEventListener("click", () => this.toggle());
|
||||
}
|
||||
|
||||
if (this.wishlistClose) {
|
||||
this.wishlistClose.addEventListener("click", () => this.close());
|
||||
}
|
||||
|
||||
// Close when clicking outside
|
||||
document.addEventListener("click", (e) => {
|
||||
if (this.isOpen && !e.target.closest(".wishlist-dropdown-wrapper")) {
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for wishlist updates
|
||||
window.addEventListener("wishlist-updated", () => this.render());
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.isOpen ? this.close() : this.open();
|
||||
}
|
||||
|
||||
open() {
|
||||
if (this.wishlistPanel) {
|
||||
this.wishlistPanel.classList.add("active");
|
||||
this.wishlistPanel.setAttribute("aria-hidden", "false");
|
||||
this.isOpen = true;
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.wishlistPanel) {
|
||||
this.wishlistPanel.classList.remove("active");
|
||||
this.wishlistPanel.setAttribute("aria-hidden", "true");
|
||||
this.isOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.wishlistContent) return;
|
||||
|
||||
const wishlist = window.AppState.wishlist;
|
||||
|
||||
if (wishlist.length === 0) {
|
||||
this.wishlistContent.innerHTML =
|
||||
'<p class="empty-state">Your wishlist is empty</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
const html = wishlist
|
||||
.map((item) => this.renderWishlistItem(item))
|
||||
.join("");
|
||||
this.wishlistContent.innerHTML = html;
|
||||
|
||||
// Add event listeners
|
||||
this.setupWishlistItemListeners();
|
||||
}
|
||||
|
||||
renderWishlistItem(item) {
|
||||
const imageUrl =
|
||||
item.imageUrl || item.image_url || "/assets/images/placeholder.jpg";
|
||||
const title = window.Utils.escapeHtml(
|
||||
item.title || item.name || "Product"
|
||||
);
|
||||
const price = window.Utils.formatCurrency(item.price || 0);
|
||||
|
||||
return `
|
||||
<div class="wishlist-item" data-id="${item.id}">
|
||||
<img src="${imageUrl}" alt="${title}" class="wishlist-item-image" loading="lazy">
|
||||
<div class="wishlist-item-details">
|
||||
<h4 class="wishlist-item-title">${title}</h4>
|
||||
<p class="wishlist-item-price">${price}</p>
|
||||
<button class="btn-add-to-cart" data-id="${item.id}">Add to Cart</button>
|
||||
</div>
|
||||
<button class="wishlist-item-remove" data-id="${item.id}" aria-label="Remove from wishlist">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
setupWishlistItemListeners() {
|
||||
// Remove buttons
|
||||
this.wishlistContent
|
||||
.querySelectorAll(".wishlist-item-remove")
|
||||
.forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
window.AppState.removeFromWishlist(id);
|
||||
this.render();
|
||||
});
|
||||
});
|
||||
|
||||
// Add to cart buttons
|
||||
this.wishlistContent
|
||||
.querySelectorAll(".btn-add-to-cart")
|
||||
.forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
const item = window.AppState.wishlist.find(
|
||||
(item) => item.id === id
|
||||
);
|
||||
if (item) {
|
||||
window.AppState.addToCart(item);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize when DOM is ready
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
new ShoppingCart();
|
||||
new Wishlist();
|
||||
});
|
||||
} else {
|
||||
new ShoppingCart();
|
||||
new Wishlist();
|
||||
}
|
||||
})();
|
||||
|
||||
72
website/assets/js/lazy-load.js
Normal file
72
website/assets/js/lazy-load.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Lazy Loading Images Script
|
||||
* Optimizes image loading for better performance
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Check for Intersection Observer support
|
||||
if (!("IntersectionObserver" in window)) {
|
||||
// Fallback: load all images immediately
|
||||
document.querySelectorAll('img[loading="lazy"]').forEach((img) => {
|
||||
if (img.dataset.src) {
|
||||
img.src = img.dataset.src;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Configure intersection observer
|
||||
const imageObserver = new IntersectionObserver(
|
||||
(entries, observer) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
|
||||
// Load the image
|
||||
if (img.dataset.src) {
|
||||
img.src = img.dataset.src;
|
||||
img.removeAttribute("data-src");
|
||||
}
|
||||
|
||||
// Optional: load srcset
|
||||
if (img.dataset.srcset) {
|
||||
img.srcset = img.dataset.srcset;
|
||||
img.removeAttribute("data-srcset");
|
||||
}
|
||||
|
||||
// Add loaded class for fade-in effect
|
||||
img.classList.add("loaded");
|
||||
|
||||
// Stop observing this image
|
||||
observer.unobserve(img);
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
// Start loading when image is 50px from viewport
|
||||
rootMargin: "50px 0px",
|
||||
threshold: 0.01,
|
||||
}
|
||||
);
|
||||
|
||||
// Observe all lazy images
|
||||
const lazyImages = document.querySelectorAll('img[loading="lazy"]');
|
||||
lazyImages.forEach((img) => imageObserver.observe(img));
|
||||
|
||||
// Add CSS for fade-in effect if not already present
|
||||
if (!document.getElementById("lazy-load-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "lazy-load-styles";
|
||||
style.textContent = `
|
||||
img[loading="lazy"] {
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease-in-out;
|
||||
}
|
||||
img[loading="lazy"].loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
})();
|
||||
@@ -1,427 +1,350 @@
|
||||
// Sky Art Shop - Main JavaScript File
|
||||
|
||||
// ====================================
|
||||
// Mobile Navigation Toggle
|
||||
// ====================================
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
const navToggle = document.querySelector(".nav-toggle");
|
||||
const navMenu = document.querySelector("#navDropdown");
|
||||
|
||||
if (navToggle && navMenu) {
|
||||
// Hover to open dropdown
|
||||
navToggle.addEventListener("mouseenter", function () {
|
||||
navMenu.classList.add("active");
|
||||
this.setAttribute("aria-expanded", "true");
|
||||
|
||||
const spans = this.querySelectorAll("span");
|
||||
spans[0].style.transform = "rotate(45deg) translate(7px, 7px)";
|
||||
spans[1].style.opacity = "0";
|
||||
spans[2].style.transform = "rotate(-45deg) translate(7px, -7px)";
|
||||
});
|
||||
|
||||
// Keep dropdown open when hovering over it
|
||||
navMenu.addEventListener("mouseenter", function () {
|
||||
this.classList.add("active");
|
||||
});
|
||||
|
||||
// Close when mouse leaves both hamburger and dropdown
|
||||
navToggle.addEventListener("mouseleave", function (e) {
|
||||
// Delay closing to allow moving to dropdown
|
||||
setTimeout(() => {
|
||||
if (!navMenu.matches(":hover") && !navToggle.matches(":hover")) {
|
||||
navMenu.classList.remove("active");
|
||||
navToggle.setAttribute("aria-expanded", "false");
|
||||
|
||||
const spans = navToggle.querySelectorAll("span");
|
||||
spans[0].style.transform = "none";
|
||||
spans[1].style.opacity = "1";
|
||||
spans[2].style.transform = "none";
|
||||
}
|
||||
}, 200);
|
||||
});
|
||||
|
||||
navMenu.addEventListener("mouseleave", function () {
|
||||
setTimeout(() => {
|
||||
if (!navMenu.matches(":hover") && !navToggle.matches(":hover")) {
|
||||
navMenu.classList.remove("active");
|
||||
navToggle.setAttribute("aria-expanded", "false");
|
||||
|
||||
const spans = navToggle.querySelectorAll("span");
|
||||
spans[0].style.transform = "none";
|
||||
spans[1].style.opacity = "1";
|
||||
spans[2].style.transform = "none";
|
||||
}
|
||||
}, 200);
|
||||
});
|
||||
|
||||
// Click to toggle (for mobile/touch)
|
||||
navToggle.addEventListener("click", function (e) {
|
||||
e.stopPropagation();
|
||||
const isActive = navMenu.classList.toggle("active");
|
||||
this.setAttribute("aria-expanded", isActive ? "true" : "false");
|
||||
|
||||
// Animate hamburger menu
|
||||
const spans = this.querySelectorAll("span");
|
||||
if (isActive) {
|
||||
spans[0].style.transform = "rotate(45deg) translate(7px, 7px)";
|
||||
spans[1].style.opacity = "0";
|
||||
spans[2].style.transform = "rotate(-45deg) translate(7px, -7px)";
|
||||
} else {
|
||||
spans[0].style.transform = "none";
|
||||
spans[1].style.opacity = "1";
|
||||
spans[2].style.transform = "none";
|
||||
}
|
||||
});
|
||||
|
||||
// Close dropdown when clicking on a link
|
||||
const dropdownLinks = navMenu.querySelectorAll("a");
|
||||
dropdownLinks.forEach((link) => {
|
||||
link.addEventListener("click", function () {
|
||||
navMenu.classList.remove("active");
|
||||
navToggle.setAttribute("aria-expanded", "false");
|
||||
const spans = navToggle.querySelectorAll("span");
|
||||
spans[0].style.transform = "none";
|
||||
spans[1].style.opacity = "1";
|
||||
spans[2].style.transform = "none";
|
||||
});
|
||||
});
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
document.addEventListener("click", function (event) {
|
||||
// Don't close if clicking on cart/wishlist dropdowns
|
||||
if (
|
||||
event.target.closest(".dropdown-container") ||
|
||||
event.target.closest(".icon-dropdown")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isClickInside =
|
||||
navToggle.contains(event.target) || navMenu.contains(event.target);
|
||||
if (!isClickInside && navMenu.classList.contains("active")) {
|
||||
navMenu.classList.remove("active");
|
||||
navToggle.setAttribute("aria-expanded", "false");
|
||||
const spans = navToggle.querySelectorAll("span");
|
||||
spans[0].style.transform = "none";
|
||||
spans[1].style.opacity = "1";
|
||||
spans[2].style.transform = "none";
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ====================================
|
||||
// Smooth Scrolling for Anchor Links
|
||||
// ====================================
|
||||
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
|
||||
anchor.addEventListener("click", function (e) {
|
||||
const href = this.getAttribute("href");
|
||||
if (href !== "#" && href !== "#instagram" && href !== "#wishlist") {
|
||||
e.preventDefault();
|
||||
const target = document.querySelector(href);
|
||||
if (target) {
|
||||
target.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "start",
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ====================================
|
||||
// Shop Page Filtering
|
||||
// ====================================
|
||||
const categoryFilter = document.getElementById("category-filter");
|
||||
const sortFilter = document.getElementById("sort-filter");
|
||||
|
||||
if (categoryFilter) {
|
||||
categoryFilter.addEventListener("change", function () {
|
||||
const selectedCategory = this.value;
|
||||
const productCards = document.querySelectorAll(".product-card");
|
||||
|
||||
productCards.forEach((card) => {
|
||||
if (selectedCategory === "all") {
|
||||
card.style.display = "block";
|
||||
} else {
|
||||
const cardCategory = card.getAttribute("data-category");
|
||||
if (cardCategory === selectedCategory) {
|
||||
card.style.display = "block";
|
||||
} else {
|
||||
card.style.display = "none";
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (sortFilter) {
|
||||
sortFilter.addEventListener("change", function () {
|
||||
const sortValue = this.value;
|
||||
const productsGrid = document.querySelector(".products-grid");
|
||||
const productCards = Array.from(document.querySelectorAll(".product-card"));
|
||||
|
||||
if (sortValue === "price-low") {
|
||||
productCards.sort((a, b) => {
|
||||
const priceA = parseFloat(
|
||||
a.querySelector(".price").textContent.replace("$", "")
|
||||
);
|
||||
const priceB = parseFloat(
|
||||
b.querySelector(".price").textContent.replace("$", "")
|
||||
);
|
||||
return priceA - priceB;
|
||||
});
|
||||
} else if (sortValue === "price-high") {
|
||||
productCards.sort((a, b) => {
|
||||
const priceA = parseFloat(
|
||||
a.querySelector(".price").textContent.replace("$", "")
|
||||
);
|
||||
const priceB = parseFloat(
|
||||
b.querySelector(".price").textContent.replace("$", "")
|
||||
);
|
||||
return priceB - priceA;
|
||||
});
|
||||
}
|
||||
|
||||
// Re-append sorted cards
|
||||
productCards.forEach((card) => {
|
||||
productsGrid.appendChild(card);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Add to Cart Functionality (Basic)
|
||||
// ====================================
|
||||
document.querySelectorAll(".product-card .btn").forEach((button) => {
|
||||
button.addEventListener("click", function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
// Get product details
|
||||
const productCard = this.closest(".product-card");
|
||||
const productName = productCard.querySelector("h3").textContent;
|
||||
const productPrice = productCard.querySelector(".price").textContent;
|
||||
|
||||
// Show notification
|
||||
showNotification(`${productName} added to cart!`);
|
||||
|
||||
// You can expand this to actually store cart items
|
||||
// For example, using localStorage or sending to a server
|
||||
});
|
||||
});
|
||||
|
||||
// ====================================
|
||||
// Contact Form Handling
|
||||
// ====================================
|
||||
const contactForm = document.getElementById("contactForm");
|
||||
|
||||
if (contactForm) {
|
||||
contactForm.addEventListener("submit", function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
// Get form values
|
||||
const name = document.getElementById("name").value;
|
||||
const email = document.getElementById("email").value;
|
||||
const phone = document.getElementById("phone").value;
|
||||
const subject = document.getElementById("subject").value;
|
||||
const message = document.getElementById("message").value;
|
||||
|
||||
// Basic validation
|
||||
if (!name || !email || !subject || !message) {
|
||||
showNotification("Please fill in all required fields!", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
showNotification("Please enter a valid email address!", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Here you would typically send the form data to a server
|
||||
// For now, we'll just show a success message
|
||||
showNotification(
|
||||
"Thank you! Your message has been sent. We'll get back to you soon.",
|
||||
"success"
|
||||
);
|
||||
|
||||
// Reset form
|
||||
contactForm.reset();
|
||||
});
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Notification System
|
||||
// ====================================
|
||||
function showNotification(message, type = "success") {
|
||||
// Create notification element
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.textContent = message;
|
||||
|
||||
// Style the notification
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
top: 100px;
|
||||
right: 20px;
|
||||
background-color: ${type === "success" ? "#4CAF50" : "#F44336"};
|
||||
color: white;
|
||||
padding: 15px 25px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
z-index: 10000;
|
||||
animation: slideIn 0.3s ease-out;
|
||||
`;
|
||||
|
||||
// Add animation
|
||||
const style = document.createElement("style");
|
||||
style.textContent = `
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes slideOut {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
// Add to page
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// Remove after 3 seconds
|
||||
setTimeout(() => {
|
||||
notification.style.animation = "slideOut 0.3s ease-out";
|
||||
setTimeout(() => {
|
||||
notification.remove();
|
||||
}, 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Image Lazy Loading (Optional Enhancement)
|
||||
// ====================================
|
||||
if ("IntersectionObserver" in window) {
|
||||
const imageObserver = new IntersectionObserver((entries, observer) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
img.src = img.dataset.src || img.src;
|
||||
img.classList.add("loaded");
|
||||
observer.unobserve(img);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("img").forEach((img) => {
|
||||
imageObserver.observe(img);
|
||||
});
|
||||
}
|
||||
|
||||
// ====================================
|
||||
// Scroll to Top Button
|
||||
// ====================================
|
||||
function createScrollToTopButton() {
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "↑";
|
||||
button.className = "scroll-to-top";
|
||||
button.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 30px;
|
||||
right: 30px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
background-color: #6B4E9B;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
display: none;
|
||||
z-index: 1000;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
`;
|
||||
|
||||
document.body.appendChild(button);
|
||||
|
||||
// Show/hide button based on scroll position
|
||||
window.addEventListener("scroll", () => {
|
||||
if (window.pageYOffset > 300) {
|
||||
button.style.display = "block";
|
||||
} else {
|
||||
button.style.display = "none";
|
||||
}
|
||||
});
|
||||
|
||||
// Scroll to top when clicked
|
||||
button.addEventListener("click", () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: "smooth",
|
||||
});
|
||||
});
|
||||
|
||||
// Hover effect
|
||||
button.addEventListener("mouseenter", () => {
|
||||
button.style.backgroundColor = "#5a3e82";
|
||||
button.style.transform = "translateY(-3px)";
|
||||
});
|
||||
|
||||
button.addEventListener("mouseleave", () => {
|
||||
button.style.backgroundColor = "#6B4E9B";
|
||||
button.style.transform = "translateY(0)";
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize scroll to top button
|
||||
createScrollToTopButton();
|
||||
|
||||
// ====================================
|
||||
// Portfolio Gallery Hover Effects
|
||||
// ====================================
|
||||
document.querySelectorAll(".portfolio-category").forEach((category) => {
|
||||
category.addEventListener("mouseenter", function () {
|
||||
this.style.transition = "all 0.3s ease";
|
||||
});
|
||||
});
|
||||
|
||||
// ====================================
|
||||
// Active Navigation Link Highlighting
|
||||
// ====================================
|
||||
function highlightActiveNavLink() {
|
||||
const currentPage = window.location.pathname.split("/").pop() || "index.html";
|
||||
const navLinks = document.querySelectorAll(".nav-menu a");
|
||||
|
||||
navLinks.forEach((link) => {
|
||||
const linkPage = link.getAttribute("href").split("/").pop().split("#")[0];
|
||||
if (linkPage === currentPage) {
|
||||
link.classList.add("active");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
highlightActiveNavLink();
|
||||
|
||||
// ====================================
|
||||
// Print console message
|
||||
// ====================================
|
||||
console.log(
|
||||
"%c Sky Art Shop Website ",
|
||||
"background: #6B4E9B; color: white; font-size: 20px; padding: 10px;"
|
||||
);
|
||||
console.log("Welcome to Sky Art Shop! 🎨");
|
||||
/**
|
||||
* Main Application JavaScript
|
||||
* Handles global state management, API integration, and core functionality
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Global state management
|
||||
window.AppState = {
|
||||
cart: [],
|
||||
wishlist: [],
|
||||
products: [],
|
||||
settings: null,
|
||||
user: null,
|
||||
|
||||
// Initialize state from localStorage
|
||||
init() {
|
||||
this.loadCart();
|
||||
this.loadWishlist();
|
||||
this.updateUI();
|
||||
},
|
||||
|
||||
// Cart management
|
||||
loadCart() {
|
||||
try {
|
||||
const saved = localStorage.getItem("cart");
|
||||
this.cart = saved ? JSON.parse(saved) : [];
|
||||
} catch (error) {
|
||||
console.error("Error loading cart:", error);
|
||||
this.cart = [];
|
||||
}
|
||||
},
|
||||
|
||||
saveCart() {
|
||||
try {
|
||||
localStorage.setItem("cart", JSON.stringify(this.cart));
|
||||
this.updateUI();
|
||||
} catch (error) {
|
||||
console.error("Error saving cart:", error);
|
||||
}
|
||||
},
|
||||
|
||||
addToCart(product, quantity = 1) {
|
||||
const existing = this.cart.find((item) => item.id === product.id);
|
||||
if (existing) {
|
||||
existing.quantity += quantity;
|
||||
} else {
|
||||
this.cart.push({ ...product, quantity });
|
||||
}
|
||||
this.saveCart();
|
||||
this.showNotification("Added to cart", "success");
|
||||
},
|
||||
|
||||
removeFromCart(productId) {
|
||||
this.cart = this.cart.filter((item) => item.id !== productId);
|
||||
this.saveCart();
|
||||
this.showNotification("Removed from cart", "info");
|
||||
},
|
||||
|
||||
updateCartQuantity(productId, quantity) {
|
||||
const item = this.cart.find((item) => item.id === productId);
|
||||
if (item) {
|
||||
item.quantity = Math.max(1, quantity);
|
||||
this.saveCart();
|
||||
}
|
||||
},
|
||||
|
||||
getCartTotal() {
|
||||
return this.cart.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
},
|
||||
|
||||
getCartCount() {
|
||||
return this.cart.reduce((sum, item) => sum + item.quantity, 0);
|
||||
},
|
||||
|
||||
// Wishlist management
|
||||
loadWishlist() {
|
||||
try {
|
||||
const saved = localStorage.getItem("wishlist");
|
||||
this.wishlist = saved ? JSON.parse(saved) : [];
|
||||
} catch (error) {
|
||||
console.error("Error loading wishlist:", error);
|
||||
this.wishlist = [];
|
||||
}
|
||||
},
|
||||
|
||||
saveWishlist() {
|
||||
try {
|
||||
localStorage.setItem("wishlist", JSON.stringify(this.wishlist));
|
||||
this.updateUI();
|
||||
} catch (error) {
|
||||
console.error("Error saving wishlist:", error);
|
||||
}
|
||||
},
|
||||
|
||||
addToWishlist(product) {
|
||||
if (!this.wishlist.find((item) => item.id === product.id)) {
|
||||
this.wishlist.push(product);
|
||||
this.saveWishlist();
|
||||
this.showNotification("Added to wishlist", "success");
|
||||
}
|
||||
},
|
||||
|
||||
removeFromWishlist(productId) {
|
||||
this.wishlist = this.wishlist.filter((item) => item.id !== productId);
|
||||
this.saveWishlist();
|
||||
this.showNotification("Removed from wishlist", "info");
|
||||
},
|
||||
|
||||
isInWishlist(productId) {
|
||||
return this.wishlist.some((item) => item.id === productId);
|
||||
},
|
||||
|
||||
// UI updates
|
||||
updateUI() {
|
||||
this.updateCartUI();
|
||||
this.updateWishlistUI();
|
||||
},
|
||||
|
||||
updateCartUI() {
|
||||
const count = this.getCartCount();
|
||||
const badge = document.getElementById("cartCount");
|
||||
if (badge) {
|
||||
badge.textContent = count;
|
||||
badge.style.display = count > 0 ? "flex" : "none";
|
||||
}
|
||||
},
|
||||
|
||||
updateWishlistUI() {
|
||||
const count = this.wishlist.length;
|
||||
const badge = document.getElementById("wishlistCount");
|
||||
if (badge) {
|
||||
badge.textContent = count;
|
||||
badge.style.display = count > 0 ? "flex" : "none";
|
||||
}
|
||||
},
|
||||
|
||||
// Notifications
|
||||
showNotification(message, type = "info") {
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.textContent = message;
|
||||
notification.setAttribute("role", "alert");
|
||||
notification.setAttribute("aria-live", "polite");
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
setTimeout(() => notification.classList.add("show"), 10);
|
||||
setTimeout(() => {
|
||||
notification.classList.remove("show");
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
},
|
||||
};
|
||||
|
||||
// API Client
|
||||
window.API = {
|
||||
baseURL: "/api",
|
||||
|
||||
async request(endpoint, options = {}) {
|
||||
try {
|
||||
const response = await fetch(this.baseURL + endpoint, {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("API request failed:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
// Product endpoints
|
||||
async getProducts(filters = {}) {
|
||||
const params = new URLSearchParams(filters);
|
||||
return this.request(`/products?${params}`);
|
||||
},
|
||||
|
||||
async getProduct(id) {
|
||||
return this.request(`/products/${id}`);
|
||||
},
|
||||
|
||||
async getFeaturedProducts() {
|
||||
return this.request("/products/featured");
|
||||
},
|
||||
|
||||
// Settings endpoint
|
||||
async getSettings() {
|
||||
return this.request("/settings");
|
||||
},
|
||||
|
||||
// Homepage endpoint
|
||||
async getHomepageSettings() {
|
||||
return this.request("/homepage/settings");
|
||||
},
|
||||
|
||||
// Menu endpoint
|
||||
async getMenu() {
|
||||
return this.request("/menu");
|
||||
},
|
||||
|
||||
// Blog endpoints
|
||||
async getBlogPosts() {
|
||||
return this.request("/blog");
|
||||
},
|
||||
|
||||
async getBlogPost(id) {
|
||||
return this.request(`/blog/${id}`);
|
||||
},
|
||||
|
||||
// Portfolio endpoints
|
||||
async getPortfolioProjects() {
|
||||
return this.request("/portfolio");
|
||||
},
|
||||
|
||||
async getPortfolioProject(id) {
|
||||
return this.request(`/portfolio/${id}`);
|
||||
},
|
||||
|
||||
// Pages endpoints
|
||||
async getPages() {
|
||||
return this.request("/pages");
|
||||
},
|
||||
|
||||
async getPage(slug) {
|
||||
return this.request(`/pages/${slug}`);
|
||||
},
|
||||
};
|
||||
|
||||
// Utility functions
|
||||
window.Utils = {
|
||||
// Format currency
|
||||
formatCurrency(amount) {
|
||||
return new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
}).format(amount);
|
||||
},
|
||||
|
||||
// Format date
|
||||
formatDate(date) {
|
||||
return new Intl.DateTimeFormat("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
}).format(new Date(date));
|
||||
},
|
||||
|
||||
// Debounce function
|
||||
debounce(func, wait) {
|
||||
let timeout;
|
||||
return function executedFunction(...args) {
|
||||
const later = () => {
|
||||
clearTimeout(timeout);
|
||||
func(...args);
|
||||
};
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
},
|
||||
|
||||
// Get URL parameter
|
||||
getUrlParameter(name) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return params.get(name);
|
||||
},
|
||||
|
||||
// Safe HTML encode
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
},
|
||||
|
||||
// Show loading state
|
||||
showLoading(element) {
|
||||
if (element) {
|
||||
element.classList.add("loading");
|
||||
element.setAttribute("aria-busy", "true");
|
||||
}
|
||||
},
|
||||
|
||||
hideLoading(element) {
|
||||
if (element) {
|
||||
element.classList.remove("loading");
|
||||
element.setAttribute("aria-busy", "false");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Initialize on DOM ready
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
window.AppState.init();
|
||||
});
|
||||
} else {
|
||||
window.AppState.init();
|
||||
}
|
||||
|
||||
// Add notification styles if not exists
|
||||
if (!document.getElementById("notification-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "notification-styles";
|
||||
style.textContent = `
|
||||
.notification {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 15px 20px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
z-index: 10000;
|
||||
opacity: 0;
|
||||
transform: translateX(400px);
|
||||
transition: all 0.3s ease;
|
||||
max-width: 300px;
|
||||
}
|
||||
.notification.show {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
.notification-success {
|
||||
border-left: 4px solid #28a745;
|
||||
}
|
||||
.notification-error {
|
||||
border-left: 4px solid #dc3545;
|
||||
}
|
||||
.notification-info {
|
||||
border-left: 4px solid #17a2b8;
|
||||
}
|
||||
.notification-warning {
|
||||
border-left: 4px solid #ffc107;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,79 +1,203 @@
|
||||
// Dynamic Menu Loader for Sky Art Shop
|
||||
// Include this in all public pages to load menu from database
|
||||
/**
|
||||
* Navigation Component
|
||||
* Handles mobile menu, dropdowns, and accessibility
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Load and render navigation menu from API
|
||||
async function loadNavigationMenu() {
|
||||
try {
|
||||
const response = await fetch("/api/menu");
|
||||
const data = await response.json();
|
||||
class Navigation {
|
||||
constructor() {
|
||||
this.mobileMenuToggle = document.getElementById("mobileMenuToggle");
|
||||
this.mobileMenu = document.getElementById("mobileMenu");
|
||||
this.mobileMenuClose = document.getElementById("mobileMenuClose");
|
||||
this.overlay = document.getElementById("mobileMenuOverlay");
|
||||
this.body = document.body;
|
||||
|
||||
if (data.success && data.items && data.items.length > 0) {
|
||||
renderDesktopMenu(data.items);
|
||||
renderMobileMenu(data.items);
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupMobileMenu();
|
||||
this.setupAccessibility();
|
||||
this.highlightCurrentPage();
|
||||
this.setupKeyboardNavigation();
|
||||
}
|
||||
|
||||
setupMobileMenu() {
|
||||
// Open mobile menu
|
||||
if (this.mobileMenuToggle) {
|
||||
this.mobileMenuToggle.addEventListener("click", () =>
|
||||
this.openMobileMenu()
|
||||
);
|
||||
}
|
||||
|
||||
// Close mobile menu
|
||||
if (this.mobileMenuClose) {
|
||||
this.mobileMenuClose.addEventListener("click", () =>
|
||||
this.closeMobileMenu()
|
||||
);
|
||||
}
|
||||
|
||||
if (this.overlay) {
|
||||
this.overlay.addEventListener("click", () => this.closeMobileMenu());
|
||||
}
|
||||
|
||||
// Close on ESC key
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (
|
||||
e.key === "Escape" &&
|
||||
this.mobileMenu &&
|
||||
this.mobileMenu.classList.contains("active")
|
||||
) {
|
||||
this.closeMobileMenu();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
openMobileMenu() {
|
||||
if (this.mobileMenu) {
|
||||
this.mobileMenu.classList.add("active");
|
||||
this.mobileMenu.setAttribute("aria-hidden", "false");
|
||||
this.body.style.overflow = "hidden";
|
||||
|
||||
if (this.overlay) {
|
||||
this.overlay.classList.add("active");
|
||||
}
|
||||
|
||||
// Focus first link
|
||||
const firstLink = this.mobileMenu.querySelector("a");
|
||||
if (firstLink) {
|
||||
setTimeout(() => firstLink.focus(), 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
closeMobileMenu() {
|
||||
if (this.mobileMenu) {
|
||||
this.mobileMenu.classList.remove("active");
|
||||
this.mobileMenu.setAttribute("aria-hidden", "true");
|
||||
this.body.style.overflow = "";
|
||||
|
||||
if (this.overlay) {
|
||||
this.overlay.classList.remove("active");
|
||||
}
|
||||
|
||||
// Return focus to toggle button
|
||||
if (this.mobileMenuToggle) {
|
||||
this.mobileMenuToggle.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupAccessibility() {
|
||||
// Wait for body to exist
|
||||
if (!document.body) return;
|
||||
|
||||
// Add ARIA labels to nav items
|
||||
const navLinks = document.querySelectorAll(".nav-link");
|
||||
navLinks.forEach((link) => {
|
||||
if (!link.getAttribute("aria-label")) {
|
||||
link.setAttribute(
|
||||
"aria-label",
|
||||
`Navigate to ${link.textContent.trim()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Add skip to main content link
|
||||
if (!document.getElementById("skip-to-main")) {
|
||||
const skipLink = document.createElement("a");
|
||||
skipLink.id = "skip-to-main";
|
||||
skipLink.href = "#main-content";
|
||||
skipLink.textContent = "Skip to main content";
|
||||
skipLink.className = "skip-link";
|
||||
document.body.insertBefore(skipLink, document.body.firstChild);
|
||||
|
||||
// Add styles for skip link
|
||||
if (!document.getElementById("skip-link-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "skip-link-styles";
|
||||
style.textContent = `
|
||||
.skip-link {
|
||||
position: fixed;
|
||||
top: -100px;
|
||||
left: 0;
|
||||
padding: 10px 20px;
|
||||
background: #000;
|
||||
color: #fff;
|
||||
z-index: 10001;
|
||||
text-decoration: none;
|
||||
border-radius: 0 0 8px 0;
|
||||
}
|
||||
.skip-link:focus {
|
||||
top: 0;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
highlightCurrentPage() {
|
||||
const currentPath = window.location.pathname;
|
||||
const navLinks = document.querySelectorAll(".nav-link, .mobile-link");
|
||||
|
||||
navLinks.forEach((link) => {
|
||||
const href = link.getAttribute("href");
|
||||
if (
|
||||
href &&
|
||||
(currentPath === href || currentPath.startsWith(href + "/"))
|
||||
) {
|
||||
link.classList.add("active");
|
||||
link.setAttribute("aria-current", "page");
|
||||
} else {
|
||||
link.classList.remove("active");
|
||||
link.removeAttribute("aria-current");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupKeyboardNavigation() {
|
||||
// Tab trap in mobile menu when open
|
||||
if (this.mobileMenu) {
|
||||
const focusableElements = this.mobileMenu.querySelectorAll(
|
||||
'a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
|
||||
if (focusableElements.length > 0) {
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
|
||||
this.mobileMenu.addEventListener("keydown", (e) => {
|
||||
if (
|
||||
e.key === "Tab" &&
|
||||
this.mobileMenu.classList.contains("active")
|
||||
) {
|
||||
if (e.shiftKey) {
|
||||
if (document.activeElement === firstElement) {
|
||||
e.preventDefault();
|
||||
lastElement.focus();
|
||||
}
|
||||
} else {
|
||||
if (document.activeElement === lastElement) {
|
||||
e.preventDefault();
|
||||
firstElement.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load menu:", error);
|
||||
// Keep existing hardcoded menu as fallback
|
||||
}
|
||||
}
|
||||
|
||||
function renderDesktopMenu(items) {
|
||||
const desktopMenuList = document.querySelector(".nav-menu-list");
|
||||
if (!desktopMenuList) return;
|
||||
|
||||
desktopMenuList.innerHTML = items
|
||||
.map(
|
||||
(item) => `
|
||||
<li class="nav-item">
|
||||
<a href="${item.url}" class="nav-link">
|
||||
${item.icon ? `<i class="bi ${item.icon}"></i> ` : ""}${item.label}
|
||||
</a>
|
||||
</li>
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
|
||||
// Set active state based on current page
|
||||
const currentPath = window.location.pathname;
|
||||
document.querySelectorAll(".nav-link").forEach((link) => {
|
||||
if (link.getAttribute("href") === currentPath) {
|
||||
link.classList.add("active");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function renderMobileMenu(items) {
|
||||
const mobileMenuList = document.querySelector(".mobile-menu-list");
|
||||
if (!mobileMenuList) return;
|
||||
|
||||
mobileMenuList.innerHTML = items
|
||||
.map(
|
||||
(item) => `
|
||||
<li>
|
||||
<a href="${item.url}" class="mobile-link">
|
||||
${item.icon ? `<i class="bi ${item.icon}"></i> ` : ""}${item.label}
|
||||
</a>
|
||||
</li>
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
|
||||
// Set active state for mobile menu
|
||||
const currentPath = window.location.pathname;
|
||||
document.querySelectorAll(".mobile-link").forEach((link) => {
|
||||
if (link.getAttribute("href") === currentPath) {
|
||||
link.classList.add("active");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Load menu when DOM is ready
|
||||
// Initialize navigation when DOM is ready
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", loadNavigationMenu);
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
new Navigation();
|
||||
});
|
||||
} else {
|
||||
loadNavigationMenu();
|
||||
new Navigation();
|
||||
}
|
||||
})();
|
||||
|
||||
224
website/assets/js/notifications.js
Normal file
224
website/assets/js/notifications.js
Normal file
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Notification System
|
||||
* Accessible toast notifications
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
class NotificationManager {
|
||||
constructor() {
|
||||
this.container = null;
|
||||
this.notifications = new Map();
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () =>
|
||||
this.createContainer()
|
||||
);
|
||||
} else {
|
||||
this.createContainer();
|
||||
}
|
||||
}
|
||||
|
||||
createContainer() {
|
||||
if (!document.body || this.container) return;
|
||||
|
||||
this.container = document.createElement("div");
|
||||
this.container.id = "notification-container";
|
||||
this.container.setAttribute("aria-live", "polite");
|
||||
this.container.setAttribute("aria-atomic", "true");
|
||||
this.container.className = "notification-container";
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.textContent = `
|
||||
.notification-container {
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
right: 20px;
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 400px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.notification {
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
color: white;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
pointer-events: auto;
|
||||
animation: slideInRight 0.3s ease;
|
||||
min-width: 250px;
|
||||
}
|
||||
|
||||
.notification.removing {
|
||||
animation: slideOutRight 0.3s ease;
|
||||
}
|
||||
|
||||
.notification-success {
|
||||
background: #10b981;
|
||||
}
|
||||
|
||||
.notification-error {
|
||||
background: #ef4444;
|
||||
}
|
||||
|
||||
.notification-info {
|
||||
background: #3b82f6;
|
||||
}
|
||||
|
||||
.notification-warning {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
.notification-icon {
|
||||
font-size: 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notification-message {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.notification-close {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
opacity: 0.8;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.notification-close:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@keyframes slideInRight {
|
||||
from {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideOutRight {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.notification-container {
|
||||
right: 10px;
|
||||
left: 10px;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.notification {
|
||||
min-width: auto;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
document.head.appendChild(style);
|
||||
document.body.appendChild(this.container);
|
||||
}
|
||||
|
||||
show(message, type = "info", duration = 3000) {
|
||||
if (!this.container) this.createContainer();
|
||||
if (!this.container) return;
|
||||
|
||||
const id = Date.now() + Math.random();
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.setAttribute("role", "alert");
|
||||
|
||||
const icons = {
|
||||
success: "✓",
|
||||
error: "✕",
|
||||
info: "ℹ",
|
||||
warning: "⚠",
|
||||
};
|
||||
|
||||
notification.innerHTML = `
|
||||
<span class="notification-icon">${icons[type] || icons.info}</span>
|
||||
<span class="notification-message">${this.escapeHtml(message)}</span>
|
||||
<button class="notification-close" aria-label="Close notification">×</button>
|
||||
`;
|
||||
|
||||
const closeBtn = notification.querySelector(".notification-close");
|
||||
closeBtn.addEventListener("click", () => this.remove(id));
|
||||
|
||||
this.container.appendChild(notification);
|
||||
this.notifications.set(id, notification);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(() => this.remove(id), duration);
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
remove(id) {
|
||||
const notification = this.notifications.get(id);
|
||||
if (!notification) return;
|
||||
|
||||
notification.classList.add("removing");
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.parentNode.removeChild(notification);
|
||||
}
|
||||
this.notifications.delete(id);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
success(message, duration) {
|
||||
return this.show(message, "success", duration);
|
||||
}
|
||||
|
||||
error(message, duration) {
|
||||
return this.show(message, "error", duration);
|
||||
}
|
||||
|
||||
info(message, duration) {
|
||||
return this.show(message, "info", duration);
|
||||
}
|
||||
|
||||
warning(message, duration) {
|
||||
return this.show(message, "warning", duration);
|
||||
}
|
||||
}
|
||||
|
||||
// Create global instance
|
||||
window.Notifications = window.Notifications || new NotificationManager();
|
||||
|
||||
// Legacy compatibility
|
||||
window.showNotification = function (message, type = "info") {
|
||||
window.Notifications.show(message, type);
|
||||
};
|
||||
})();
|
||||
@@ -1,143 +1,555 @@
|
||||
// Smooth Page Transitions for Sky Art Shop
|
||||
// Provides fade-out/fade-in effects when navigating between pages
|
||||
/**
|
||||
* Page Transitions and Smooth Navigation
|
||||
* Handles page loading, transitions, and history management
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
class PageTransitions {
|
||||
constructor() {
|
||||
this.transitionDuration = 300;
|
||||
this.isTransitioning = false;
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Add page transition styles (less aggressive approach)
|
||||
const style = document.createElement("style");
|
||||
style.textContent = `
|
||||
body {
|
||||
transition: opacity 0.25s ease-in-out;
|
||||
init() {
|
||||
// Wait for body to exist
|
||||
if (!document.body) return;
|
||||
|
||||
// Add transition wrapper if it doesn't exist
|
||||
if (!document.getElementById("page-transition")) {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.id = "page-transition";
|
||||
wrapper.className = "page-transition";
|
||||
|
||||
// Wrap main content
|
||||
const main = document.querySelector("main") || document.body;
|
||||
const parent = main.parentNode;
|
||||
parent.insertBefore(wrapper, main);
|
||||
wrapper.appendChild(main);
|
||||
}
|
||||
|
||||
body.page-transitioning {
|
||||
|
||||
// Add fade-in on page load
|
||||
this.fadeIn();
|
||||
|
||||
// Intercept navigation clicks
|
||||
this.setupLinkInterception();
|
||||
|
||||
// Handle back/forward buttons
|
||||
window.addEventListener("popstate", (e) => {
|
||||
if (e.state && e.state.url) {
|
||||
this.navigate(e.state.url, false);
|
||||
}
|
||||
});
|
||||
|
||||
// Add scroll restoration
|
||||
if ("scrollRestoration" in history) {
|
||||
history.scrollRestoration = "manual";
|
||||
}
|
||||
}
|
||||
|
||||
fadeIn() {
|
||||
const wrapper = document.getElementById("page-transition");
|
||||
if (wrapper) {
|
||||
wrapper.classList.add("fade-in");
|
||||
setTimeout(() => {
|
||||
wrapper.classList.remove("fade-in");
|
||||
}, this.transitionDuration);
|
||||
}
|
||||
}
|
||||
|
||||
fadeOut(callback) {
|
||||
const wrapper = document.getElementById("page-transition");
|
||||
if (wrapper) {
|
||||
wrapper.classList.add("fade-out");
|
||||
setTimeout(() => {
|
||||
if (callback) callback();
|
||||
wrapper.classList.remove("fade-out");
|
||||
}, this.transitionDuration);
|
||||
} else {
|
||||
if (callback) callback();
|
||||
}
|
||||
}
|
||||
|
||||
setupLinkInterception() {
|
||||
document.addEventListener("click", (e) => {
|
||||
const link = e.target.closest("a");
|
||||
|
||||
// Check if it's a valid internal link
|
||||
if (!link) return;
|
||||
if (link.hasAttribute("data-no-transition")) return;
|
||||
if (link.target === "_blank") return;
|
||||
if (link.hasAttribute("download")) return;
|
||||
|
||||
const href = link.getAttribute("href");
|
||||
if (
|
||||
!href ||
|
||||
href.startsWith("#") ||
|
||||
href.startsWith("mailto:") ||
|
||||
href.startsWith("tel:")
|
||||
)
|
||||
return;
|
||||
|
||||
// Check if it's an external link
|
||||
const url = new URL(href, window.location.origin);
|
||||
if (url.origin !== window.location.origin) return;
|
||||
|
||||
// Intercept the navigation
|
||||
e.preventDefault();
|
||||
this.navigate(href, true);
|
||||
});
|
||||
}
|
||||
|
||||
navigate(url, updateHistory = true) {
|
||||
if (this.isTransitioning) return;
|
||||
this.isTransitioning = true;
|
||||
|
||||
this.fadeOut(() => {
|
||||
if (updateHistory) {
|
||||
history.pushState({ url }, "", url);
|
||||
}
|
||||
window.location.href = url;
|
||||
});
|
||||
}
|
||||
|
||||
// Scroll to element with smooth animation
|
||||
scrollTo(selector, offset = 0) {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) return;
|
||||
|
||||
const top =
|
||||
element.getBoundingClientRect().top + window.pageYOffset - offset;
|
||||
|
||||
window.scrollTo({
|
||||
top,
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
|
||||
// Scroll to top
|
||||
scrollToTop() {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy Loading Images
|
||||
* Improves performance by loading images only when they're visible
|
||||
*/
|
||||
class LazyLoader {
|
||||
constructor() {
|
||||
this.images = [];
|
||||
this.observer = null;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Find all lazy images
|
||||
this.images = document.querySelectorAll(
|
||||
'img[data-src], img[loading="lazy"]'
|
||||
);
|
||||
|
||||
// Set up Intersection Observer
|
||||
if ("IntersectionObserver" in window) {
|
||||
this.observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
this.loadImage(entry.target);
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
rootMargin: "50px",
|
||||
}
|
||||
);
|
||||
|
||||
this.images.forEach((img) => this.observer.observe(img));
|
||||
} else {
|
||||
// Fallback for older browsers
|
||||
this.images.forEach((img) => this.loadImage(img));
|
||||
}
|
||||
}
|
||||
|
||||
loadImage(img) {
|
||||
const src = img.getAttribute("data-src");
|
||||
if (src) {
|
||||
img.src = src;
|
||||
img.removeAttribute("data-src");
|
||||
}
|
||||
|
||||
// Add fade-in effect
|
||||
img.addEventListener("load", () => {
|
||||
img.classList.add("loaded");
|
||||
});
|
||||
|
||||
if (this.observer) {
|
||||
this.observer.unobserve(img);
|
||||
}
|
||||
}
|
||||
|
||||
// Add new images to observer
|
||||
observe(images) {
|
||||
if (!images) return;
|
||||
|
||||
const imageList = Array.isArray(images) ? images : [images];
|
||||
imageList.forEach((img) => {
|
||||
if (this.observer) {
|
||||
this.observer.observe(img);
|
||||
} else {
|
||||
this.loadImage(img);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Smooth Scroll Handler
|
||||
* Adds smooth scrolling to anchor links
|
||||
*/
|
||||
class SmoothScroll {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
|
||||
anchor.addEventListener("click", (e) => {
|
||||
const href = anchor.getAttribute("href");
|
||||
if (href === "#") return;
|
||||
|
||||
e.preventDefault();
|
||||
const target = document.querySelector(href);
|
||||
|
||||
if (target) {
|
||||
const offset = 80; // Account for fixed header
|
||||
const top =
|
||||
target.getBoundingClientRect().top + window.pageYOffset - offset;
|
||||
|
||||
window.scrollTo({
|
||||
top,
|
||||
behavior: "smooth",
|
||||
});
|
||||
|
||||
// Update URL without scrolling
|
||||
history.pushState(null, "", href);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Back to Top Button
|
||||
* Shows/hides button based on scroll position
|
||||
*/
|
||||
class BackToTop {
|
||||
constructor() {
|
||||
this.button = null;
|
||||
this.scrollThreshold = 300;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Wait for body to exist
|
||||
if (!document.body) return;
|
||||
|
||||
// Create button if it doesn't exist
|
||||
this.button = document.getElementById("back-to-top");
|
||||
if (!this.button) {
|
||||
this.button = document.createElement("button");
|
||||
this.button.id = "back-to-top";
|
||||
this.button.className = "back-to-top";
|
||||
this.button.innerHTML = "↑";
|
||||
this.button.setAttribute("aria-label", "Back to top");
|
||||
document.body.appendChild(this.button);
|
||||
}
|
||||
|
||||
// Handle scroll
|
||||
window.addEventListener("scroll", () => {
|
||||
if (window.pageYOffset > this.scrollThreshold) {
|
||||
this.button.classList.add("visible");
|
||||
} else {
|
||||
this.button.classList.remove("visible");
|
||||
}
|
||||
});
|
||||
|
||||
// Handle click
|
||||
this.button.addEventListener("click", () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: "smooth",
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loading Overlay
|
||||
* Shows loading state during async operations
|
||||
*/
|
||||
class LoadingOverlay {
|
||||
constructor() {
|
||||
this.overlay = null;
|
||||
this.activeOperations = 0;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Wait for body to exist
|
||||
if (!document.body) return;
|
||||
|
||||
// Create overlay if it doesn't exist
|
||||
this.overlay = document.getElementById("loading-overlay");
|
||||
if (!this.overlay) {
|
||||
this.overlay = document.createElement("div");
|
||||
this.overlay.id = "loading-overlay";
|
||||
this.overlay.className = "loading-overlay";
|
||||
this.overlay.innerHTML = `
|
||||
<div class="loading-spinner">
|
||||
<div class="spinner"></div>
|
||||
<p>Loading...</p>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(this.overlay);
|
||||
}
|
||||
}
|
||||
|
||||
show() {
|
||||
this.activeOperations++;
|
||||
this.overlay.classList.add("active");
|
||||
document.body.style.overflow = "hidden";
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.activeOperations = Math.max(0, this.activeOperations - 1);
|
||||
|
||||
if (this.activeOperations === 0) {
|
||||
this.overlay.classList.remove("active");
|
||||
document.body.style.overflow = "";
|
||||
}
|
||||
}
|
||||
|
||||
// Force hide regardless of operation count
|
||||
forceHide() {
|
||||
this.activeOperations = 0;
|
||||
this.overlay.classList.remove("active");
|
||||
document.body.style.overflow = "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Page Visibility Handler
|
||||
* Handles actions when page becomes visible/hidden
|
||||
*/
|
||||
class PageVisibility {
|
||||
constructor() {
|
||||
this.callbacks = {
|
||||
visible: [],
|
||||
hidden: [],
|
||||
};
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
this.callbacks.hidden.forEach((cb) => cb());
|
||||
} else {
|
||||
this.callbacks.visible.forEach((cb) => cb());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onVisible(callback) {
|
||||
this.callbacks.visible.push(callback);
|
||||
}
|
||||
|
||||
onHidden(callback) {
|
||||
this.callbacks.hidden.push(callback);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Network Status Handler
|
||||
* Monitors online/offline status
|
||||
*/
|
||||
class NetworkStatus {
|
||||
constructor() {
|
||||
this.isOnline = navigator.onLine;
|
||||
this.callbacks = {
|
||||
online: [],
|
||||
offline: [],
|
||||
};
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
window.addEventListener("online", () => {
|
||||
this.isOnline = true;
|
||||
this.callbacks.online.forEach((cb) => cb());
|
||||
this.showNotification("Back online", "success");
|
||||
});
|
||||
|
||||
window.addEventListener("offline", () => {
|
||||
this.isOnline = false;
|
||||
this.callbacks.offline.forEach((cb) => cb());
|
||||
this.showNotification("No internet connection", "error");
|
||||
});
|
||||
}
|
||||
|
||||
onOnline(callback) {
|
||||
this.callbacks.online.push(callback);
|
||||
}
|
||||
|
||||
onOffline(callback) {
|
||||
this.callbacks.offline.push(callback);
|
||||
}
|
||||
|
||||
showNotification(message, type) {
|
||||
if (window.Utils && window.Utils.notify) {
|
||||
window.Utils.notify(message, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize when DOM is ready
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", initPageTransitions);
|
||||
} else {
|
||||
initPageTransitions();
|
||||
}
|
||||
|
||||
function initPageTransitions() {
|
||||
// Initialize all modules
|
||||
window.pageTransitions = new PageTransitions();
|
||||
window.lazyLoader = new LazyLoader();
|
||||
window.smoothScroll = new SmoothScroll();
|
||||
window.backToTop = new BackToTop();
|
||||
window.loadingOverlay = new LoadingOverlay();
|
||||
window.pageVisibility = new PageVisibility();
|
||||
window.networkStatus = new NetworkStatus();
|
||||
|
||||
console.log("Page transitions initialized");
|
||||
}
|
||||
|
||||
// Add CSS if not already present
|
||||
if (!document.getElementById("page-transitions-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "page-transitions-styles";
|
||||
style.textContent = `
|
||||
.page-transition {
|
||||
opacity: 1;
|
||||
transition: opacity 300ms ease;
|
||||
}
|
||||
|
||||
.page-transition.fade-in {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
animation: fadeIn 300ms ease forwards;
|
||||
}
|
||||
|
||||
.page-transition.fade-out {
|
||||
opacity: 1;
|
||||
animation: fadeOut 300ms ease forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes fadeOut {
|
||||
from { opacity: 1; }
|
||||
to { opacity: 0; }
|
||||
}
|
||||
|
||||
img[data-src] {
|
||||
opacity: 0;
|
||||
transition: opacity 300ms ease;
|
||||
}
|
||||
|
||||
img.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.back-to-top {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
right: 20px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(20px);
|
||||
transition: all 0.3s ease;
|
||||
z-index: 999;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
.back-to-top.visible {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.back-to-top:hover {
|
||||
background: #5568d3;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.loading-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(255,255,255,0.95);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: all 0.3s ease;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.loading-overlay.active {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border: 4px solid #f3f3f3;
|
||||
border-top: 4px solid #667eea;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto 16px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.loading-spinner p {
|
||||
color: #667eea;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
// Fade in page on load (if coming from a transition)
|
||||
function initPageTransition() {
|
||||
// Check if we're coming from a transition
|
||||
const isTransitioning = sessionStorage.getItem("page-transitioning");
|
||||
if (isTransitioning === "true") {
|
||||
document.body.style.opacity = "0";
|
||||
sessionStorage.removeItem("page-transitioning");
|
||||
|
||||
// Wait for content to be ready, then fade in
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
document.body.style.opacity = "1";
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Handle navigation with transitions
|
||||
function setupNavigationTransitions() {
|
||||
// Get all internal links
|
||||
document.addEventListener("click", function (e) {
|
||||
const link = e.target.closest("a");
|
||||
|
||||
if (!link) return;
|
||||
|
||||
const href = link.getAttribute("href");
|
||||
|
||||
// Skip if:
|
||||
// - External link
|
||||
// - Opens in new tab
|
||||
// - Has download attribute
|
||||
// - Is a hash link on same page
|
||||
// - Is a javascript: link
|
||||
// - Is a mailto: or tel: link
|
||||
if (
|
||||
!href ||
|
||||
link.target === "_blank" ||
|
||||
link.hasAttribute("download") ||
|
||||
href.startsWith("javascript:") ||
|
||||
href.startsWith("mailto:") ||
|
||||
href.startsWith("tel:") ||
|
||||
href.startsWith("#") ||
|
||||
(href.includes("://") && !href.includes(window.location.host))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent default navigation
|
||||
e.preventDefault();
|
||||
|
||||
// Start transition
|
||||
document.body.classList.add("page-transitioning");
|
||||
sessionStorage.setItem("page-transitioning", "true");
|
||||
|
||||
// Navigate after fade-out completes
|
||||
setTimeout(() => {
|
||||
window.location.href = href;
|
||||
}, 250); // Match CSS transition duration
|
||||
});
|
||||
}
|
||||
|
||||
// Use View Transitions API if available (Chrome 111+, Safari 18+)
|
||||
function setupViewTransitions() {
|
||||
if (!document.startViewTransition) return;
|
||||
|
||||
document.addEventListener(
|
||||
"click",
|
||||
function (e) {
|
||||
const link = e.target.closest("a");
|
||||
|
||||
if (!link) return;
|
||||
|
||||
const href = link.getAttribute("href");
|
||||
|
||||
// Same checks as above
|
||||
if (
|
||||
!href ||
|
||||
link.target === "_blank" ||
|
||||
link.hasAttribute("download") ||
|
||||
href.startsWith("javascript:") ||
|
||||
href.startsWith("mailto:") ||
|
||||
href.startsWith("tel:") ||
|
||||
href.startsWith("#") ||
|
||||
(href.includes("://") && !href.includes(window.location.host))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
// Use View Transitions API for smooth cross-page transitions
|
||||
sessionStorage.setItem("page-transitioning", "true");
|
||||
document.startViewTransition(() => {
|
||||
window.location.href = href;
|
||||
});
|
||||
},
|
||||
true
|
||||
); // Use capture to run before other handlers
|
||||
}
|
||||
|
||||
// Initialize
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
initPageTransition();
|
||||
setupNavigationTransitions();
|
||||
});
|
||||
} else {
|
||||
initPageTransition();
|
||||
setupNavigationTransitions();
|
||||
}
|
||||
|
||||
// For browsers that support View Transitions API (progressive enhancement)
|
||||
if ("startViewTransition" in document) {
|
||||
const viewStyle = document.createElement("style");
|
||||
viewStyle.textContent = `
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) {
|
||||
animation-duration: 0.25s;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(viewStyle);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -1,376 +1,306 @@
|
||||
/**
|
||||
* Enhanced Cart and Wishlist Management System
|
||||
* Amazon/eBay-style product display with images and details
|
||||
* Shopping/Products Component
|
||||
* Handles product display, filtering, and interactions
|
||||
*/
|
||||
|
||||
class ShoppingManager {
|
||||
constructor() {
|
||||
this.cart = this.loadFromStorage("skyart_cart") || [];
|
||||
this.wishlist = this.loadFromStorage("skyart_wishlist") || [];
|
||||
this.init();
|
||||
}
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
init() {
|
||||
this.updateAllBadges();
|
||||
this.setupEventListeners();
|
||||
this.renderCart();
|
||||
this.renderWishlist();
|
||||
}
|
||||
class ShoppingPage {
|
||||
constructor() {
|
||||
this.productsContainer = document.getElementById("productsContainer");
|
||||
this.loadingIndicator = document.getElementById("loadingIndicator");
|
||||
this.errorContainer = document.getElementById("errorContainer");
|
||||
this.currentCategory = window.Utils.getUrlParameter("category") || "all";
|
||||
this.currentSort = "newest";
|
||||
this.products = [];
|
||||
|
||||
loadFromStorage(key) {
|
||||
try {
|
||||
const data = localStorage.getItem(key);
|
||||
return data ? JSON.parse(data) : null;
|
||||
} catch (e) {
|
||||
console.error("Error loading from storage:", e);
|
||||
return null;
|
||||
this.init();
|
||||
}
|
||||
}
|
||||
|
||||
saveToStorage(key, data) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(data));
|
||||
} catch (e) {
|
||||
console.error("Error saving to storage:", e);
|
||||
async init() {
|
||||
this.setupEventListeners();
|
||||
await this.loadProducts();
|
||||
}
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
// Cart toggle
|
||||
const cartToggle = document.getElementById("cartToggle");
|
||||
const cartPanel = document.getElementById("cartPanel");
|
||||
const cartClose = document.getElementById("cartClose");
|
||||
|
||||
if (cartToggle) {
|
||||
cartToggle.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
cartPanel?.classList.toggle("active");
|
||||
document.getElementById("wishlistPanel")?.classList.remove("active");
|
||||
setupEventListeners() {
|
||||
// Category filters
|
||||
document.querySelectorAll("[data-category]").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
this.currentCategory = e.currentTarget.dataset.category;
|
||||
this.filterProducts();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (cartClose) {
|
||||
cartClose.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
cartPanel?.classList.remove("active");
|
||||
});
|
||||
}
|
||||
|
||||
// Wishlist toggle
|
||||
const wishlistToggle = document.getElementById("wishlistToggle");
|
||||
const wishlistPanel = document.getElementById("wishlistPanel");
|
||||
const wishlistClose = document.getElementById("wishlistClose");
|
||||
|
||||
if (wishlistToggle) {
|
||||
wishlistToggle.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
wishlistPanel?.classList.toggle("active");
|
||||
cartPanel?.classList.remove("active");
|
||||
});
|
||||
}
|
||||
|
||||
if (wishlistClose) {
|
||||
wishlistClose.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
wishlistPanel?.classList.remove("active");
|
||||
});
|
||||
}
|
||||
|
||||
// Mobile menu
|
||||
const mobileToggle = document.getElementById("mobileMenuToggle");
|
||||
const mobileMenu = document.getElementById("mobileMenu");
|
||||
const mobileClose = document.getElementById("mobileMenuClose");
|
||||
|
||||
if (mobileToggle) {
|
||||
mobileToggle.addEventListener("click", () => {
|
||||
mobileMenu?.classList.toggle("active");
|
||||
document.body.style.overflow = mobileMenu?.classList.contains("active")
|
||||
? "hidden"
|
||||
: "";
|
||||
});
|
||||
}
|
||||
|
||||
if (mobileClose) {
|
||||
mobileClose.addEventListener("click", () => {
|
||||
mobileMenu?.classList.remove("active");
|
||||
document.body.style.overflow = "";
|
||||
});
|
||||
}
|
||||
|
||||
// Close dropdowns on outside click
|
||||
document.addEventListener("click", (e) => {
|
||||
if (!e.target.closest(".cart-dropdown-wrapper")) {
|
||||
cartPanel?.classList.remove("active");
|
||||
// Sort dropdown
|
||||
const sortSelect = document.getElementById("sortSelect");
|
||||
if (sortSelect) {
|
||||
sortSelect.addEventListener("change", (e) => {
|
||||
this.currentSort = e.target.value;
|
||||
this.filterProducts();
|
||||
});
|
||||
}
|
||||
if (!e.target.closest(".wishlist-dropdown-wrapper")) {
|
||||
wishlistPanel?.classList.remove("active");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add to Cart
|
||||
addToCart(product, quantity = 1) {
|
||||
const existingItem = this.cart.find((item) => item.id === product.id);
|
||||
|
||||
if (existingItem) {
|
||||
existingItem.quantity += quantity;
|
||||
} else {
|
||||
this.cart.push({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
price: parseFloat(product.price),
|
||||
imageurl: product.imageurl,
|
||||
quantity: quantity,
|
||||
addedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
this.saveToStorage("skyart_cart", this.cart);
|
||||
this.updateAllBadges();
|
||||
this.renderCart();
|
||||
this.showNotification(`${product.name} added to cart!`, "success");
|
||||
}
|
||||
|
||||
// Remove from Cart
|
||||
removeFromCart(productId) {
|
||||
this.cart = this.cart.filter((item) => item.id !== productId);
|
||||
this.saveToStorage("skyart_cart", this.cart);
|
||||
this.updateAllBadges();
|
||||
this.renderCart();
|
||||
this.showNotification("Item removed from cart", "info");
|
||||
}
|
||||
|
||||
// Update Cart Quantity
|
||||
updateCartQuantity(productId, quantity) {
|
||||
const item = this.cart.find((item) => item.id === productId);
|
||||
if (item) {
|
||||
if (quantity <= 0) {
|
||||
this.removeFromCart(productId);
|
||||
} else {
|
||||
item.quantity = quantity;
|
||||
this.saveToStorage("skyart_cart", this.cart);
|
||||
this.updateAllBadges();
|
||||
this.renderCart();
|
||||
// Search
|
||||
const searchInput = document.getElementById("productSearch");
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener(
|
||||
"input",
|
||||
window.Utils.debounce((e) => {
|
||||
this.searchProducts(e.target.value);
|
||||
}, 300)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add to Wishlist
|
||||
addToWishlist(product) {
|
||||
const exists = this.wishlist.find((item) => item.id === product.id);
|
||||
async loadProducts() {
|
||||
if (!this.productsContainer) return;
|
||||
|
||||
if (!exists) {
|
||||
this.wishlist.push({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
price: parseFloat(product.price),
|
||||
imageurl: product.imageurl,
|
||||
addedAt: new Date().toISOString(),
|
||||
try {
|
||||
this.showLoading();
|
||||
const response = await window.API.getProducts();
|
||||
this.products = response.products || response.data || [];
|
||||
this.renderProducts(this.products);
|
||||
this.hideLoading();
|
||||
} catch (error) {
|
||||
console.error("Error loading products:", error);
|
||||
this.showError("Failed to load products. Please try again later.");
|
||||
this.hideLoading();
|
||||
}
|
||||
}
|
||||
|
||||
filterProducts() {
|
||||
let filtered = [...this.products];
|
||||
|
||||
// Filter by category
|
||||
if (this.currentCategory && this.currentCategory !== "all") {
|
||||
filtered = filtered.filter(
|
||||
(p) =>
|
||||
p.category?.toLowerCase() === this.currentCategory.toLowerCase()
|
||||
);
|
||||
}
|
||||
|
||||
// Sort products
|
||||
filtered = this.sortProducts(filtered);
|
||||
|
||||
this.renderProducts(filtered);
|
||||
}
|
||||
|
||||
sortProducts(products) {
|
||||
switch (this.currentSort) {
|
||||
case "price-low":
|
||||
return products.sort((a, b) => (a.price || 0) - (b.price || 0));
|
||||
case "price-high":
|
||||
return products.sort((a, b) => (b.price || 0) - (a.price || 0));
|
||||
case "name":
|
||||
return products.sort((a, b) =>
|
||||
(a.title || a.name || "").localeCompare(b.title || b.name || "")
|
||||
);
|
||||
case "newest":
|
||||
default:
|
||||
return products.sort(
|
||||
(a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
searchProducts(query) {
|
||||
if (!query.trim()) {
|
||||
this.filterProducts();
|
||||
return;
|
||||
}
|
||||
|
||||
const searchTerm = query.toLowerCase();
|
||||
const filtered = this.products.filter((p) => {
|
||||
const title = (p.title || p.name || "").toLowerCase();
|
||||
const description = (p.description || "").toLowerCase();
|
||||
const category = (p.category || "").toLowerCase();
|
||||
|
||||
return (
|
||||
title.includes(searchTerm) ||
|
||||
description.includes(searchTerm) ||
|
||||
category.includes(searchTerm)
|
||||
);
|
||||
});
|
||||
|
||||
this.saveToStorage("skyart_wishlist", this.wishlist);
|
||||
this.updateAllBadges();
|
||||
this.renderWishlist();
|
||||
this.showNotification(`${product.name} added to wishlist!`, "success");
|
||||
} else {
|
||||
this.showNotification("Already in wishlist", "info");
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from Wishlist
|
||||
removeFromWishlist(productId) {
|
||||
this.wishlist = this.wishlist.filter((item) => item.id !== productId);
|
||||
this.saveToStorage("skyart_wishlist", this.wishlist);
|
||||
this.updateAllBadges();
|
||||
this.renderWishlist();
|
||||
this.showNotification("Item removed from wishlist", "info");
|
||||
}
|
||||
|
||||
// Move from Wishlist to Cart
|
||||
moveToCart(productId) {
|
||||
const item = this.wishlist.find((item) => item.id === productId);
|
||||
if (item) {
|
||||
this.addToCart(item, 1);
|
||||
this.removeFromWishlist(productId);
|
||||
}
|
||||
}
|
||||
|
||||
// Update All Badges
|
||||
updateAllBadges() {
|
||||
const cartCount = this.cart.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const wishlistCount = this.wishlist.length;
|
||||
|
||||
const cartBadge = document.getElementById("cartCount");
|
||||
const wishlistBadge = document.getElementById("wishlistCount");
|
||||
|
||||
if (cartBadge) {
|
||||
cartBadge.textContent = cartCount;
|
||||
cartBadge.style.display = cartCount > 0 ? "flex" : "none";
|
||||
this.renderProducts(filtered);
|
||||
}
|
||||
|
||||
if (wishlistBadge) {
|
||||
wishlistBadge.textContent = wishlistCount;
|
||||
wishlistBadge.style.display = wishlistCount > 0 ? "flex" : "none";
|
||||
}
|
||||
}
|
||||
renderProducts(products) {
|
||||
if (!this.productsContainer) return;
|
||||
|
||||
// Render Cart
|
||||
renderCart() {
|
||||
const cartContent = document.getElementById("cartContent");
|
||||
const cartSubtotal = document.getElementById("cartSubtotal");
|
||||
if (products.length === 0) {
|
||||
this.productsContainer.innerHTML = `
|
||||
<div class="no-products">
|
||||
<i class="bi bi-inbox" style="font-size: 48px; opacity: 0.5;"></i>
|
||||
<p>No products found</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!cartContent) return;
|
||||
const html = products
|
||||
.map((product) => this.renderProductCard(product))
|
||||
.join("");
|
||||
this.productsContainer.innerHTML = html;
|
||||
|
||||
if (this.cart.length === 0) {
|
||||
cartContent.innerHTML = '<p class="empty-state">Your cart is empty</p>';
|
||||
if (cartSubtotal) cartSubtotal.textContent = "$0.00";
|
||||
return;
|
||||
// Setup product card listeners
|
||||
this.setupProductListeners();
|
||||
}
|
||||
|
||||
const subtotal = this.cart.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
renderProductCard(product) {
|
||||
const id = product.id;
|
||||
const title = window.Utils?.escapeHtml
|
||||
? window.Utils.escapeHtml(product.title || product.name || "Product")
|
||||
: product.title || product.name || "Product";
|
||||
const price = window.Utils?.formatCurrency
|
||||
? window.Utils.formatCurrency(product.price || 0)
|
||||
: `$${parseFloat(product.price || 0).toFixed(2)}`;
|
||||
|
||||
cartContent.innerHTML = this.cart
|
||||
.map(
|
||||
(item) => `
|
||||
<div class="cart-item" data-product-id="${item.id}">
|
||||
<div class="cart-item-image">
|
||||
<img src="${item.imageurl || "/assets/images/placeholder.jpg"}"
|
||||
alt="${item.name}"
|
||||
onerror="this.src='/assets/images/placeholder.jpg'" />
|
||||
</div>
|
||||
<div class="cart-item-details">
|
||||
<h4 class="cart-item-name">${item.name}</h4>
|
||||
<p class="cart-item-price">$${item.price.toFixed(2)}</p>
|
||||
<div class="cart-item-quantity">
|
||||
<button class="qty-btn" onclick="shoppingManager.updateCartQuantity('${
|
||||
item.id
|
||||
}', ${item.quantity - 1})">
|
||||
<i class="bi bi-dash"></i>
|
||||
</button>
|
||||
<span class="qty-value">${item.quantity}</span>
|
||||
<button class="qty-btn" onclick="shoppingManager.updateCartQuantity('${
|
||||
item.id
|
||||
}', ${item.quantity + 1})">
|
||||
<i class="bi bi-plus"></i>
|
||||
// Get image URL from multiple possible sources
|
||||
let imageUrl = "/assets/images/placeholder.jpg";
|
||||
if (
|
||||
product.images &&
|
||||
Array.isArray(product.images) &&
|
||||
product.images.length > 0
|
||||
) {
|
||||
const primaryImg = product.images.find((img) => img.is_primary);
|
||||
imageUrl = primaryImg
|
||||
? primaryImg.image_url
|
||||
: product.images[0].image_url;
|
||||
} else if (product.imageUrl) {
|
||||
imageUrl = product.imageUrl;
|
||||
} else if (product.image_url) {
|
||||
imageUrl = product.image_url;
|
||||
}
|
||||
|
||||
// Get description
|
||||
const description =
|
||||
product.shortdescription ||
|
||||
(product.description
|
||||
? product.description.substring(0, 100) + "..."
|
||||
: "");
|
||||
|
||||
const isInWishlist = window.AppState?.isInWishlist(id) || false;
|
||||
|
||||
return `
|
||||
<article class="product-card" data-id="${id}">
|
||||
<div class="product-image-wrapper">
|
||||
<img src="${imageUrl}" alt="${title}" class="product-image" loading="lazy" onerror="this.src='/assets/images/placeholder.svg'">
|
||||
<button
|
||||
class="wishlist-btn ${isInWishlist ? "active" : ""}"
|
||||
data-id="${id}"
|
||||
aria-label="${
|
||||
isInWishlist ? "Remove from wishlist" : "Add to wishlist"
|
||||
}"
|
||||
>
|
||||
<i class="bi bi-heart${isInWishlist ? "-fill" : ""}"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="cart-item-actions">
|
||||
<button class="cart-item-remove" onclick="shoppingManager.removeFromCart('${
|
||||
item.id
|
||||
}')" title="Remove">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
<p class="cart-item-total">$${(item.price * item.quantity).toFixed(
|
||||
2
|
||||
)}</p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
<div class="product-info">
|
||||
<a href="/product?id=${id}" style="text-decoration: none; color: inherit;">
|
||||
<h3 class="product-title">${title}</h3>
|
||||
</a>
|
||||
${
|
||||
description
|
||||
? `<div class="product-description">${description}</div>`
|
||||
: ""
|
||||
}
|
||||
<p class="product-price">${price}</p>
|
||||
<div class="product-actions">
|
||||
<button class="btn-add-to-cart" data-id="${id}" style="flex: 1;">
|
||||
<i class="bi bi-cart-plus"></i> Add to Cart
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
||||
if (cartSubtotal) {
|
||||
cartSubtotal.textContent = `$${subtotal.toFixed(2)}`;
|
||||
setupProductListeners() {
|
||||
// Add to cart buttons
|
||||
this.productsContainer
|
||||
.querySelectorAll(".btn-add-to-cart")
|
||||
.forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
const product = this.products.find((p) => p.id === id);
|
||||
if (product) {
|
||||
window.AppState.addToCart(product);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Wishlist buttons
|
||||
this.productsContainer
|
||||
.querySelectorAll(".wishlist-btn")
|
||||
.forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
const id = parseInt(e.currentTarget.dataset.id);
|
||||
const product = this.products.find((p) => p.id === id);
|
||||
if (product) {
|
||||
if (window.AppState.isInWishlist(id)) {
|
||||
window.AppState.removeFromWishlist(id);
|
||||
} else {
|
||||
window.AppState.addToWishlist(product);
|
||||
}
|
||||
this.renderProducts(this.products);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
showLoading() {
|
||||
if (this.loadingIndicator) {
|
||||
this.loadingIndicator.style.display = "flex";
|
||||
}
|
||||
if (this.productsContainer) {
|
||||
this.productsContainer.style.opacity = "0.5";
|
||||
}
|
||||
}
|
||||
|
||||
hideLoading() {
|
||||
if (this.loadingIndicator) {
|
||||
this.loadingIndicator.style.display = "none";
|
||||
}
|
||||
if (this.productsContainer) {
|
||||
this.productsContainer.style.opacity = "1";
|
||||
}
|
||||
}
|
||||
|
||||
showError(message) {
|
||||
if (this.errorContainer) {
|
||||
this.errorContainer.innerHTML = `
|
||||
<div class="error-message" role="alert">
|
||||
<i class="bi bi-exclamation-triangle"></i>
|
||||
<p>${window.Utils.escapeHtml(message)}</p>
|
||||
<button onclick="location.reload()">Retry</button>
|
||||
</div>
|
||||
`;
|
||||
this.errorContainer.style.display = "block";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Render Wishlist
|
||||
renderWishlist() {
|
||||
const wishlistContent = document.getElementById("wishlistContent");
|
||||
|
||||
if (!wishlistContent) return;
|
||||
|
||||
if (this.wishlist.length === 0) {
|
||||
wishlistContent.innerHTML =
|
||||
'<p class="empty-state">Your wishlist is empty</p>';
|
||||
return;
|
||||
// Initialize on shop/products pages
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (
|
||||
window.location.pathname.includes("/shop") ||
|
||||
window.location.pathname.includes("/products")
|
||||
) {
|
||||
new ShoppingPage();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (
|
||||
window.location.pathname.includes("/shop") ||
|
||||
window.location.pathname.includes("/products")
|
||||
) {
|
||||
new ShoppingPage();
|
||||
}
|
||||
|
||||
wishlistContent.innerHTML = this.wishlist
|
||||
.map(
|
||||
(item) => `
|
||||
<div class="wishlist-item" data-product-id="${item.id}">
|
||||
<div class="wishlist-item-image">
|
||||
<img src="${item.imageurl || "/assets/images/placeholder.jpg"}"
|
||||
alt="${item.name}"
|
||||
onerror="this.src='/assets/images/placeholder.jpg'" />
|
||||
</div>
|
||||
<div class="wishlist-item-details">
|
||||
<h4 class="wishlist-item-name">${item.name}</h4>
|
||||
<p class="wishlist-item-price">$${item.price.toFixed(2)}</p>
|
||||
<button class="btn-move-to-cart" onclick="shoppingManager.moveToCart('${
|
||||
item.id
|
||||
}')">
|
||||
<i class="bi bi-cart-plus"></i> Add to Cart
|
||||
</button>
|
||||
</div>
|
||||
<button class="wishlist-item-remove" onclick="shoppingManager.removeFromWishlist('${
|
||||
item.id
|
||||
}')" title="Remove">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
// Show Notification
|
||||
showNotification(message, type = "info") {
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<i class="bi bi-${
|
||||
type === "success" ? "check-circle" : "info-circle"
|
||||
}"></i>
|
||||
<span>${message}</span>
|
||||
`;
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
setTimeout(() => notification.classList.add("show"), 10);
|
||||
setTimeout(() => {
|
||||
notification.classList.remove("show");
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Get Cart Total
|
||||
getCartTotal() {
|
||||
return this.cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||
}
|
||||
|
||||
// Get Cart Count
|
||||
getCartCount() {
|
||||
return this.cart.reduce((sum, item) => sum + item.quantity, 0);
|
||||
}
|
||||
|
||||
// Clear Cart
|
||||
clearCart() {
|
||||
this.cart = [];
|
||||
this.saveToStorage("skyart_cart", this.cart);
|
||||
this.updateAllBadges();
|
||||
this.renderCart();
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize Shopping Manager
|
||||
const shoppingManager = new ShoppingManager();
|
||||
|
||||
// Make it globally available
|
||||
window.shoppingManager = shoppingManager;
|
||||
|
||||
// Navigation active state
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const currentPage = window.location.pathname.split("/").pop() || "home.html";
|
||||
document.querySelectorAll(".nav-link, .mobile-link").forEach((link) => {
|
||||
const linkPage = link.getAttribute("href")?.split("/").pop();
|
||||
if (linkPage === currentPage) {
|
||||
link.classList.add("active");
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
||||
236
website/assets/js/state-manager.js
Normal file
236
website/assets/js/state-manager.js
Normal file
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Global State Management
|
||||
* Centralized state for cart, wishlist, and user preferences
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
class StateManager {
|
||||
constructor() {
|
||||
this.state = {
|
||||
cart: [],
|
||||
wishlist: [],
|
||||
user: null,
|
||||
preferences: {},
|
||||
};
|
||||
this.listeners = {};
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.loadFromStorage();
|
||||
this.setupStorageSync();
|
||||
}
|
||||
|
||||
loadFromStorage() {
|
||||
try {
|
||||
this.state.cart = JSON.parse(localStorage.getItem("cart") || "[]");
|
||||
this.state.wishlist = JSON.parse(
|
||||
localStorage.getItem("wishlist") || "[]"
|
||||
);
|
||||
this.state.preferences = JSON.parse(
|
||||
localStorage.getItem("preferences") || "{}"
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("State load error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
saveToStorage() {
|
||||
try {
|
||||
localStorage.setItem("cart", JSON.stringify(this.state.cart));
|
||||
localStorage.setItem("wishlist", JSON.stringify(this.state.wishlist));
|
||||
localStorage.setItem(
|
||||
"preferences",
|
||||
JSON.stringify(this.state.preferences)
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("State save error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
setupStorageSync() {
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === "cart" || e.key === "wishlist") {
|
||||
this.loadFromStorage();
|
||||
this.emit("stateChanged", { key: e.key });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cart methods
|
||||
addToCart(product, quantity = 1) {
|
||||
const existing = this.state.cart.find((item) => item.id === product.id);
|
||||
|
||||
if (existing) {
|
||||
existing.quantity += quantity;
|
||||
} else {
|
||||
this.state.cart.push({
|
||||
...product,
|
||||
quantity,
|
||||
addedAt: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
removeFromCart(productId) {
|
||||
this.state.cart = this.state.cart.filter((item) => item.id !== productId);
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
updateCartQuantity(productId, quantity) {
|
||||
const item = this.state.cart.find((item) => item.id === productId);
|
||||
if (item) {
|
||||
item.quantity = Math.max(0, quantity);
|
||||
if (item.quantity === 0) {
|
||||
return this.removeFromCart(productId);
|
||||
}
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
}
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
getCart() {
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
getCartTotal() {
|
||||
return this.state.cart.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
getCartCount() {
|
||||
return this.state.cart.reduce((sum, item) => sum + item.quantity, 0);
|
||||
}
|
||||
|
||||
clearCart() {
|
||||
this.state.cart = [];
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
}
|
||||
|
||||
// Wishlist methods
|
||||
addToWishlist(product) {
|
||||
const exists = this.state.wishlist.find((item) => item.id === product.id);
|
||||
|
||||
if (!exists) {
|
||||
this.state.wishlist.push({
|
||||
...product,
|
||||
addedAt: Date.now(),
|
||||
});
|
||||
this.saveToStorage();
|
||||
this.emit("wishlistUpdated", this.state.wishlist);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
removeFromWishlist(productId) {
|
||||
this.state.wishlist = this.state.wishlist.filter(
|
||||
(item) => item.id !== productId
|
||||
);
|
||||
this.saveToStorage();
|
||||
this.emit("wishlistUpdated", this.state.wishlist);
|
||||
return this.state.wishlist;
|
||||
}
|
||||
|
||||
getWishlist() {
|
||||
return this.state.wishlist;
|
||||
}
|
||||
|
||||
isInWishlist(productId) {
|
||||
return this.state.wishlist.some((item) => item.id === productId);
|
||||
}
|
||||
|
||||
// Event system
|
||||
on(event, callback) {
|
||||
if (!this.listeners[event]) {
|
||||
this.listeners[event] = [];
|
||||
}
|
||||
this.listeners[event].push(callback);
|
||||
}
|
||||
|
||||
off(event, callback) {
|
||||
if (this.listeners[event]) {
|
||||
this.listeners[event] = this.listeners[event].filter(
|
||||
(cb) => cb !== callback
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
emit(event, data) {
|
||||
if (this.listeners[event]) {
|
||||
this.listeners[event].forEach((callback) => {
|
||||
try {
|
||||
callback(data);
|
||||
} catch (e) {
|
||||
console.error(`Error in ${event} listener:`, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create global instance
|
||||
window.StateManager = window.StateManager || new StateManager();
|
||||
|
||||
// Expose helper functions for backward compatibility
|
||||
window.addToCart = function (productId, name, price, imageurl) {
|
||||
const product = { id: productId, name, price: parseFloat(price), imageurl };
|
||||
window.StateManager.addToCart(product, 1);
|
||||
if (window.showNotification) {
|
||||
window.showNotification(`${name} added to cart!`, "success");
|
||||
}
|
||||
};
|
||||
|
||||
window.addToWishlist = function (productId, name, price, imageurl) {
|
||||
const product = { id: productId, name, price: parseFloat(price), imageurl };
|
||||
const added = window.StateManager.addToWishlist(product);
|
||||
if (window.showNotification) {
|
||||
window.showNotification(
|
||||
added ? `${name} added to wishlist!` : "Already in wishlist!",
|
||||
added ? "success" : "info"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Update badges on state changes
|
||||
window.StateManager.on("cartUpdated", () => {
|
||||
const badge = document.querySelector(".cart-badge");
|
||||
if (badge) {
|
||||
const count = window.StateManager.getCartCount();
|
||||
badge.textContent = count;
|
||||
badge.style.display = count > 0 ? "flex" : "none";
|
||||
}
|
||||
});
|
||||
|
||||
window.StateManager.on("wishlistUpdated", () => {
|
||||
const badge = document.querySelector(".wishlist-badge");
|
||||
if (badge) {
|
||||
const count = window.StateManager.getWishlist().length;
|
||||
badge.textContent = count;
|
||||
badge.style.display = count > 0 ? "flex" : "none";
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize badges
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
window.StateManager.emit("cartUpdated");
|
||||
window.StateManager.emit("wishlistUpdated");
|
||||
});
|
||||
} else {
|
||||
window.StateManager.emit("cartUpdated");
|
||||
window.StateManager.emit("wishlistUpdated");
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user