-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
163 lines (138 loc) · 5.75 KB
/
main.js
File metadata and controls
163 lines (138 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// main.js
// Sample data structure for listings
let listings = [];
async function getDataFromAPI() {
try {
// Fetch data from API
const response = await fetch('http://127.0.0.1:3000');
if (!response.ok) throw new Error("Failed to fetch data");
// Store fetched data in the listings array
listings = await response.json();
console.log("Fetched Listings:", listings);
//e the UI with new data
displayListings(listings.reverse());
} catch (error) {
console.error("Error:", error);
}
}
getDataFromAPI();
async function addListingToAPI(newListing) {
console.log(`$newListing`, newListing);
try {
const response = await fetch('http://127.0.0.1:3000/add', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newListing)
});
if (!response.ok) throw new Error("❌ ERROR IN SERVER");
const result = await response.json();
console.log("✅", result);
getDataFromAPI();
} catch (error) {
console.error("❌ ERROR", error);
}
}
// Theme Management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
// DOM Elements
const listingsContainer = document.getElementById('listings');
const addListingBtn = document.getElementById('addListingBtn');
const modal = document.getElementById('addListingModal');
const listingForm = document.getElementById('listingForm');
const themeToggle = document.getElementById('themeToggle');
// Event Listeners
addListingBtn.addEventListener('click', () => modal.style.display = 'block');
themeToggle.addEventListener('click', toggleTheme);
window.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
listingForm.addEventListener('submit', (e) => {
e.preventDefault();
addListing();
});
// Functions
function closeModal() {
modal.style.display = 'none';
listingForm.reset();
}
function checkCategory(category) {
const categoryImages = {
books: 'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?w=500',
tech: 'https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=500',
clothing: 'https://images.pexels.com/photos/298863/pexels-photo-298863.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
accessories: 'https://images.unsplash.com/3/www.madebyvadim.com.jpg?q=80&w=2082&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',
services: 'https://images.unsplash.com/photo-1521791136064-7986c2920216?q=80&w=2069&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'
};
return categoryImages[category.toLowerCase()]
|| 'https://images.unsplash.com/photo-1663465374413-83cba00bff6f?q=80&w=2080&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D';
}
function validateImage(url, fallbackUrl) {
return new Promise((resolve) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(url);
img.onerror = () => resolve(fallbackUrl);
});
}
function addListing() {
const userImageUrl = document.getElementById('imageUrl').value;
const fallbackImage = checkCategory(document.getElementById('listingCategory').value);
validateImage(userImageUrl, fallbackImage).then((validImageUrl) => {
const newListing = {
title: document.getElementById('title').value,
category: document.getElementById('listingCategory').value,
price: parseFloat(document.getElementById('price').value),
description: document.getElementById('description').value,
imageUrl: validImageUrl,
intra: document.getElementById('intra').value
};
addListingToAPI(newListing);
closeModal();
displayListings(listings.reverse());
}).catch(error => console.error("error", error));
}
function filterListings() {
const searchTerm = document.getElementById('search').value.toLowerCase();
const category = document.getElementById('category').value;
const filtered = listings.filter(listing => {
const matchesSearch = listing.title.toLowerCase().includes(searchTerm) ||
listing.description.toLowerCase().includes(searchTerm);
const matchesCategory = category === '' || listing.category === category;
return matchesSearch && matchesCategory;
});
displayListings(filtered)
}
function displayListings(listingsToShow) {
listingsContainer.innerHTML = listingsToShow.map(listing => `
<div class="listing-card">
<img src="${listing.imageUrl}" alt="${listing.title}" class="listing-image">
<div class="listing-details">
<h3 class="listing-title">${listing.title}</h3>
<p class="listing-price">${listing.price} MAD</p>
<p class="listing-description">${listing.description}</p>
<button onclick="contactSeller('${listing.intra}')" class="primary-btn" style="margin-bottom: 20px;">
See Seller's Profile
</button>
</div>
</div>
`).join('');
}
function contactSeller(intra) {
window.open(`https://profile.intra.42.fr/users/${intra}`);
}
// Initialize theme and listings
initTheme();
displayListings(listings.reverse);