-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
480 lines (410 loc) · 13.8 KB
/
script.js
File metadata and controls
480 lines (410 loc) · 13.8 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
'use strict';
// prettier-ignore
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/* UTILITY FUNCTIONS */
function capitalizeWords(str) {
return str
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
function formatSpotType(str) {
if (!str) return '';
return str
.split('-') // split on dashes
.map(word => word.charAt(0).toUpperCase() + word.slice(1)) // capitalize each
.join(' '); // rejoin with spaces
}
const formatDate = date => {
return `${date.getDate()} ${monthNames[date.getMonth()].substring(
0,
3
)} ${date.getFullYear()}`;
};
// prettier-ignore
function popupHTML(studySession) {
// prettier-ignore
const formatType = s =>
s
.split('-')
.map(w => w[0].toUpperCase() + w.slice(1))
.join(' ');
// prettier-ignore
const esc = s =>
String(s ?? '').replace(
/[&<>"']/g,
m =>
({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
}[m])
);
return `
<div class="popup">
<div class="popup__top">
<span class="popup__badge popup__badge--${studySession.type}">${formatType(
studySession.type
)}</span>
<span class="popup__date">
${formatDate(studySession.date)}
</span>
</div>
<div class="popup__loc">
<span>${esc(
studySession.location ||
`Near ${studySession.coords[0].toFixed(5)}, ${studySession.coords[1].toFixed(
5
)}`
)}</span>
</div>
</div>`;
}
/**
* Build the nicest possible location string from a geocoder response.
* Works even when there is no street address (like lakes, forests, etc.).
*/
function prettyLocationFromGeo(data, lat, lng) {
// --- inline utils ---
const pick = (...vals) =>
vals.find(v => typeof v === 'string' && v.trim())?.trim();
const asText = v =>
typeof v === 'string'
? v
: v && typeof v === 'object' && typeof v.name === 'string'
? v.name
: '';
const titleCase = s =>
s
.split(/[\s-]+/)
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
const latlngText = (lat, lng) => `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
// --- extract values safely ---
const stnumber = pick(data.stnumber, data.standard?.stnumber);
const staddress = pick(
data.staddress,
data.standard?.staddress,
data.standard?.addresst
);
const city = pick(data.city, asText(data.standard?.city));
const county = pick(data.county, asText(data.standard?.county));
const region = pick(
data.region,
data.state,
data.prov,
asText(data.standard?.region),
asText(data.standard?.state)
);
const country = pick(
data.country,
asText(data.standard?.countryname),
asText(data.standard?.country)
);
const postal = pick(data.postal, data.standard?.postal);
const poi = pick(
asText(data.osmtags?.name),
asText(data.standard?.addresst), // sometimes a feature name
asText(data.alt?.loc?.title)
);
// --- choose the nicest fallback ---
if (staddress && stnumber)
return titleCase(
`${stnumber} ${staddress}, ${pick(city, region, country) || ''}${
postal ? ' ' + postal : ''
}`.trim()
);
if (staddress)
return titleCase(
`${staddress}, ${pick(city, region, country) || ''}`.trim()
);
if (poi && (city || region || country))
return titleCase(`${poi}, ${pick(city, region, country)}`);
if (city && (region || country))
return titleCase(`${city}, ${pick(region, country)}`);
if (region && country) return titleCase(`${region}, ${country}`);
if (country) return titleCase(country);
return `Near ${latlngText(lat, lng)}`;
}
class StudySession {
date = new Date();
id = (Date.now() + '').slice(-10);
constructor(coords) {
this.coords = coords;
}
async setLocation(coords) {
const [lat, lng] = coords;
const apiKey = '225012544721267652909x73918';
try {
const res = await fetch(
`https://geocode.xyz/${lat},${lng}?geoit=json&auth=${apiKey}`
);
const data = await res.json();
this.location = prettyLocationFromGeo(data, lat, lng); // <-- single path
if (!this.location)
this.location = `Near ${lat.toFixed(5)}, ${lng.toFixed(5)}`;
} catch {
this.location = `Near ${lat.toFixed(5)}, ${lng.toFixed(5)}`;
}
}
}
// StudySpot DOM hooks
const form = document.querySelector('.form');
const inputType = document.querySelector('.form__input--type');
const inputNoiseLevel = document.querySelector('.form__input--noise');
const inputFocusLevel = document.querySelector('.form__input--focus');
const inputPowerOutlet = document.querySelector('.form__input--outlet');
const inputFoodAllowed = document.querySelector('.form__input--food');
const inputRating = document.querySelectorAll('.stars input[name="rating"]');
const inputNotes = document.querySelector('.form__input--notes');
const spots = document.querySelector('.spots');
const noCardsMessage = document.querySelector('.no-cards');
const spotCard = document.querySelector('.spot-card');
class App {
#map;
#mapZoomLevel = 13;
#mapEvent;
#studySessions = [];
constructor() {
// Get user's positions
this._getPosition();
// Get data from local storage
this._getLocalStorage();
// Attach event handlers
form.addEventListener('submit', this._newStudySession.bind(this));
spots.addEventListener('click', this._moveToPopup.bind(this));
}
_getPosition() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(
this._loadMap.bind(this),
function () {
alert('Could not get your position !');
}
);
}
_loadMap(position) {
const { latitude } = position.coords;
const { longitude } = position.coords;
console.log(`https://www.google.pt/maps/@${latitude},${longitude}`);
const coords = [latitude, longitude];
this.#map = L.map('map').setView(coords, this.#mapZoomLevel);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(this.#map);
// Handling clicks on map
this.#map.on('click', this._clickMapEffect.bind(this));
this.#studySessions.forEach(studySession => {
this._renderStudySessionMarker(studySession);
});
}
_clickMapEffect(mapE) {
this.#mapEvent = mapE;
// Showing Form
form.classList.remove('hidden');
inputType.focus();
}
async _newStudySession(e) {
e.preventDefault();
// Require a map click first
if (!this.#mapEvent) {
alert('Click on the map to pick a spot first.');
return;
}
// Helper validators
const validNums = (...vals) => vals.every(v => Number.isFinite(v));
const allPositive = (...vals) => vals.every(v => v >= 0);
// Coordinates from last map click
const { lat, lng } = this.#mapEvent.latlng;
// Read form values
const type = inputType.value;
const noise = +inputNoiseLevel.value;
const focus = +inputFocusLevel.value; // 0–100 expected
const outlet = +inputPowerOutlet.value;
const foodIsAllowed = inputFoodAllowed.checked;
const ratingEl = document.querySelector(
'.stars input[name="rating"]:checked'
);
const rating = ratingEl ? +ratingEl.value : null; // 1–5 or null
const notes = inputNotes.value.trim();
// Validate numeric fields
if (!validNums(noise, focus, outlet) || !allPositive(noise, focus, outlet))
return alert('Inputs have to be positive numbers !');
// Create & store session
const studySession = new StudySession([lat, lng]);
studySession.type = type;
studySession.noise = noise;
studySession.focus = focus;
studySession.outlet = outlet;
studySession.foodIsAllowed = foodIsAllowed;
studySession.rating = rating;
studySession.notes = notes;
// wait for reverse geocode BEFORE rendering
await studySession.setLocation([lat, lng]);
this.#studySessions.push(studySession);
// Render Study Session on map as a marker
this._renderStudySessionMarker(studySession);
// Render Study Session as a card
this._renderStudySessionCard(studySession);
// Clear the form
inputType.value = '';
inputNoiseLevel.value = '';
inputFocusLevel.value = '';
inputPowerOutlet.value = '';
inputFoodAllowed.checked = false;
document.querySelectorAll('.stars input[name="rating"]').forEach(r => {
r.checked = false;
});
inputNotes.value = '';
// Set Local Storagr to all Study Sessions
this._setLocalStorage();
}
_renderStudySessionMarker(studySession) {
L.marker(studySession.coords)
.addTo(this.#map)
.bindPopup(
L.popup({
maxWidth: 260,
minWidth: 180,
autoClose: false,
closeOnClick: false,
className: `${studySession.type}-popup`, // keeps your colored left border
})
)
.setPopupContent(popupHTML(studySession))
.openPopup();
}
_renderStudySessionCard(studySession) {
noCardsMessage.textContent = '';
let html = `<article class="spot-card is-${
studySession.type
}" data-id="${String(studySession.id)}">
<div class="spot-card__media">
<img
src="./images/${studySession.type}.jpg"
alt="Study spot preview"
/>
</div>
<div class="spot-card__body">
<!-- badge + meta -->
<div class="spot-card__top">
<span class="spot-card__badge" data-type="${
studySession.type
}">${formatSpotType(studySession.type)}</span>
<span class="spot-card__meta">Added ${formatDate(
studySession.date
)} </span>
</div>
<!-- title (location) -->
<h3 class="spot-card__title">${studySession.location}</h3>
<!-- note -->
<p class="spot-card__note">
${studySession.notes}
</p>
<!-- 2×2 specs -->
<ul class="spot-card__specs">
<li class="spec">
<span class="spec__icon" aria-hidden="true">
<!-- noise icon -->
<svg viewBox="0 0 24 24">
<path
d="M4 10v4h3l4 4V6L7 10H4zm9.5 2a3.5 3.5 0 0 0-1.5-2.9v5.8A3.5 3.5 0 0 0 13.5 12zm3 0c0-2.7-1.5-5-3.5-6.2v2c1 1 1.5 2.4 1.5 4.2s-.5 3.2-1.5 4.2v2c2-1.2 3.5-3.5 3.5-6.2z"
/>
</svg>
</span>
<span class="spec__label">Noise</span>
<span class="spec__value">${studySession.noise} / 10</span>
</li>
<li class="spec">
<span class="spec__icon" aria-hidden="true">
<!-- focus icon -->
<svg viewBox="0 0 24 24">
<path
d="M12 7a5 5 0 1 0 5 5h2a7 7 0 1 1-7-7v2zm1-5h-2v6h2V2z"
/>
</svg>
</span>
<span class="spec__label">Focus</span>
<span class="spec__value">${studySession.focus}%</span>
</li>
<li class="spec">
<span class="spec__icon" aria-hidden="true">
<!-- outlets icon -->
<svg viewBox="0 0 24 24">
<path
d="M7 2h10a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V5a3 3 0 0 1 3-3zm2 4v6h2V6H9zm4 0v6h2V6h-2zm-2 10v2h4v-2h-4z"
/>
</svg>
</span>
<span class="spec__label">Outlets</span>
<span class="spec__value">${studySession.outlet} / 10</span>
</li>
<li class="spec">
<span class="spec__icon" aria-hidden="true">
<!-- food icon -->
<svg viewBox="0 0 24 24">
<path
d="M7 2v11a3 3 0 0 0 6 0V2h-2v6H9V2H7zm9 4h2v14h-2V6z"
/>
</svg>
</span>
<span class="spec__label">Food/Drinks</span>
<span class="spec__value">${
studySession.foodIsAllowed ? 'Allowed' : 'Restricted'
} </span>
</li>
</ul>
<!-- rating -->
<div class="spot-card__footer">
<div class="rating" aria-label="Rating:${
studySession.rating
} out of 5">
<span class="rating__stars" data-value="${
studySession.rating
}">★★★★★</span>
<span class="rating__value">${studySession.rating}.0</span>
</div>
</div>
</div>
</article>`;
spots.insertAdjacentHTML('beforeend', html);
}
_moveToPopup(e) {
const cardEl = e.target.closest('.spot-card');
if (!cardEl) return;
const targetId = cardEl.getAttribute('data-id')?.trim();
const studySession = this.#studySessions.find(
s => String(s.id) === targetId
);
this.#map.setView(studySession.coords, this.#mapZoomLevel, {
animate: true,
pan: {
duration: 1,
},
});
}
_setLocalStorage() {
localStorage.setItem('studySessions', JSON.stringify(this.#studySessions));
}
_getLocalStorage() {
const data = localStorage.getItem('studySessions');
if (!data) return;
this.#studySessions = JSON.parse(data).map(obj => {
// restore Date + prototype
const session = Object.assign(new StudySession(obj.coords), obj);
session.date = new Date(obj.date); // rehydrate date string to Date
return session;
});
this.#studySessions.forEach(studySession => {
this._renderStudySessionCard(studySession);
});
}
reset() {
localStorage.removeItem('studySessions');
location.reload();
}
}
const app = new App();