-
Notifications
You must be signed in to change notification settings - Fork 0
/
supa4dir.html
568 lines (494 loc) · 23.1 KB
/
supa4dir.html
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ApproVideo Aug 2024</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<style>
:root {
--bg-light: #f0f4f8;
--text-light: #2d3748;
--card-bg-light: #ffffff;
--card-text-light: #4a5568;
--bg-dark: #1a202c;
--text-dark: #e2e8f0;
--card-bg-dark: #2d3748;
--card-text-dark: #e2e8f0;
}
body {
transition: background-color 0.3s, color 0.3s;
}
body.light {
background-color: var(--bg-light);
color: var(--text-light);
}
body.dark {
background-color: var(--bg-dark);
color: var(--text-dark);
}
.header {
background: linear-gradient(45deg, #4CAF50, #2196F3);
padding: 20px;
text-align: center;
color: white;
font-size: 2.5rem;
font-weight: bold;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}
.subheader {
font-size: 1.2rem;
margin-top: 10px;
}
.video-card {
background-color: var(--card-bg-light);
color: var(--card-text-light);
transition: background-color 0.3s, color 0.3s;
}
body.dark .video-card {
background-color: var(--card-bg-dark);
color: var(--card-text-dark);
}
.theme-toggle {
position: fixed;
top: 20px;
right: 20px;
z-index: 1000;
background-color: rgba(255, 255, 255, 0.8);
border-radius: 50%;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
body.dark .theme-toggle {
background-color: rgba(0, 0, 0, 0.5);
}
.panel-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
margin-top: 2rem;
}
.info-panel {
background-color: #f0f4f8;
border-radius: 8px;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.info-panel h3 {
color: #2c5282;
margin-bottom: 0.5rem;
}
.info-panel p {
color: #4a5568;
font-size: 0.9rem;
line-height: 1.4;
}
body.dark .info-panel {
background-color: #2d3748;
}
body.dark .info-panel h3 {
color: #90cdf4;
}
body.dark .info-panel p {
color: #e2e8f0;
}
.offline-indicator {
background-color: #FFA500;
color: white;
padding: 5px 10px;
border-radius: 4px;
position: fixed;
top: 10px;
left: 10px;
z-index: 1000;
}
</style>
</head>
<body>
<div id="offline-indicator" class="offline-indicator hidden">Offline Mode</div>
<button id="theme-toggle" class="theme-toggle text-2xl">
<i class="fas fa-sun" id="theme-toggle-light-icon"></i>
<i class="fas fa-moon hidden" id="theme-toggle-dark-icon"></i>
</button>
<button id="test-supabase" class="mt-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Test Supabase Connection</button>
<div class="header">
ApproVideo
<div class="subheader">Appropriate Technology Videos for the DIY Sector</div>
</div>
<div class="p-4 sm:ml-64 mt-4">
<div class="mb-4 flex justify-center space-x-4">
<a href="#" class="category-link flex items-center p-2 text-base font-normal rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700" data-category="Drinking Water">
<i class="fas fa-tint w-6 h-6 text-blue-500"></i>
<span class="ml-3">Drinking Water</span>
</a>
<a href="#" class="category-link flex items-center p-2 text-base font-normal rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700" data-category="Waste Management">
<i class="fas fa-recycle w-6 h-6 text-green-500"></i>
<span class="ml-3">Waste Management</span>
</a>
<a href="#" class="category-link flex items-center p-2 text-base font-normal rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700" data-category="Energy Systems">
<i class="fas fa-solar-panel w-6 h-6 text-yellow-500"></i>
<span class="ml-3">Energy Systems</span>
</a>
<a href="#" class="category-link flex items-center p-2 text-base font-normal rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700" data-category="Health">
<i class="fas fa-heartbeat w-6 h-6 text-red-500"></i>
<span class="ml-3">Health</span>
</a>
</div>
<div class="mb-4">
<input type="text" id="search" placeholder="Search videos..." class="w-full p-2 border rounded dark:bg-gray-700 dark:text-white">
</div>
<div id="categories" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"></div>
</div>
<div id="video-detail" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
<div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white dark:bg-gray-800">
<div id="video-content"></div>
<div class="text-center mt-4">
<button id="close-detail" class="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300">
Close
</button>
</div>
</div>
<div class="panel-container">
${video.panels.map(panel => `
<div class="info-panel">
<h3>${panel.title}</h3>
<p>${panel.content}</p>
</div>
`).join('')}
</div>
</div>
<button id="export-csv" class="mt-4 bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">Export to CSV</button>
<script>
// RAD: Really Awesome Development starts here!
// ==================== Initialization ====================
const SUPABASE_URL = 'https://vlvbodwrtblttvwnxkjx.supabase.co'
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZsdmJvZHdydGJsdHR2d254a2p4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2ODY3NDk2NzIsImV4cCI6MjAwMjMyNTY3Mn0.TRT1HeX85vP1zDxnU7qBz5GqNPgYZUj-BOdek4qmtEg'
const supabase = supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
let videoData = [];.
let isOffline = false;
// ==================== Data Fetching ====================async function fetchVideoData() {
try {
const { data, error } = await supabase
.from('video')
.select('*')
.order('date', { ascending: false })
if (error) {
console.error('Error fetching data from Supabase:', error)
return null
}
return data
} catch (error) {
console.error('Error connecting to Supabase:', error)
return null
}
}
// ==================== Data Initialization ====================
async function initializeVideoData() {
const supabaseData = await fetchVideoData()
const localData = await localforage.getItem('videoData')
if (supabaseData && supabaseData.length > 0) {
videoData = supabaseData
await localforage.setItem('videoData', videoData)
console.log('Data loaded from Supabase')
isOffline = false
} else if (localData) {
videoData = localData
console.log('Using local data')
isOffline = true
} else {
videoData = []
console.log('No data available')
isOffline = true
}
updateOfflineIndicator()
filterAndSortVideos()
}
// Add this function to your existing JavaScript code
async function testSupabaseConnection() {
try {
const { data, error } = await supabase
.from('video')
.select('*')
.limit(5)
if (error) {
console.error('Error fetching data from Supabase:', error)
alert('Error fetching data from Supabase. Check the console for details.')
return
}
if (data && data.length > 0) {
const resultDiv = document.createElement('div')
resultDiv.innerHTML = `
<h2 class="text-xl font-bold mb-2">Supabase Test Results:</h2>
<pre class="bg-gray-100 p-4 rounded overflow-auto max-h-60">${JSON.stringify(data, null, 2)}</pre>
`
document.body.appendChild(resultDiv)
} else {
alert('No data found in the Supabase table.')
}
} catch (error) {
console.error('Error connecting to Supabase:', error)
alert('Error connecting to Supabase. Check the console for details.')
}
}
// Add this to your event listeners
document.getElementById('test-supabase').addEventListener('click', testSupabaseConnection);
function renderStars(rating) {
const fullStars = Math.floor(rating);
const halfStar = rating % 1 >= 0.5 ? 1 : 0;
const emptyStars = 5 - fullStars - halfStar;
return '★'.repeat(fullStars) + (halfStar ? '½' : '') + '☆'.repeat(emptyStars);
}
function slugify(text) {
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
function renderVideo(video) {
const mainCategory = video.categories[0];
const mainTag = video.tags[0];
const detailUrl = `/${slugify(mainCategory)}/${slugify(mainTag)}/${slugify(video.title)}`;
return `
<div class="video-card rounded-lg shadow-md p-4 mb-4">
<h3 class="text-xl font-semibold mb-2">${video.title}</h3>
<div class="aspect-w-16 aspect-h-9 mb-2">
<img src="https://img.youtube.com/vi/${video.youtubeId}/0.jpg" alt="${video.title}" class="w-full h-64 object-cover">
</div>
<p class="mb-2">${video.description}</p>
<div class="flex flex-wrap mb-2">
${video.tags.map(tag => `<span class="tag text-sm font-medium mr-2 px-2.5 py-0.5 rounded cursor-pointer bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300">${tag}</span>`).join('')}
</div>
<div class="text-yellow-400">${renderStars(video.rating)}</div>
<div class="text-sm opacity-75">Date: ${video.date}</div>
<a href="${detailUrl}" class="mt-2 inline-block bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 video-detail-link" data-id="${video.id}">View Details</a>
</div>
`;
}
function renderVideoDetails(video) {
return `
<h1 class="text-3xl font-bold mb-4">${video.title}</h1>
<div class="aspect-w-16 aspect-h-9 mb-4">
<iframe src="https://www.youtube.com/embed/${video.youtubeId}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen class="w-full h-96"></iframe>
</div>
<p class="mb-4">${video.description}</p>
<div class="mb-4">
${video.tags.map(tag => `<span class="tag text-sm font-medium mr-2 px-2.5 py-0.5 rounded cursor-pointer bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300">${tag}</span>`).join('')}
</div>
<div class="text-yellow-400 mb-2">${renderStars(video.rating)}</div>
<p class="text-sm opacity-75 mb-4">Date: ${video.date}</p>
<h2 class="text-2xl font-bold mb-2">Materials Needed:</h2>
<ul class="list-disc list-inside mb-4">
${video.materials.map(material => `<li>${material}</li>`).join('')}
</ul>
<h2 class="text-2xl font-bold mb-2">Steps:</h2>
<ol class="list-decimal list-inside mb-4">
${video.steps.map(step => `<li>${step}</li>`).join('')}
</ol>
<h2 class="text-2xl font-bold mb-2">Transcript:</h2>
<p class="mb-4">${video.transcript}</p>
`;
if (video.panels) {
detailsContainer.innerHTML += `
<h2 class="text-2xl font-bold mb-2">Additional Information:</h2>
<div class="panel-container">
${video.panels.map(panel => `
<div class="info-panel">
<h3>${panel.title}</h3>
<p>${panel.content}</p>
</div>
`).join('')}
</div>
`;
}
}
function renderCategories(videos) {
const categoriesContainer = document.getElementById('categories');
categoriesContainer.innerHTML = videos.map(renderVideo).join('');
// Add event listeners to detail links
document.querySelectorAll('.video-detail-link').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const videoId = this.getAttribute('data-id');
const video = videoData.find(v => v.id === videoId);
if (video) {
document.getElementById('video-content').innerHTML = renderVideoDetails(video);
document.getElementById('video-detail').classList.remove('hidden');
}
});
});
} //
// ==================== Editing Functions ====================
async function handleEdit(videoId) {
const video = videoData.find(v => v.id == videoId);
if (video) {
document.getElementById('video-content').innerHTML = renderEditForm(video);
document.getElementById('video-detail').classList.remove('hidden');
document.getElementById('edit-form').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(e.target);
const updatedVideo = {
...video,
title: formData.get('title'),
description: formData.get('description'),
tags: formData.get('tags').split(',').map(tag => tag.trim()),
rating: parseFloat(formData.get('rating'))
};
// Update local data
const index = videoData.findIndex(v => v.id == videoId);
videoData[index] = updatedVideo;
// Save to localforage
await localforage.setItem('videoData', videoData);
// Try to update Supabase if online
if (!isOffline) {
try {
const { error } = await supabase
.from('video')
.update(updatedVideo)
.eq('id', videoId)
if (error) {
console.error('Error updating Supabase:', error)
isOffline = true
updateOfflineIndicator()
}
} catch (error) {
console.error('Error connecting to Supabase:', error)
isOffline = true
updateOfflineIndicator()
}
}
// Re-render the video list
filterAndSortVideos();
// Close the edit form
document.getElementById('video-detail').classList.add('hidden');
});
}
}
// ==================== Offline/Online Handling ====================
function updateOfflineIndicator() {
const indicator = document.getElementById('offline-indicator');
if (isOffline) {
indicator.classList.remove('hidden');
} else {
indicator.classList.add('hidden');
}
}
async function syncWithSupabase() {
if (isOffline) {
const localData = await localforage.getItem('videoData');
if (localData) {
try {
const { data, error } = await supabase
.from('video')
.upsert(localData)
if (error) {
console.error('Error syncing with Supabase:', error)
} else {
console.log('Successfully synced with Supabase')
isOffline = false
updateOfflineIndicator()
}
} catch (error) {
console.error('Error connecting to Supabase:', error)
}
}
}
}
// ==================== CSV Export ====================
function exportToCSV() {
const csv = Papa.unparse(videoData);
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", "video_data.csv");
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
// ==================== Event Listeners ====================
document.addEventListener('click', function(e) {
if (e.target.classList.contains('edit-button')) {
const videoId = e.target.getAttribute('data-id');
handleEdit(videoId);
}
if (e.target.classList.contains('video-detail-link')) {
e.preventDefault();
const videoId = e.target.getAttribute('data-id');
const video = videoData.find(v => v.id == videoId);
if (video) {
document.getElementById('video-content').innerHTML = renderVideoDetails(video);
document.getElementById('video-detail').classList.remove('hidden');
}
}
});
document.getElementById('close-detail').addEventListener('click', function() {
document.getElementById('video-detail').classList.add('hidden');
});
document.getElementById('search').addEventListener('input', filterAndSortVideos);
document.getElementById('export-csv').addEventListener('click', exportToCSV);
// Category filtering
document.querySelectorAll('.category-link').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const category = this.getAttribute('data-category');
history.pushState(null, '', `?category=${category}`);
filterAndSortVideos();
});
});
// Theme toggle functionality
const themeToggleBtn = document.getElementById('theme-toggle');
const themeToggleDarkIcon = document.getElementById('theme-toggle-dark-icon');
const themeToggleLightIcon = document.getElementById('theme-toggle-light-icon');
function setTheme(isDark) {
document.body.classList.toggle('dark', isDark);
document.body.classList.toggle('light', !isDark);
themeToggleDarkIcon.classList.toggle('hidden', !isDark);
themeToggleLightIcon.classList.toggle('hidden', isDark);
}
function toggleTheme() {
const isDark = document.body.classList.contains('light');
setTheme(isDark);
}
// Detect user preference
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
setTheme(prefersDarkScheme.matches);
themeToggleBtn.addEventListener('click', toggleTheme);
prefersDarkScheme.addListener((e) => setTheme(e.matches));
function filterAndSortVideos() {
if (!videoData || videoData.length === 0) {
console.log('No video data available');
document.getElementById('categories').innerHTML = '<p>No videos available.</p>';
return;
}
const searchTerm = document.getElementById('search').value.toLowerCase();
const urlParams = new URLSearchParams(window.location.search);
const category = urlParams.get('category');
let filteredVideos = videoData.filter(video =>
(category ? video.categories.includes(category) : true) &&
(video.title.toLowerCase().includes(searchTerm) ||
video.description.toLowerCase().includes(searchTerm) ||
video.tags.some(tag => tag.toLowerCase().includes(searchTerm)))
);
filteredVideos.sort((a, b) => b.rating - a.rating);
renderCategories(filteredVideos);
}
// Initial render
filterAndSortVideos();
// ==================== Main Execution ====================
document.addEventListener('DOMContentLoaded', async () => {
await initializeVideoData();
setInterval(syncWithSupabase, 60000); // Try to sync every minute
});
// RAD: Really Awesome Development ends here! You're totally rad for adding these features!
</script>
</body>
</html>