-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.html
More file actions
416 lines (383 loc) · 15.8 KB
/
Copy pathuser.html
File metadata and controls
416 lines (383 loc) · 15.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Speechdeb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js"></script>
<script>
const SUPABASE_URL = "https://tdaykujyicpvokrkryea.supabase.co";
const SUPABASE_KEY = "sb_publishable_m_eAW0KQTU_GYz0KhsLIbw_ltdhysCv";
const supabaseClient = supabase.createClient(SUPABASE_URL, SUPABASE_KEY);
</script>
<style>
.profile-box { display: flex; gap: 20px; align-items: flex-start; padding: 20px; background: #f5f5f5; border-bottom: 1px solid #ccc; }
#avatarSection { display: flex; flex-direction: column; align-items: center; }
#profilePic { width: 100px; height: 100px; object-fit: cover; border-radius: 50%; cursor: pointer; }
.profileField { margin-bottom: 10px; }
textarea { width: 100%; height: 60px; }
</style>
<style>
#contentRow { display: flex; align-items: flex-start; gap: 20px; }
#filterSidebar { flex: 0 0 20%; min-width: 180px; max-width: 220px; background: #f9f9f9; padding: 15px 20px; border: 1px solid #ccc; box-shadow: 0 1px 4px rgba(0,0,0,0.05); }
#categoryFilters div { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
#menuView { flex: 1; }
.filterSection { margin-top: 20px; }
#filterHeader { display: flex; justify-content: space-between; align-items: center; }
#filterHeader a { font-size: 0.9em; color: #007bff; text-decoration: none; cursor: pointer; }
#filterHeader a:hover { text-decoration: underline; }
</style>
</head>
<body>
<script>
let activeSort = 'title';
let activeCategories = [];
let originalSpeechBoxes = [];
function updateSpeechDisplay() {
const menu = document.getElementById("menuView");
if (!menu) return;
menu.innerHTML = "";
let filtered = [...originalSpeechBoxes];
if (activeCategories.length > 0) {
filtered = filtered.filter(box => activeCategories.includes(box.getAttribute("data-category")));
}
filtered.sort((a, b) => {
if (activeSort === 'title') {
return a.getAttribute("data-title").localeCompare(b.getAttribute("data-title"));
} else {
return new Date(b.getAttribute("data-updated")) - new Date(a.getAttribute("data-updated"));
}
});
filtered.forEach(box => menu.appendChild(box));
const label = activeCategories.length > 0 ? activeCategories.join(", ") : "None";
document.getElementById("activeFilters").textContent = `Filters: ${label}`;
}
function initializeFilters(speechData) {
const container = document.getElementById("categoryFilters");
const categories = [...new Set(speechData.map(s => s.category).filter(Boolean))].sort();
if (container) container.innerHTML = "";
categories.forEach(cat => {
const id = `filter-${cat.replace(/\s+/g, '-')}`;
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = id;
checkbox.value = cat;
checkbox.onchange = () => {
if (checkbox.checked) activeCategories.push(cat);
else activeCategories = activeCategories.filter(c => c !== cat);
updateSpeechDisplay();
};
const label = document.createElement("label");
label.htmlFor = id;
label.textContent = cat;
const wrapper = document.createElement("div");
wrapper.style.display = "flex";
wrapper.style.alignItems = "center";
wrapper.style.gap = "8px";
wrapper.style.marginBottom = "6px";
wrapper.appendChild(checkbox);
wrapper.appendChild(label);
if (container) container.appendChild(wrapper);
});
document.querySelectorAll("input[name='sortOption']").forEach(radio => {
radio.onchange = () => {
activeSort = radio.value;
updateSpeechDisplay();
};
});
document.getElementById("clearFilters").onclick = (e) => {
e.preventDefault();
activeCategories = [];
document.querySelectorAll("#categoryFilters input[type='checkbox']").forEach(cb => cb.checked = false);
updateSpeechDisplay();
};
}
</script>
<div id="mainContainer">
<div id="profileBox" class="profile-box">
<div id="avatarSection">
<div style="position: relative; width: 100px; height: 100px;">
<img id="profilePic" src="favicon.png"
alt="Profile Picture"
style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;"
onerror="this.onerror=null; this.src='favicon.png';" />
<input type="file" id="uploadAvatar" accept="image/*"
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;
opacity: 0; cursor: pointer; z-index: 10;" />
</div>
</div>
<div id="profileInfo">
<div class="profileField">
<label>Name:</label>
<input type="text" id="profileName" />
</div>
<div class="profileField">
<label>Bio:</label>
<textarea id="profileBio"></textarea>
</div>
<div class="profileField">
<label>Role:</label>
<select id="profileRole">
<option value="student">Student</option>
<option value="coach">Coach</option>
<option value="judge">Judge</option>
</select>
</div>
<button id="saveProfileBtn">Save Changes</button>
</div>
</div>
<br><br>
<div id="contentRow">
<div id="filterSidebar">
<div id="filterHeader">
<strong id="activeFilters">Filters: None</strong> <a href="#" id="clearFilters">(Clear)</a>
</div>
<div class="filterSection">
<h4>Sort</h4>
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
<input type="radio" name="sortOption" value="title" checked />
<label for="sort-title">Title (A–Z)</label>
</div>
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
<input type="radio" name="sortOption" value="recent" />
<label for="sort-recent">Recent</label>
</div>
</div>
<div class="filterSection">
<h4>Filters</h4>
<div id="categoryFilters"></div>
</div>
</div>
<div style="flex: 1;">
<div id="menuView"></div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", async () => {
const params = new URLSearchParams(window.location.search);
const isGuest = params.get("guest") === "1" || localStorage.getItem("speechdeb_guest") === "1";
const pic = document.getElementById("profilePic");
const nameEl = document.getElementById("profileName");
const bioEl = document.getElementById("profileBio");
const roleEl = document.getElementById("profileRole");
const saveBtn = document.getElementById("saveProfileBtn");
const uploadInp = document.getElementById("uploadAvatar");
// === Guest-mode speech storage ===
const GUEST_STORAGE_KEY = "speechdeb_guest_speeches";
function getGuestSpeeches() {
try {
const raw = localStorage.getItem(GUEST_STORAGE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
console.warn("Failed to parse guest speeches from localStorage:", e);
return [];
}
}
function setGuestSpeeches(list) {
try {
localStorage.setItem(GUEST_STORAGE_KEY, JSON.stringify(list || []));
} catch (e) {
console.warn("Failed to save guest speeches to localStorage:", e);
}
}
function ensureGuestNewSpeechButton() {
let btn = document.getElementById("newSpeechBtn");
const menuContainer = document.getElementById("menuView");
if (!menuContainer) { console.warn("Guest menu: #menuView not found."); return; }
if (!btn) {
btn = document.createElement("button");
btn.id = "newSpeechBtn";
btn.textContent = "New Speech";
btn.className = "primaryButton";
if (menuContainer.parentNode) {
menuContainer.parentNode.insertBefore(btn, menuContainer);
} else {
menuContainer.prepend(btn);
}
}
btn.style.display = "block";
btn.style.margin = "0 auto 15px auto";
btn.style.textAlign = "center";
btn.onclick = () => {
const speeches = getGuestSpeeches();
const newId = Date.now();
const newSpeech = { id: newId, title: "Untitled Speech", category: "Uncategorized", updated_at: new Date().toISOString() };
speeches.push(newSpeech);
setGuestSpeeches(speeches);
try {
localStorage.setItem("speechdeb_editor_payload", JSON.stringify({
id: newId, title: newSpeech.title, category: newSpeech.category, content: "", guest: true
}));
} catch (e) { console.warn("Failed to set editor payload for guest:", e); }
window.location.href = "editor.html?guest=1";
};
}
function loadGuestSpeeches() {
const menu = document.getElementById("menuView");
if (!menu) { console.warn("Guest menu: #menuView not found."); return; }
menu.innerHTML = "";
ensureGuestNewSpeechButton();
const speeches = getGuestSpeeches();
if (!speeches.length) {
const emptyMsg = document.createElement("div");
emptyMsg.id = "noSpeechesMessage";
emptyMsg.textContent = "No speeches yet in Guest Mode. Click “New Speech” to get started.";
emptyMsg.style = "margin-top: 20px; font-size: 20px; color: #666; text-align: center;";
menu.appendChild(emptyMsg);
return;
}
speeches.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at)).forEach(s => {
const box = document.createElement("div");
box.className = "speechBox";
const lastUpdated = s.updated_at || new Date().toISOString();
const category = s.category || "Uncategorized";
const title = s.title || "Untitled Speech";
box.setAttribute("data-category", category);
box.setAttribute("data-title", title);
box.setAttribute("data-updated", lastUpdated);
box.style = `background-color: #f9f9f9; border: 1px solid #ccc; border-radius: 10px; padding: 14px 20px; margin: 10px auto; max-width: 70%; cursor: pointer;`;
const relative = (typeof formatRelativeTime === "function") ? formatRelativeTime(lastUpdated) : new Date(lastUpdated).toLocaleString();
box.innerHTML = `
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<div style="font-weight: bold; font-size: 18px;">[${category}] ${title}</div>
<div style="color: #666; font-size: 14px;">Last edited ${relative}</div>
</div>
<button class="deleteBtn" style="margin-left: 20px; background-color: #cc0000; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer;">Delete</button>
</div>`;
const deleteBtn = box.querySelector(".deleteBtn");
if (deleteBtn) {
deleteBtn.onclick = (e) => {
e.stopPropagation();
if (!confirm(`Delete your ${category} speech “${title}”? This cannot be undone.`)) return;
const all = getGuestSpeeches();
const remaining = all.filter(sp => sp.id !== s.id);
setGuestSpeeches(remaining);
loadGuestSpeeches();
};
}
box.onclick = () => {
try {
localStorage.setItem("speechdeb_editor_payload", JSON.stringify({
id: s.id, title: s.title || "", category: s.category || "Uncategorized", content: s.content || "", guest: true
}));
} catch (e) { console.warn("Failed to set editor payload for guest:", e); }
window.location.href = "editor.html?guest=1";
};
menu.appendChild(box);
});
}
// 🔹 GUEST MODE
if (isGuest) {
if (pic) { pic.src = "favicon.png"; pic.style.cursor = "default"; }
if (nameEl) { nameEl.value = "Guest"; nameEl.readOnly = true; }
if (bioEl) { bioEl.value = "Browse and edit speeches in Guest mode (stored locally on this device)."; bioEl.readOnly = true; }
if (roleEl) { roleEl.value = "student"; roleEl.disabled = true; }
if (saveBtn) saveBtn.style.display = "none";
if (uploadInp) uploadInp.style.display = "none";
const bannerPic = document.getElementById("userAvatarDisplay");
const bannerName = document.getElementById("userNameDisplay");
if (bannerPic) bannerPic.src = "favicon.png";
if (bannerName) bannerName.textContent = "Guest";
if (typeof loadGuestSpeeches === "function") {
try { loadGuestSpeeches(); } catch (e) { console.warn("loadGuestSpeeches guest call failed:", e); }
}
return;
}
// 🔹 NORMAL (LOGGED-IN) PROFILE FLOW — real Supabase session + data
const { data: sessionData } = await supabaseClient.auth.getSession();
const currentUser = sessionData?.session?.user;
if (!currentUser) {
// Not logged in and not guest -> send to login
window.location.href = "login.html";
return;
}
const profileId = params.get("id") || currentUser.id;
const isOwner = profileId === currentUser.id;
try {
const { data, error } = await supabaseClient
.from("profiles")
.select("*")
.eq("id", profileId)
.single();
if (error) throw error;
if (pic) {
pic.src = data.profile_picture_url || "favicon.png";
}
if (isOwner) {
nameEl.value = data.name || "";
bioEl.value = data.bio || "";
roleEl.value = data.role || "student";
pic.addEventListener("click", () => uploadInp.click());
let uploadedPicUrl = null;
uploadInp.addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file || !file.type.startsWith("image/")) return;
const filePath = `${currentUser.id}/${Date.now()}_${file.name}`;
const { error: uploadError } = await supabaseClient
.storage
.from("avatars")
.upload(filePath, file, { upsert: true });
if (uploadError) {
alert("Avatar upload failed: " + uploadError.message);
return;
}
const { data: urlData } = supabaseClient
.storage
.from("avatars")
.getPublicUrl(filePath);
uploadedPicUrl = urlData.publicUrl;
pic.src = uploadedPicUrl + "?t=" + Date.now();
const bannerPic = document.getElementById("userAvatarDisplay");
if (bannerPic) bannerPic.src = uploadedPicUrl + "?t=" + Date.now();
});
saveBtn.addEventListener("click", async () => {
const name = nameEl.value.trim();
const bio = bioEl.value.trim();
const role = roleEl.value;
const { error: updateError } = await supabaseClient
.from("profiles")
.update({
name,
bio,
role,
profile_picture_url: uploadedPicUrl || data.profile_picture_url || null
})
.eq("id", currentUser.id);
if (updateError) {
alert(updateError.message || "Update failed.");
} else {
location.reload();
}
});
} else {
// Viewing someone else's profile — view-only
nameEl.value = data.name || "(Unnamed)";
nameEl.readOnly = true;
bioEl.value = data.bio || "";
bioEl.readOnly = true;
roleEl.value = data.role || "student";
roleEl.disabled = true;
saveBtn.style.display = "none";
uploadInp.style.display = "none";
if (pic) pic.style.cursor = "default";
}
// NOTE: loadSpeechesFromServer() still needs to be rebuilt against
// Supabase's `speeches` table — that's the next file in the queue
// (load_speeches.php).
if (typeof loadSpeechesFromServer === "function") {
loadSpeechesFromServer(profileId, isOwner);
}
} catch (err) {
console.error("Profile load error:", err);
document.getElementById("profileBox").innerHTML =
`<p>Failed to load profile.</p><pre>${err.message}</pre>`;
}
});
</script>
<script type="module" src="common.js"></script>
</body>
</html>