-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1194 lines (1027 loc) · 42.6 KB
/
Copy pathscript.js
File metadata and controls
1194 lines (1027 loc) · 42.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
// 闹钟管理器类
class AlarmManager {
constructor() {
this.alarms = [];
this.currentAlarmIndex = -1; // 当前正在计时的闹钟索引
this.alarmTimers = []; // 闹钟计时器数组
this.isSequenceRunning = false; // 是否正在运行闹钟序列
this.activeIntervals = []; // 存储所有活动的计时器ID
this.remainingSeconds = []; // 存储每个闹钟的剩余秒数
this.loadAlarms();
// 不要在构造函数中立即设置事件监听器,等到DOMContentLoaded后再设置
}
// 公开方法,用于在DOM加载完成后设置事件监听器
init() {
this.setupEventListeners();
this.renderAllAlarms();
}
loadAlarms() {
// 修改为默认没有闹钟
this.alarms = [];
// 初始化闹钟计时器
this.initializeAlarmTimers();
}
// 初始化闹钟计时器
initializeAlarmTimers() {
this.alarmTimers = this.alarms.map(alarm => {
const timeParts = alarm.time.split(':');
const hours = parseInt(timeParts[0]);
const minutes = parseInt(timeParts[1]);
const seconds = parseInt(timeParts[2]);
// 转换为总秒数
return hours * 3600 + minutes * 60 + seconds;
});
// 初始化剩余秒数数组
this.remainingSeconds = [...this.alarmTimers];
}
// 开始闹钟序列
startAlarmSequence() {
// 如果序列已经在运行,则不执行任何操作
if (this.isSequenceRunning) {
return;
}
// 播放倒计时音频
this.playCountdownSound().then(() => {
// 音频播放完成后开始计时序列
this.isSequenceRunning = true;
// 如果当前闹钟索引为-1(未开始或已重置),则从第一个闹钟开始
if (this.currentAlarmIndex === -1) {
this.currentAlarmIndex = 0;
}
// 开始当前闹钟计时
this.startCurrentAlarm();
}).catch(error => {
console.log('音频播放失败,直接开始计时:', error);
// 如果音频播放失败,直接开始计时
this.isSequenceRunning = true;
if (this.currentAlarmIndex === -1) {
this.currentAlarmIndex = 0;
}
this.startCurrentAlarm();
});
}
// 播放倒计时音频
playCountdownSound() {
return new Promise((resolve, reject) => {
try {
const audio = new Audio('countdown.mp3');
audio.addEventListener('canplaythrough', () => {
// 音频可以播放时开始播放
audio.play().then(() => {
// 音频播放完成后解析Promise
audio.addEventListener('ended', () => {
resolve();
});
// 添加错误处理
audio.addEventListener('error', (e) => {
reject(e);
});
}).catch(error => {
reject(error);
});
});
// 添加加载错误处理
audio.addEventListener('error', (e) => {
reject(e);
});
// 预加载音频
audio.load();
} catch (error) {
reject(error);
}
});
}
// 开始当前闹钟计时
startCurrentAlarm() {
if (this.currentAlarmIndex >= this.alarmTimers.length) {
// 所有闹钟都已完成
this.isSequenceRunning = false;
this.currentAlarmIndex = -1;
return;
}
// 高亮显示当前闹钟
this.highlightCurrentAlarm();
// 开始倒计时
const alarmElement = document.querySelector(`.alarm-item[data-alarm-id="${this.alarms[this.currentAlarmIndex].id}"]`);
if (alarmElement) {
const timeElement = alarmElement.querySelector('.alarm-time');
// 更新显示
this.updateAlarmDisplay(timeElement, this.remainingSeconds[this.currentAlarmIndex]);
// 设置倒计时
const startTime = Date.now();
const targetSeconds = this.remainingSeconds[this.currentAlarmIndex];
const countdownInterval = setInterval(() => {
const elapsed = Math.floor((Date.now() - startTime) / 1000);
const remaining = targetSeconds - elapsed;
if (remaining <= 0) {
clearInterval(countdownInterval);
// 从活动计时器中移除
this.activeIntervals = this.activeIntervals.filter(id => id !== countdownInterval);
// 确保显示为00:00:00
this.updateAlarmDisplay(timeElement, 0);
this.playAlarmSound();
// 播放countdown.mp3音频后开始下一个闹钟
setTimeout(() => {
this.playCountdownSound().then(() => {
// 音频播放完成后立即开始下一个闹钟
this.currentAlarmIndex++;
this.startCurrentAlarm();
}).catch((error) => {
console.log('音频播放失败,直接开始下一个闹钟:', error);
this.currentAlarmIndex++;
this.startCurrentAlarm();
});
}, 1000); // 添加1秒间隔
} else {
this.updateAlarmDisplay(timeElement, remaining);
}
}, 100); // 使用更短的间隔(100ms)来提高精度
// 保存计时器ID
this.activeIntervals.push(countdownInterval);
}
}
// 更新闹钟显示
updateAlarmDisplay(timeElement, seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainingSeconds = seconds % 60;
timeElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}
// 高亮显示当前闹钟
highlightCurrentAlarm() {
// 移除所有高亮
const allAlarms = document.querySelectorAll('.alarm-item');
allAlarms.forEach(alarm => {
alarm.classList.remove('current-alarm');
});
// 高亮当前闹钟
if (this.currentAlarmIndex >= 0 && this.currentAlarmIndex < this.alarms.length) {
const currentAlarm = document.querySelector(`.alarm-item[data-alarm-id="${this.alarms[this.currentAlarmIndex].id}"]`);
if (currentAlarm) {
currentAlarm.classList.add('current-alarm');
}
}
}
// 播放闹钟声音
playAlarmSound() {
// 这里可以添加声音播放逻辑
console.log('闹钟时间到!');
// 简单的提示音(可以使用更复杂的音频文件)
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.5);
} catch (error) {
console.log('无法播放声音:', error);
}
}
// 停止闹钟序列
// 停止闹钟序列
stopAlarmSequence() {
this.isSequenceRunning = false;
this.currentAlarmIndex = -1;
// 清除所有活动计时器
this.activeIntervals.forEach(intervalId => {
clearInterval(intervalId);
});
this.activeIntervals = [];
// 移除所有高亮
const allAlarms = document.querySelectorAll('.alarm-item');
allAlarms.forEach(alarm => {
alarm.classList.remove('current-alarm');
});
// 注意:暂停时不应该恢复原始时间,应该保持当前的时间状态
// 只有在重置时才需要调用 this.restoreOriginalTimes();
}
// 恢复原始时间显示
restoreOriginalTimes() {
this.alarms.forEach((alarm, index) => {
const alarmElement = document.querySelector(`.alarm-item[data-alarm-id="${alarm.id}"]`);
if (alarmElement) {
const timeElement = alarmElement.querySelector('.alarm-time');
timeElement.textContent = alarm.time;
}
});
}
// 暂停闹钟序列
pauseAlarmSequence() {
if (!this.isSequenceRunning) {
return;
}
this.isSequenceRunning = false;
// 清除所有活动计时器
this.activeIntervals.forEach(intervalId => {
clearInterval(intervalId);
});
this.activeIntervals = [];
// 注意:暂停时保持当前的时间状态,不恢复原始时间
console.log('闹钟序列已暂停');
}
// 重置闹钟序列
resetAlarmSequence() {
// 停止序列
this.stopAlarmSequence();
// 恢复所有闹钟的原始时间显示和剩余秒数
this.restoreOriginalTimes();
this.initializeAlarmTimers(); // 重新初始化剩余秒数
console.log('闹钟序列已重置');
}
setupEventListeners() {
// 监听添加闹钟按钮点击
const addAlarmBtn = document.querySelector('.add-alarm-btn');
addAlarmBtn.addEventListener('click', () => {
this.addNewAlarm();
});
// 添加事件委托,处理删除按钮点击
const alarmsList = document.querySelector('.alarms-list');
alarmsList.addEventListener('click', (e) => {
if (e.target.closest('.delete-alarm-btn')) {
const alarmElement = e.target.closest('.alarm-item');
const alarmId = parseInt(alarmElement.dataset.alarmId);
this.deleteAlarm(alarmId);
}
});
}
addNewAlarm() {
// 创建时间选择对话框
const timeDialog = document.createElement('div');
timeDialog.className = 'time-dialog';
timeDialog.style.position = 'fixed';
timeDialog.style.top = '50%';
timeDialog.style.left = '50%';
timeDialog.style.transform = 'translate(-50%, -50%)';
timeDialog.style.backgroundColor = 'var(--bg-tertiary)';
timeDialog.style.borderRadius = '16px';
timeDialog.style.padding = '20px';
timeDialog.style.boxShadow = '0 10px 40px rgba(0, 0, 0, 0.3)';
timeDialog.style.zIndex = '2000';
timeDialog.style.width = '340px';
timeDialog.style.maxWidth = '90vw';
timeDialog.style.border = '1px solid var(--border-color)';
// 创建标题
const title = document.createElement('h3');
title.textContent = '设置闹钟时间';
title.style.marginBottom = '20px';
title.style.color = 'var(--text-primary)';
title.style.textAlign = 'center';
// 创建时间输入容器
const timeContainer = document.createElement('div');
timeContainer.style.display = 'flex';
timeContainer.style.gap = '8px';
timeContainer.style.marginBottom = '20px';
timeContainer.style.justifyContent = 'center';
timeContainer.style.alignItems = 'center';
// 创建小时输入框
const hourInput = document.createElement('input');
hourInput.type = 'number';
hourInput.min = '0';
hourInput.max = '23';
hourInput.value = '00';
hourInput.placeholder = '时';
hourInput.style.width = '60px';
hourInput.style.padding = '12px';
hourInput.style.borderRadius = '8px';
hourInput.style.border = '1px solid var(--border-color)';
hourInput.style.backgroundColor = 'var(--bg-secondary)';
hourInput.style.color = 'var(--text-primary)';
hourInput.style.fontSize = '1.1rem';
hourInput.style.textAlign = 'center';
// 创建分钟输入框
const minuteInput = document.createElement('input');
minuteInput.type = 'number';
minuteInput.min = '0';
minuteInput.max = '59';
minuteInput.value = '00';
minuteInput.placeholder = '分';
minuteInput.style.width = '60px';
minuteInput.style.padding = '12px';
minuteInput.style.borderRadius = '8px';
minuteInput.style.border = '1px solid var(--border-color)';
minuteInput.style.backgroundColor = 'var(--bg-secondary)';
minuteInput.style.color = 'var(--text-primary)';
minuteInput.style.fontSize = '1.1rem';
minuteInput.style.textAlign = 'center';
// 创建秒钟输入框
const secondInput = document.createElement('input');
secondInput.type = 'number';
secondInput.min = '0';
secondInput.max = '59';
secondInput.value = '00';
secondInput.placeholder = '秒';
secondInput.style.width = '60px';
secondInput.style.padding = '12px';
secondInput.style.borderRadius = '8px';
secondInput.style.border = '1px solid var(--border-color)';
secondInput.style.backgroundColor = 'var(--bg-secondary)';
secondInput.style.color = 'var(--text-primary)';
secondInput.style.fontSize = '1.1rem';
secondInput.style.textAlign = 'center';
// 添加冒号分隔符
const colon1 = document.createElement('div');
colon1.textContent = ':';
colon1.style.display = 'flex';
colon1.style.alignItems = 'center';
colon1.style.justifyContent = 'center';
colon1.style.color = 'var(--text-secondary)';
colon1.style.fontSize = '1.2rem';
colon1.style.width = '10px';
const colon2 = document.createElement('div');
colon2.textContent = ':';
colon2.style.display = 'flex';
colon2.style.alignItems = 'center';
colon2.style.justifyContent = 'center';
colon2.style.color = 'var(--text-secondary)';
colon2.style.fontSize = '1.2rem';
colon2.style.width = '10px';
// 组装时间输入容器
timeContainer.appendChild(hourInput);
timeContainer.appendChild(colon1);
timeContainer.appendChild(minuteInput);
timeContainer.appendChild(colon2);
timeContainer.appendChild(secondInput);
// 创建按钮容器
const buttonContainer = document.createElement('div');
buttonContainer.style.display = 'flex';
buttonContainer.style.gap = '10px';
buttonContainer.style.justifyContent = 'center';
// 创建取消按钮
const cancelBtn = document.createElement('button');
cancelBtn.textContent = '取消';
cancelBtn.style.padding = '10px 20px';
cancelBtn.style.borderRadius = '8px';
cancelBtn.style.border = '1px solid var(--border-color)';
cancelBtn.style.backgroundColor = 'var(--bg-secondary)';
cancelBtn.style.color = 'var(--text-primary)';
cancelBtn.style.cursor = 'pointer';
cancelBtn.style.flex = '1';
// 创建确认按钮
const confirmBtn = document.createElement('button');
confirmBtn.textContent = '确认';
confirmBtn.style.padding = '10px 20px';
confirmBtn.style.borderRadius = '8px';
confirmBtn.style.backgroundColor = 'var(--accent-color)';
confirmBtn.style.color = 'white';
confirmBtn.style.border = 'none';
confirmBtn.style.cursor = 'pointer';
confirmBtn.style.flex = '1';
// 添加元素到对话框
timeDialog.appendChild(title);
timeDialog.appendChild(timeContainer);
buttonContainer.appendChild(cancelBtn);
buttonContainer.appendChild(confirmBtn);
timeDialog.appendChild(buttonContainer);
// 添加到文档
document.body.appendChild(timeDialog);
// 聚焦到秒钟输入框(修改为从秒钟开始输入)
setTimeout(() => {
secondInput.focus();
}, 100);
// 输入验证函数
const validateInput = (input, max) => {
let value = parseInt(input.value) || 0;
if (value < 0) value = 0;
if (value > max) value = max;
input.value = value.toString().padStart(2, '0');
};
// 自动跳转到下一个输入框
const autoTab = (current, next) => {
if (current.value.length === 2 && next) {
next.focus();
}
};
// 设置输入框事件
hourInput.addEventListener('input', () => {
validateInput(hourInput, 23);
autoTab(hourInput, minuteInput);
});
minuteInput.addEventListener('input', () => {
validateInput(minuteInput, 59);
autoTab(minuteInput, secondInput);
});
secondInput.addEventListener('input', () => {
validateInput(secondInput, 59);
});
// 取消按钮事件
cancelBtn.addEventListener('click', () => {
document.body.removeChild(timeDialog);
});
// 确认按钮事件
confirmBtn.addEventListener('click', () => {
const hours = hourInput.value.padStart(2, '0');
const minutes = minuteInput.value.padStart(2, '0');
const seconds = secondInput.value.padStart(2, '0');
if (hours && minutes && seconds) {
const timeValue = `${hours}:${minutes}:${seconds}`;
const newAlarm = {
id: Date.now(),
time: timeValue
};
this.alarms.push(newAlarm);
// 更新计时器数组
this.initializeAlarmTimers();
// 如果闹钟序列正在运行,需要重新开始当前闹钟以确保新闹钟参与计时
if (this.isSequenceRunning && this.currentAlarmIndex >= 0) {
// 暂停当前计时器
this.activeIntervals.forEach(intervalId => {
clearInterval(intervalId);
});
this.activeIntervals = [];
// 重新开始当前闹钟计时
this.startCurrentAlarm();
}
this.renderAlarm(newAlarm, this.alarms.length - 1);
document.body.removeChild(timeDialog);
}
});
// 按ESC键关闭对话框
const handleKeydown = (e) => {
if (e.key === 'Escape') {
document.body.removeChild(timeDialog);
} else if (e.key === 'Enter') {
confirmBtn.click();
}
};
hourInput.addEventListener('keydown', handleKeydown);
minuteInput.addEventListener('keydown', handleKeydown);
secondInput.addEventListener('keydown', handleKeydown);
// 点击对话框外部关闭
timeDialog.addEventListener('click', (e) => {
if (e.target === timeDialog) {
document.body.removeChild(timeDialog);
}
});
}
deleteAlarm(alarmId) {
// 从数据中删除闹钟
this.alarms = this.alarms.filter(alarm => alarm.id !== alarmId);
// 从DOM中删除对应元素
const alarmElement = document.querySelector(`.alarm-item[data-alarm-id="${alarmId}"]`);
if (alarmElement) {
// 添加淡出动画
alarmElement.style.opacity = '0';
alarmElement.style.transform = 'translateY(20px)';
alarmElement.style.height = `${alarmElement.offsetHeight}px`;
setTimeout(() => {
alarmElement.style.height = '0';
alarmElement.style.padding = '0';
alarmElement.style.marginBottom = '0';
alarmElement.style.overflow = 'hidden';
setTimeout(() => {
alarmElement.remove();
}, 300);
}, 300);
}
}
renderAlarm(alarm, index) {
const alarmsList = document.querySelector('.alarms-list');
// 创建新的闹钟项元素
const alarmElement = document.createElement('div');
alarmElement.classList.add('alarm-item');
alarmElement.dataset.alarmId = alarm.id;
alarmElement.style.opacity = '0';
alarmElement.style.transform = 'translateY(20px)';
// 创建序号元素 - 修复NaN问题
const indexElement = document.createElement('div');
indexElement.classList.add('alarm-index');
// 确保index是有效数字,否则使用默认值
const displayIndex = (typeof index === 'number' && !isNaN(index)) ? index + 1 : 1;
indexElement.textContent = displayIndex;
// 创建时间显示元素
const timeElement = document.createElement('div');
timeElement.classList.add('alarm-time');
timeElement.textContent = alarm.time;
// 创建删除按钮
const deleteButton = document.createElement('button');
deleteButton.classList.add('delete-alarm-btn');
deleteButton.textContent = '❌';
deleteButton.title = '删除闹钟';
// 组装并添加到DOM
alarmElement.appendChild(indexElement);
alarmElement.appendChild(timeElement);
alarmElement.appendChild(deleteButton);
alarmsList.appendChild(alarmElement);
// 添加显示动画
setTimeout(() => {
alarmElement.style.opacity = '1';
alarmElement.style.transform = 'translateY(0)';
}, 10);
}
renderAllAlarms() {
// 清空现有列表
const alarmsList = document.querySelector('.alarms-list');
alarmsList.innerHTML = '';
// 重新渲染所有闹钟,并传递序号
this.alarms.forEach((alarm, index) => {
this.renderAlarm(alarm, index);
});
}
}
// 防止移动端缩放
function preventZoom() {
let lastTouchEnd = 0;
document.addEventListener('touchstart', function(e) {
if (e.touches.length > 1) {
e.preventDefault();
}
}, { passive: false });
document.addEventListener('touchend', function(e) {
const now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
e.preventDefault();
}
lastTouchEnd = now;
}, false);
// 禁止长按菜单
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
}, false);
}
// 注册Service Worker
function registerServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('ServiceWorker 注册成功: ', registration.scope);
}).catch(function(error) {
console.log('ServiceWorker 注册失败: ', error);
});
});
}
}
// PWA安装提示
function showPWAInstallPrompt() {
// 检查是否支持PWA安装
if (!window.matchMedia('(display-mode: standalone)').matches) {
// 创建安装提示
const installPrompt = document.createElement('div');
installPrompt.className = 'pwa-install-prompt';
installPrompt.innerHTML = `
<div class="pwa-prompt-content">
<h3>📱 安装应用</h3>
<p>将此应用添加到主屏幕,获得更好的使用体验</p>
<div class="pwa-prompt-buttons">
<button class="pwa-install-btn">安装应用</button>
<button class="pwa-dismiss-btn">稍后再说</button>
</div>
</div>
`;
// 添加样式
const style = document.createElement('style');
style.textContent = `
.pwa-install-prompt {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
animation: fadeIn 0.3s ease;
}
.pwa-prompt-content {
background: var(--bg-primary);
border-radius: 16px;
padding: 24px;
max-width: 300px;
text-align: center;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
.pwa-prompt-content h3 {
margin: 0 0 10px 0;
color: var(--text-primary);
}
.pwa-prompt-content p {
margin: 0 0 20px 0;
color: var(--text-secondary);
font-size: 0.9rem;
}
.pwa-prompt-buttons {
display: flex;
gap: 10px;
}
.pwa-install-btn, .pwa-dismiss-btn {
flex: 1;
padding: 10px 16px;
border: none;
border-radius: 8px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.3s ease;
}
.pwa-install-btn {
background: var(--accent-color);
color: white;
}
.pwa-dismiss-btn {
background: var(--bg-secondary);
color: var(--text-primary);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
`;
document.head.appendChild(style);
document.body.appendChild(installPrompt);
// 添加事件监听
installPrompt.querySelector('.pwa-install-btn').addEventListener('click', () => {
// 触发PWA安装流程
if (window.deferredPrompt) {
window.deferredPrompt.prompt();
window.deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('用户接受了PWA安装');
}
window.deferredPrompt = null;
});
}
installPrompt.remove();
});
installPrompt.querySelector('.pwa-dismiss-btn').addEventListener('click', () => {
installPrompt.remove();
// 保存用户选择,避免频繁提示
localStorage.setItem('pwaPromptDismissed', 'true');
});
// 点击背景关闭
installPrompt.addEventListener('click', (e) => {
if (e.target === installPrompt) {
installPrompt.remove();
localStorage.setItem('pwaPromptDismissed', 'true');
}
});
}
}
// 创建设置菜单
function createSettingsMenu() {
// 检查是否已经创建了设置菜单
if (document.getElementById('settings-menu')) {
return;
}
// 创建设置菜单容器
const settingsMenu = document.createElement('div');
settingsMenu.id = 'settings-menu';
settingsMenu.className = 'settings-menu';
settingsMenu.style.position = 'fixed';
settingsMenu.style.top = '70px';
settingsMenu.style.right = '20px';
settingsMenu.style.width = '150px';
settingsMenu.style.backgroundColor = 'var(--bg-tertiary)';
settingsMenu.style.borderRadius = '16px';
settingsMenu.style.border = '1px solid var(--border-color)';
settingsMenu.style.padding = '10px 0';
settingsMenu.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.2)';
settingsMenu.style.zIndex = '1000';
settingsMenu.style.display = 'none';
settingsMenu.style.opacity = '0';
settingsMenu.style.transition = 'opacity 0.3s ease';
// 创建主题选项
const themeOptionTitle = document.createElement('div');
themeOptionTitle.textContent = '主题';
themeOptionTitle.style.padding = '10px 20px';
themeOptionTitle.style.fontWeight = '600';
themeOptionTitle.style.color = 'var(--text-secondary)';
themeOptionTitle.style.fontSize = '0.8rem';
// 创建系统主题选项
const systemThemeOption = document.createElement('div');
systemThemeOption.className = 'settings-option';
systemThemeOption.textContent = '跟随系统';
systemThemeOption.setAttribute('data-theme-option', 'system');
// 创建深色主题选项
const darkThemeOption = document.createElement('div');
darkThemeOption.className = 'settings-option';
darkThemeOption.textContent = '深色模式';
darkThemeOption.setAttribute('data-theme-option', 'dark');
// 创建浅色主题选项
const lightThemeOption = document.createElement('div');
lightThemeOption.className = 'settings-option';
lightThemeOption.textContent = '浅色模式';
lightThemeOption.setAttribute('data-theme-option', 'light');
// 添加设置菜单项样式
const settingOptions = [systemThemeOption, darkThemeOption, lightThemeOption];
settingOptions.forEach(option => {
option.style.padding = '12px 20px';
option.style.cursor = 'pointer';
option.style.color = 'var(--text-primary)';
option.style.display = 'flex';
option.style.alignItems = 'center';
option.style.justifyContent = 'space-between';
option.style.transition = 'background-color 0.2s ease';
option.addEventListener('click', function() {
const theme = this.getAttribute('data-theme-option');
applyTheme(theme);
saveThemeSetting(theme);
updateSelectedThemeOption();
hideSettingsMenu();
});
option.addEventListener('mouseenter', function() {
this.style.backgroundColor = 'rgba(255, 255, 255, 0.05)';
});
option.addEventListener('mouseleave', function() {
this.style.backgroundColor = 'transparent';
});
// 创建选中指示器
const checkmark = document.createElement('div');
checkmark.className = 'theme-option-checkmark';
checkmark.textContent = '✓';
checkmark.style.fontSize = '1.2rem';
checkmark.style.opacity = '0';
checkmark.style.transition = 'opacity 0.3s ease';
option.appendChild(checkmark);
});
// 将所有元素添加到设置菜单
settingsMenu.appendChild(themeOptionTitle);
settingsMenu.appendChild(systemThemeOption);
settingsMenu.appendChild(darkThemeOption);
settingsMenu.appendChild(lightThemeOption);
// 添加到文档
document.body.appendChild(settingsMenu);
}
// 初始化主题设置
function initTheme() {
// 清理可能存在的旧主题设置,防止冲突
if (localStorage.getItem('theme')) {
// 这里不实际删除,只是确保使用正确的默认值
console.log('使用已保存的主题设置');
}
// 检查localStorage中的主题设置
const savedTheme = localStorage.getItem('theme') || 'system';
// 确定初始主题
let initialTheme;
if (savedTheme === 'system') {
// 使用系统偏好主题
initialTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
} else {
initialTheme = savedTheme;
}
// 应用初始主题
applyTheme(initialTheme);
// 设置设置按钮事件
setupSettingsButton();
}
// 设置设置按钮
function setupSettingsButton() {
const settingsBtn = document.querySelector('.settings-btn');
if (!settingsBtn) {
console.error('设置按钮未找到');
return;
}
// 创建设置菜单
createSettingsMenu();
// 添加点击事件
settingsBtn.addEventListener('click', function(e) {
e.stopPropagation();
toggleSettingsMenu();
});
// 点击其他地方关闭设置菜单
document.addEventListener('click', function() {
hideSettingsMenu();
});
// 阻止设置菜单内部点击事件冒泡
const settingsMenu = document.getElementById('settings-menu');
if (settingsMenu) {
settingsMenu.addEventListener('click', function(e) {
e.stopPropagation();
});
}
}
// 切换设置菜单显示状态
function toggleSettingsMenu() {
const settingsMenu = document.getElementById('settings-menu');
if (!settingsMenu) {
return;
}
if (settingsMenu.style.display === 'block') {
hideSettingsMenu();
} else {
showSettingsMenu();
}
}
// 显示设置菜单
function showSettingsMenu() {
const settingsMenu = document.getElementById('settings-menu');
if (!settingsMenu) {
return;
}
settingsMenu.style.display = 'block';
// 触发重排以应用过渡动画
void settingsMenu.offsetWidth;
settingsMenu.style.opacity = '1';
// 更新选中的主题选项
updateSelectedThemeOption();
}
// 隐藏设置菜单
function hideSettingsMenu() {
const settingsMenu = document.getElementById('settings-menu');
if (!settingsMenu || settingsMenu.style.display === 'none') {
return;
}
settingsMenu.style.opacity = '0';
setTimeout(() => {
settingsMenu.style.display = 'none';
}, 300);
}
// 应用主题
function applyTheme(theme) {
// 获取meta theme-color元素
const metaThemeColor = document.querySelector('meta[name="theme-color"]');
if (theme === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
// 更新meta theme-color
if (metaThemeColor) {
metaThemeColor.setAttribute('content', '#ffffff');
}
} else if (theme === 'dark') {
document.documentElement.removeAttribute('data-theme');
// 更新meta theme-color
if (metaThemeColor) {
metaThemeColor.setAttribute('content', '#121212');
}
} else if (theme === 'system') {
// 使用系统偏好主题
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (systemPrefersDark) {
document.documentElement.removeAttribute('data-theme');
if (metaThemeColor) {
metaThemeColor.setAttribute('content', '#121212');
}
} else {
document.documentElement.setAttribute('data-theme', 'light');
if (metaThemeColor) {
metaThemeColor.setAttribute('content', '#ffffff');
}
}
}
}
// 保存主题设置
function saveThemeSetting(theme) {
localStorage.setItem('theme', theme);