-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver-client-script.js
More file actions
1875 lines (1604 loc) Β· 75.6 KB
/
server-client-script.js
File metadata and controls
1875 lines (1604 loc) Β· 75.6 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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// QuickPoll Application with Server-Side Storage
class QuickPollServerApp extends QuickPollEmailApp {
constructor() {
super();
// Server configuration - dynamically use current host
const currentHost = window.location.hostname;
const currentPort = window.location.port;
// Handle different environments
if (currentHost === 'localhost' || currentHost === '127.0.0.1' || currentHost.includes('192.168')) {
// Local development
const port = currentPort || '3001';
this.apiUrl = `http://${currentHost}:${port}/api`;
} else {
// Production (App Engine, custom domain, etc.)
this.apiUrl = `${window.location.protocol}//${window.location.host}/api`;
}
this.socket = null;
this.storageMode = 'server';
// Initialize server connection
this.initializeServerConnection();
}
// Ensure apiUrl is available for any method calls during initialization
get apiUrl() {
if (this._apiUrl) return this._apiUrl;
const currentHost = window.location.hostname;
const currentPort = window.location.port;
if (currentHost === 'localhost' || currentHost === '127.0.0.1' || currentHost.includes('192.168')) {
const port = currentPort || '3001';
return `http://${currentHost}:${port}/api`;
} else {
return `${window.location.protocol}//${window.location.host}/api`;
}
}
set apiUrl(value) {
this._apiUrl = value;
}
// Override the parent's init method to handle clean URLs
init() {
this.bindEvents();
this.parseQueryString(); // This will call our overridden version
this.showPage(this.currentPage);
// Check if user is already signed in
this.checkExistingAuth();
}
async checkExistingAuth() {
// Check if user data exists in localStorage
const userData = localStorage.getItem('currentUser');
if (userData) {
try {
const user = JSON.parse(userData);
// Verify with server that this session is still valid
const response = await fetch(`${this.apiUrl}/auth/status?email=${encodeURIComponent(user.email)}`);
const result = await response.json();
if (result.success && result.isSignedIn) {
// Session is valid on server
this.currentUser = user;
this.updateUserInterface();
} else {
// Session is not valid on server, clear local data
this.currentUser = null;
localStorage.removeItem('currentUser');
localStorage.removeItem(`userSession_${user.email}`);
this.updateUserInterface();
}
} catch (error) {
console.error('Error checking auth status:', error);
// If server is unavailable, use local data
this.currentUser = JSON.parse(userData);
this.updateUserInterface();
}
}
}
// Override showPage to add focus to poll title when showing create page
showPage(pageId) {
// Call parent method first
super.showPage(pageId);
// Add focus to poll title input when showing create page
if (pageId === 'create') {
// Use setTimeout to ensure the page is fully displayed before focusing
setTimeout(() => {
const pollTitleInput = document.getElementById('poll-title');
if (pollTitleInput) {
pollTitleInput.focus();
}
}, 100);
}
}
async initializeServerConnection() {
try {
// Test server connection
const response = await fetch(`${this.apiUrl}/health`);
if (response.ok) {
const healthData = await response.json();
// Initialize Socket.IO for real-time updates
this.initializeSocketIO();
// Check for existing active poll on page load
await this.checkForActivePoll();
} else {
console.warn("Real-time updates disabled");
this.handleOfflineMode();
}
} catch (error) {
console.warn( error);
this.handleOfflineMode();
}
}
// Check if there's an active poll and update UI accordingly
async checkForActivePoll() {
try {
const response = await fetch(`${this.apiUrl}/polls/current`);
if (response.ok) {
const data = await response.json();
const activePoll = data.poll;
// Check if current user is the creator of the active poll
const isCreatorOfActivePoll = this.currentUser
? this.currentUser.email.toLowerCase() === activePoll.createdBy.toLowerCase()
: activePoll.createdBy === 'anonymous';
// If we're on the landing page and user is the poll creator, redirect to results
if (this.currentPage === 'landing' && isCreatorOfActivePoll) {
console.log('Redirecting poll creator to results page');
this.pollData = activePoll; // Set poll data for the results page
// Load results data before showing the page
try {
await this.loadPollResults();
} catch (error) {
console.error('Error loading results:', error);
// Still show the page even if results fail to load
}
this.showPage('results');
return;
}
// If we're on the landing page and user is not the creator, show vote button
if (this.currentPage === 'landing' && !isCreatorOfActivePoll) {
console.log('π On landing page, user is not creator, checking vote button...');
await this.updateLandingPageVoteButton(activePoll);
} else {
console.log('π Hiding vote button - currentPage:', this.currentPage, 'isCreator:', isCreatorOfActivePoll);
this.hideLandingPageVoteButton();
}
// Otherwise, display the active poll notice (for non-creators on create page)
this.displayActivePollNotice(activePoll);
} else if (response.status === 404) {
// No active poll, show normal create form
this.hideActivePollNotice();
this.hideLandingPageVoteButton();
} else if (response.status === 410) {
// Poll is closed or expired, show normal create form
this.hideActivePollNotice();
this.hideLandingPageVoteButton();
}
} catch (error) {
console.log('No active poll or connection issue:', error.message);
this.hideActivePollNotice();
this.hideLandingPageVoteButton();
}
}
// Update landing page vote button visibility based on active poll
async updateLandingPageVoteButton(poll = null) {
console.log('π Updating landing page vote button for poll:', poll?.title || 'none');
const voteNotice = document.getElementById('active-poll-voting-notice');
const pollTitleElement = document.getElementById('active-poll-title');
const voteBtn = document.getElementById('vote-in-active-poll-btn');
const resultsBtn = document.getElementById('view-active-poll-results-btn');
if (!voteNotice) {
console.log('β Vote notice element not found');
return;
}
if (poll && !poll.isClosed) {
console.log('π Poll is active, checking if user can vote...');
// Check if user can vote before showing the button
const canUserVote = await this.checkIfUserCanVote(poll);
if (canUserVote) {
console.log('β
Showing vote button');
// Show the vote notice with poll information
pollTitleElement.innerHTML = `<strong>Title:</strong> ${poll.title}`;
voteNotice.style.display = 'block';
// Set up event listeners for the buttons
if (voteBtn) {
voteBtn.onclick = () => {
window.location.href = '/vote';
};
}
if (resultsBtn) {
resultsBtn.onclick = () => {
window.location.href = '/results';
};
}
} else {
console.log('β Hiding vote button - user cannot vote');
// User cannot vote, hide the vote notice
voteNotice.style.display = 'none';
}
} else {
console.log('β No active poll or poll is closed, hiding vote button');
// Hide the vote notice
voteNotice.style.display = 'none';
}
}
// Hide landing page vote button
hideLandingPageVoteButton() {
const voteNotice = document.getElementById('active-poll-voting-notice');
if (voteNotice) {
voteNotice.style.display = 'none';
}
}
// Check if current user can vote in the given poll
async checkIfUserCanVote(poll) {
console.log('π Checking if user can vote...');
try {
// Prepare the request URL with voter identifier if authenticated
let url = '/api/votes/status';
if (this.currentUser?.email) {
url += `?voterIdentifier=${encodeURIComponent(this.currentUser.email)}`;
console.log('οΏ½ Checking with authenticated email:', this.currentUser.email);
} else {
console.log('π€ Checking as anonymous user');
}
const response = await fetch(url);
const data = await response.json();
console.log('π Vote status response:', data);
if (!response.ok) {
console.log('β Vote status check failed:', data.error);
return false;
}
// Use the canVote field from the server response
const canVote = data.canVote;
console.log(`β
Final vote eligibility: ${canVote ? 'CAN VOTE' : 'CANNOT VOTE'}`);
if (!canVote) {
if (data.hasVoted) {
console.log('β User has already voted');
} else if (!data.isAuthorized) {
console.log('β User not authorized:', data.authError);
}
}
return canVote;
} catch (error) {
console.error('β Error checking vote eligibility:', error);
return false;
}
}
// Display notice about active poll
displayActivePollNotice(poll) {
// Check if current user is the creator of the active poll
const isCreatorOfActivePoll = this.currentUser
? this.currentUser.email.toLowerCase() === poll.createdBy.toLowerCase()
: poll.createdBy === 'anonymous';
// Find or create notice element
let notice = document.getElementById('active-poll-notice');
if (!notice) {
notice = document.createElement('div');
notice.id = 'active-poll-notice';
notice.className = 'alert alert-info active-poll-notice';
// Insert at the top of the create form
const createForm = document.getElementById('create-poll-form');
if (createForm) {
createForm.parentNode.insertBefore(notice, createForm);
}
}
const createdDate = new Date(poll.createdAt).toLocaleString();
if (isCreatorOfActivePoll) {
// Message for poll creators
notice.innerHTML = `
<h4>π Your Active Poll</h4>
<p><strong>Title:</strong> ${poll.title}</p>
<p><strong>Created:</strong> ${createdDate}</p>
<p>You have an active poll running. Go to the results page to manage it.</p>
<div class="active-poll-actions">
<a href="/results" class="btn btn-primary">Manage Your Poll</a>
<a href="/vote" class="btn btn-secondary">Preview Vote Page</a>
</div>
`;
} else {
// Message for other users
notice.innerHTML = `
<h4>β οΈ Active Poll Detected</h4>
<p><strong>Title:</strong> ${poll.title}</p>
<p><strong>Created:</strong> ${createdDate}</p>
<p><strong>Created by:</strong> ${poll.createdBy}</p>
<p>There is currently an active poll. You cannot create a new poll until this one is closed.</p>
<div class="active-poll-actions">
<a href="/vote" class="btn btn-primary">Vote in Current Poll</a>
<a href="/results" class="btn btn-secondary">View Results</a>
</div>
`;
}
// Disable the create poll form
this.disableCreateForm();
}
// Hide the active poll notice
hideActivePollNotice() {
const notice = document.getElementById('active-poll-notice');
if (notice) {
notice.style.display = 'none';
}
// Re-enable the create poll form
this.enableCreateForm();
}
// Disable create poll form
disableCreateForm() {
const form = document.getElementById('create-poll-form');
if (form) {
const inputs = form.querySelectorAll('input, textarea, button, select');
inputs.forEach(input => {
input.disabled = true;
});
form.style.opacity = '0.5';
}
}
// Enable create poll form
enableCreateForm() {
const form = document.getElementById('create-poll-form');
if (form) {
const inputs = form.querySelectorAll('input, textarea, button, select');
inputs.forEach(input => {
input.disabled = false;
});
form.style.opacity = '1';
}
}
initializeSocketIO() {
try {
// Load Socket.IO from CDN or local file
if (typeof io !== 'undefined') {
const currentHost = window.location.hostname;
const currentPort = window.location.port;
let socketUrl;
if (currentHost === 'localhost' || currentHost === '127.0.0.1' || currentHost.includes('192.168')) {
// Local development
const port = currentPort || '3001';
socketUrl = `http://${currentHost}:${port}`;
} else {
// Production - use current origin
socketUrl = window.location.origin;
}
console.log(`π Connecting to Socket.IO at: ${socketUrl}`);
this.socket = io(socketUrl);
this.socket.on('connect', () => {
console.log('π Socket.IO connected successfully');
this.updateConnectionStatus(true);
// Join the main poll room for real-time updates
console.log('π Joining main poll room');
this.socket.emit('joinPoll', 'current');
});
this.socket.on('disconnect', () => {
console.log('π Socket.IO disconnected');
this.updateConnectionStatus(false);
});
this.socket.on('joinedPoll', (data) => {
console.log('π Successfully joined poll room:', data);
});
this.socket.on('voteSubmitted', (data) => {
console.log('π₯ Received voteSubmitted event:', data);
this.handleRealTimeVoteUpdate(data);
});
this.socket.on('resultsUpdated', (data) => {
console.log('π₯ Received resultsUpdated event:', data);
this.handleRealTimeResultsUpdate(data);
});
this.socket.on('pollUpdated', (data) => {
console.log('π₯ Received pollUpdated event:', data);
this.handleRealTimePollUpdate(data);
});
this.socket.on('pollCreated', (data) => {
console.log('π₯ Received pollCreated event:', data);
this.handlePollCreated(data);
});
this.socket.on('pollDeleted', (data) => {
console.log('π₯ Received pollDeleted event:', data);
this.handlePollDeleted(data);
});
this.socket.on('error', (error) => {
console.error('π Socket error:', error);
});
this.socket.on('connect_error', (error) => {
console.error('π Socket connection error:', error);
});
} else {
console.warn('Socket.IO not available, real-time updates disabled');
}
} catch (error) {
console.error('Failed to initialize Socket.IO:', error);
}
}
handleOfflineMode() {
// Fallback to localStorage for offline functionality
this.storageMode = 'localStorage';
console.log('π± Running in offline mode with localStorage');
}
updateConnectionStatus(isConnected) {
// Update UI to show connection status
const statusIndicators = document.querySelectorAll('.connection-status');
statusIndicators.forEach(indicator => {
indicator.textContent = isConnected ? 'π’ Connected' : 'π΄ Offline';
indicator.className = `connection-status ${isConnected ? 'connected' : 'disconnected'}`;
});
}
// Override URL parsing to handle clean URLs
// Override parseQueryString to ensure apiUrl is set
parseQueryString() {
// Ensure apiUrl is set before parsing
if (!this.apiUrl) {
const currentHost = window.location.hostname;
const currentPort = window.location.port || '3001';
this.apiUrl = `http://${currentHost}:${currentPort}/api`;
}
const path = window.location.pathname;
// Handle clean URLs like /vote or /results (no ID needed)
if (path === '/vote') {
this.loadCurrentPoll('vote');
return;
} else if (path === '/results') {
this.loadCurrentPoll('results');
return;
} else if (path === '/created') {
this.loadPollCreatedPage();
return;
}
// If no specific path, default to landing page
this.currentPage = 'landing';
// Check for active polls when landing on the home page
setTimeout(async () => {
console.log('π Landing page loaded, checking for active polls...');
await this.checkForActivePoll();
}, 100);
}
// Load current poll data from server
async loadCurrentPoll(targetPage) {
try {
// For vote and results pages, include closed polls
const includeClosed = (targetPage === 'vote' || targetPage === 'results') ? '?includeClosed=true' : '';
const response = await fetch(`${this.apiUrl}/polls/current${includeClosed}`);
if (response.ok) {
const data = await response.json();
this.pollData = data.poll;
// If targeting vote page, check poll status and user's vote status
if (targetPage === 'vote') {
// Check if poll is closed
if (this.pollData.isClosed) {
// Poll is closed, redirect to results with notification
this.showRealTimeNotification('This poll has been closed. Showing results.');
this.currentPage = 'results';
await this.loadPollResults();
this.showPage('results');
return;
}
// Check if user has already voted
const hasVoted = await this.checkIfUserHasVoted();
if (hasVoted) {
// User has already voted, redirect to results with notification
this.showRealTimeNotification('You have already voted in this poll. Showing results.');
this.currentPage = 'results';
await this.loadPollResults();
this.showPage('results');
return;
}
}
// Set the page and show it after successful loading
this.currentPage = targetPage;
// If showing results, load the results data
if (targetPage === 'results') {
await this.loadPollResults();
}
this.showPage(targetPage);
} else if (response.status === 404) {
console.error('β No active poll found');
// Redirect to landing page without showing alert
this.currentPage = 'landing';
this.showPage('landing');
} else if (response.status === 410) {
console.error('β Poll is closed or expired');
// Redirect to landing page without showing alert
this.currentPage = 'landing';
this.showPage('landing');
} else {
console.error('Poll loading error:', response.status, response.statusText);
const errorText = await response.text();
console.error('Error details:', errorText);
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
} catch (error) {
console.error('Error in loadCurrentPoll:', error);
console.error('API URL:', this.apiUrl);
console.error('Target Page:', targetPage);
// Redirect to landing page without showing alert
this.currentPage = 'landing';
this.showPage('landing');
}
}
// Helper method to check if current user has already voted
// Helper method to check if current user has already voted
async checkIfUserHasVoted() {
try {
console.log('π Checking if user has voted...');
// Get voter identifier for authenticated polls
const voterIdentifier = this.currentUser ? this.currentUser.email : null;
console.log('π€ Voter identifier:', voterIdentifier);
const voteStatusUrl = voterIdentifier
? `${this.apiUrl}/votes/status?voterIdentifier=${encodeURIComponent(voterIdentifier)}`
: `${this.apiUrl}/votes/status`;
console.log('π Vote status URL:', voteStatusUrl);
const voteStatusResponse = await fetch(voteStatusUrl);
console.log('π‘ Vote status response status:', voteStatusResponse.status);
if (voteStatusResponse.ok) {
const voteStatus = await voteStatusResponse.json();
console.log('π Vote status response:', voteStatus);
return voteStatus.hasVoted;
} else {
// If we can't check vote status, assume user hasn't voted
console.warn('Could not check vote status:', voteStatusResponse.status);
return false;
}
} catch (error) {
console.error('Error checking vote status:', error);
// If there's an error, assume user hasn't voted to allow them to try
return false;
}
}
// Load the poll created success page
async loadPollCreatedPage() {
try {
// Try to load the current poll to get the data for the created page
const includeClosed = '?includeClosed=true';
const response = await fetch(`${this.apiUrl}/polls/current${includeClosed}`);
if (response.ok) {
const data = await response.json();
this.pollData = data.poll;
this.currentPage = 'poll-created';
// Set up the poll created page with poll data
await this.displayPollCreatedPage();
this.showPage('poll-created');
} else if (response.status === 404) {
// No poll found, but stay on created page and show create new poll option
console.log('No poll found - showing create new poll option');
this.pollData = null;
this.currentPage = 'poll-created';
// Set up the poll created page without poll data
await this.displayPollCreatedPage();
this.showPage('poll-created');
} else {
// Other error, redirect to landing page
console.error('Error loading poll for created page:', response.status);
window.location.href = '/';
}
} catch (error) {
console.error('Error loading poll created page:', error);
// Redirect to landing page on error
window.location.href = '/';
}
}
// Display the poll created success page with poll data
async displayPollCreatedPage() {
// Use URLs for the current poll (single-poll system)
const votingUrl = `${window.location.origin}/vote`;
const resultsUrl = `${window.location.origin}/results`;
// Update poll status info if we have poll data
const pollStatusInfo = document.getElementById('poll-status-info');
if (this.pollData && pollStatusInfo) {
// Show poll status information
const statusIndicator = document.getElementById('poll-status-indicator');
const pollTitleDisplay = document.getElementById('poll-title-display');
const pollCreatedDisplay = document.getElementById('poll-created-display');
if (statusIndicator) {
const isOpen = !this.pollData.isClosed;
statusIndicator.textContent = isOpen ? 'π’ Open' : 'π΄ Closed';
statusIndicator.className = `status-indicator ${isOpen ? 'status-open' : 'status-closed'}`;
}
if (pollTitleDisplay) {
pollTitleDisplay.textContent = this.pollData.title;
}
if (pollCreatedDisplay) {
const createdDate = new Date(this.pollData.createdAt).toLocaleString();
pollCreatedDisplay.textContent = createdDate;
}
pollStatusInfo.style.display = 'block';
} else if (pollStatusInfo) {
// Hide poll status info if no poll data
pollStatusInfo.style.display = 'none';
}
// Update URL fields if they exist and we have poll data
const votingLinkElement = document.getElementById('voting-link');
const resultsLinkElement = document.getElementById('results-link');
if (this.pollData) {
// We have poll data, show the links
if (votingLinkElement) {
votingLinkElement.value = votingUrl;
votingLinkElement.style.display = 'block';
}
if (resultsLinkElement) {
resultsLinkElement.value = resultsUrl;
resultsLinkElement.style.display = 'block';
}
// Generate QR code for voting URL
await this.generateQRCode(votingUrl);
} else {
// No poll data, hide the link fields
if (votingLinkElement) {
votingLinkElement.style.display = 'none';
}
if (resultsLinkElement) {
resultsLinkElement.style.display = 'none';
}
// Hide QR code section
const qrSection = document.querySelector('.qr-code-section');
if (qrSection) {
qrSection.style.display = 'none';
}
}
// Show/hide close poll button based on creator status and poll state
const closePollBtn = document.getElementById('close-poll');
if (closePollBtn) {
// Only show close button if there's a poll, user is creator, AND poll is not closed
if (this.pollData && this.isCreator() && !this.pollData.isClosed) {
closePollBtn.style.display = 'inline-block';
} else {
closePollBtn.style.display = 'none';
}
}
// Handle create new poll button visibility and event listener
this.setupCreateNewPollButton();
}
// Override the poll creation method for server-side storage
async handleCreatePoll(e) {
e.preventDefault();
const formData = new FormData(e.target);
const authMode = document.querySelector('input[name="auth-mode"]:checked').value;
const validEmails = document.getElementById('valid-emails').value;
// Prepare poll data
const pollData = {
title: formData.get('title'),
description: formData.get('description'),
type: formData.get('type'),
requireAuth: authMode === 'email',
validEmails: validEmails ? validEmails.split('\n').map(email => email.trim()).filter(email => email) : [],
options: formData.getAll('option').filter(option => option.trim() !== ''),
createdBy: this.currentUser ? this.currentUser.email : 'anonymous'
};
if (pollData.options.length < 2) {
alert('Please add at least 2 options.');
return;
}
try {
// Show loading state
this.showLoadingState('create');
// Send to server
const response = await this.createPollOnServer(pollData);
if (response.success) {
this.pollData = response.poll;
this.votes = {};
// Redirect to the dedicated created endpoint
window.location.href = '/created';
} else {
throw new Error(response.error || 'Failed to create poll');
}
} catch (error) {
console.error( error);
// Check for specific error messages
if (error.message.includes('Poll already exists') || error.message.includes('already an active poll')) {
alert('Cannot create poll: There is already an active poll. Please wait for it to be closed before creating a new one.');
} else if (error.message.includes('Authentication required')) {
alert('Please sign in with your email before creating a poll.');
} else {
alert('Failed to create poll. Please check your internet connection and try again.');
}
this.showPage('create');
}
}
async createPollOnServer(pollData) {
const response = await fetch(`${this.apiUrl}/polls`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(pollData)
});
if (!response.ok) {
const errorData = await response.json();
console.error( errorData);
throw new Error(errorData.error || 'Server error');
}
const result = await response.json();
return result;
}
// Override close poll for server-side storage
async closePoll() {
if (!this.pollData) {
// No active poll, redirect to landing page
this.currentPage = 'landing';
this.showPage('landing');
return;
}
const confirmed = confirm('Are you sure you want to close this poll? This will prevent any further voting. All existing data and results will be preserved. [v2.0]');
if (confirmed) {
try {
// Update poll on server - using single poll endpoint without ID
const requestBody = {
isClosed: true,
closedAt: new Date().toISOString()
};
// Include user identifier for authorization
if (this.currentUser && this.currentUser.email) {
requestBody.requestedBy = this.currentUser.email;
}
const response = await fetch(`${this.apiUrl}/polls`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to close poll');
}
// Update local poll data
this.pollData.isClosed = true;
this.pollData.closedAt = new Date().toISOString();
// Update button state
const closeButton = document.getElementById('close-poll');
if (closeButton) {
closeButton.textContent = 'Poll Closed';
closeButton.disabled = true;
closeButton.classList.remove('btn-danger');
closeButton.classList.add('btn-secondary');
}
// Update create new poll button visibility
this.setupCreateNewPollButton();
// If we're on the results page, refresh it to show updated status
if (this.currentPage === 'results') {
this.renderResultsPage();
}
alert('Poll has been closed successfully. No further votes will be accepted.');
} catch (error) {
alert('Error closing poll: ' + error.message);
}
}
}
async saveResultsAsImage() {
try {
// Load html2canvas library if not already loaded
if (typeof html2canvas === 'undefined') {
await this.loadHtml2Canvas();
}
const resultsContainer = document.getElementById('results-content');
if (!resultsContainer) {
throw new Error('Results container not found');
}
// Create a temporary container for clean capture
const tempContainer = resultsContainer.cloneNode(true);
// Remove action buttons from the clone for cleaner image
const actionButtons = tempContainer.querySelectorAll('.form-actions');
actionButtons.forEach(btn => btn.remove());
// Add timestamp to the results
const timestamp = document.createElement('div');
timestamp.className = 'results-timestamp';
timestamp.textContent = `Results saved on ${new Date().toLocaleString()}`;
tempContainer.appendChild(timestamp);
// Temporarily add the container to the page for capturing
tempContainer.style.position = 'absolute';
tempContainer.style.left = '-9999px';
tempContainer.style.backgroundColor = '#ffffff';
tempContainer.style.padding = '20px';
document.body.appendChild(tempContainer);
// Capture the temporary container
const canvas = await html2canvas(tempContainer, {
backgroundColor: '#ffffff',
scale: 2,
useCORS: true,
allowTaint: true,
width: tempContainer.scrollWidth,
height: tempContainer.scrollHeight
});
// Clean up temporary container
document.body.removeChild(tempContainer);
// Create download link
const link = document.createElement('a');
const filename = `poll-results-${this.pollData.title.replace(/[^a-z0-9]/gi, '_').toLowerCase()}-${new Date().toISOString().split('T')[0]}.png`;
link.download = filename;
link.href = canvas.toDataURL('image/png');
// Trigger download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Show success message
this.showRealTimeNotification('Results image saved successfully!');
} catch (error) {
console.error('Error saving results:', error);
alert('Failed to save results image. Please try again.');
}
}
async loadHtml2Canvas() {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load html2canvas'));
document.head.appendChild(script);
});
}
// Override vote submission for server-side storage
submitVote() {
// First, collect the vote data using the parent's logic
let voteData = {};
if (this.pollData.type === 'simple') {
const selected = document.querySelector('.poll-option.selected');
if (!selected) {
alert('Please select an option.');
return;
}
voteData = { option: parseInt(selected.dataset.value) };
} else if (this.pollData.type === 'rating') {
const ratings = {};
const starsContainers = document.querySelectorAll('.stars');
let hasRating = false;
starsContainers.forEach(container => {
const rating = container.dataset.selectedRating;
if (rating) {
ratings[container.dataset.option] = parseInt(rating);
hasRating = true;
}
});
if (!hasRating) {
alert('Please rate at least one option.');
return;
}
voteData = { ratings };
} else if (this.pollData.type === 'ranking') {
const sortedOptions = [...document.querySelectorAll('.sortable-option')];
console.log('π Found sortable options:', sortedOptions.length);
console.log('π Sortable elements:', sortedOptions);
if (sortedOptions.length === 0) {
alert('No ranking options found. Please check the poll setup.');
return;
}
const ranking = sortedOptions.map(option => {
const value = parseInt(option.dataset.value);
console.log('π Option value:', value, 'from element:', option);
return value;
});
console.log('π Final ranking data:', ranking);
voteData = { rankings: ranking }; // Server expects 'rankings' not 'ranking'
}
// Now submit to the server
this.submitVoteAsync(voteData);
}
async submitVoteAsync(voteData) {
try {
// Show loading state
const submitBtn = document.getElementById('submit-vote');
if (submitBtn) {
submitBtn.textContent = 'Submitting...';
submitBtn.disabled = true;
}
// Submit to server