forked from skybird0714/start
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.js
More file actions
2172 lines (2122 loc) · 94.1 KB
/
Copy pathstart.js
File metadata and controls
2172 lines (2122 loc) · 94.1 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
// 全局变量提前声明
const modeSwitch = document.getElementById('mode-switch');
const blurBtn = document.getElementById('blur-btn');
const searchInput = document.getElementById('search-input');
const resetBtn = document.getElementById('reset-settings-btn');
const clearHistoryBtn = document.getElementById('clear-history-btn');
const langSelect = document.getElementById('lang-select');
const langFlag = document.getElementById('lang-flag');
const settingsBtn = document.getElementById('settings-btn');
const settingsPanel = document.getElementById('settings-panel');
const settingsBgMask = document.getElementById('settings-bg-mask');
const themeColorPicker = document.getElementById('theme-color-picker');
const clock12hSwitch = document.getElementById('clock-12h-switch');
const showSecondsSwitch = document.getElementById('show-seconds-switch');
const suggestSwitch = document.getElementById('suggest-switch');
const newTabSwitch = document.getElementById('new-tab-switch');
let focusModeActive = false;
// ========== 时间与日期 ========== //
function getClock12h() {
return localStorage.getItem('clock12h') === '1';
}
function setClock12h(val) {
localStorage.setItem('clock12h', val ? '1' : '0');
if(clock12hSwitch) clock12hSwitch.checked = val;
updateTime();
}
function getShowSeconds() {
// 默认开启(true)
const val = localStorage.getItem('showSeconds');
return val === null ? true : val === '1';
}
function setShowSeconds(val) {
localStorage.setItem('showSeconds', val ? '1' : '0');
if(showSecondsSwitch) showSecondsSwitch.checked = val;
updateTime();
}
if(clock12hSwitch) {
clock12hSwitch.checked = getClock12h();
clock12hSwitch.onchange = function() {
setClock12h(this.checked);
};
}
if(showSecondsSwitch) {
showSecondsSwitch.checked = getShowSeconds();
showSecondsSwitch.onchange = function() {
setShowSeconds(this.checked);
};
}
function updateTime(lang) {
const now = new Date();
const pad = n => n.toString().padStart(2, '0');
const weekZH = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
const weekZHTW = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
const weekEN = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const weekJA = ['日','月','火','水','木','金','土'];
const weekRU = ['Вск','Пнд','Втр','Срд','Чтв','Птн','Суб'];
const weekFR = ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'];
const weekES = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];
const weekAR = ['الأحد','الاثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت'];
lang = lang || localStorage.getItem('lang') || 'zh';
const use12h = getClock12h();
const showSec = getShowSeconds();
let hour = now.getHours();
let ampm = '';
// 多语言AM/PM
const ampmMap = {
zh: ['上午','下午'],
'zh-TW': ['上午','下午'],
en: ['AM','PM'],
ja: ['午前','午後'],
fr: ['AM','PM'],
ru: ['ДП','ПП'],
es: ['a. m.','p. m.'],
ar: ['ص','م']
};
if(use12h) {
const ampmArr = ampmMap[lang] || ampmMap['en'];
ampm = hour >= 12 ? ' ' + ampmArr[1] : ' ' + ampmArr[0];
hour = hour % 12;
if(hour === 0) hour = 12;
}
// 构造带span的时间字符串
let timeStr = pad(hour) + '<span class="time-colon">:</span>' + pad(now.getMinutes());
if(showSec) timeStr += '<span class="time-colon">:</span>' + pad(now.getSeconds());
if(use12h) timeStr += ampm;
if(lang === 'en') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${now.getFullYear()}/${pad(now.getMonth()+1)}/${pad(now.getDate())} ${weekEN[now.getDay()]}`;
} else if(lang === 'zh-TW') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${now.getFullYear()}年${pad(now.getMonth()+1)}月${pad(now.getDate())}日 ${weekZHTW[now.getDay()]}`;
} else if(lang === 'ja') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${now.getFullYear()}年${pad(now.getMonth()+1)}月${pad(now.getDate())}日 (${weekJA[now.getDay()]})`;
} else if(lang === 'ru') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${pad(now.getDate())}.${pad(now.getMonth()+1)}.${now.getFullYear()} ${weekRU[now.getDay()]}`;
} else if(lang === 'fr') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${pad(now.getDate())}/${pad(now.getMonth()+1)}/${now.getFullYear()} ${weekFR[now.getDay()]}`;
} else if(lang === 'es') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${pad(now.getDate())}/${pad(now.getMonth()+1)}/${now.getFullYear()} ${weekES[now.getDay()]}`;
} else if(lang === 'ar') {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${now.getFullYear()}/${pad(now.getMonth()+1)}/${pad(now.getDate())} ${weekAR[now.getDay()]}`;
} else {
document.getElementById('time').innerHTML = timeStr;
document.getElementById('date').textContent = `${now.getFullYear()}年${pad(now.getMonth()+1)}月${pad(now.getDate())}日 ${weekZH[now.getDay()]}`;
}
}
setInterval(() => updateTime(), 1000);
updateTime();
// ========== 天气 ========== //
async function updateWeather() {
let city = '';
let lang = localStorage.getItem('lang') || 'zh';
try {
// 1. 通过代理API获取IP定位
const locRes = await fetch('/api/weather?type=ip');
const locData = await locRes.json();
if(locData.city) city = locData.city;
} catch {}
try {
// 2. 通过代理API获取天气
const weatherRes = await fetch(`/api/weather?city=${encodeURIComponent(city)}`);
const weatherData = await weatherRes.json();
if(weatherData.status==='1' && weatherData.lives && weatherData.lives[0]) {
const w = weatherData.lives[0];
// 多语言适配
const weatherMap = {
'晴': {en:'Sunny', ja:'晴れ', 'zh-TW':'晴', ru:'Ясно', fr:'Ensoleillé', es:'Soleado', ar:'مشمس'},
'多云': {en:'Cloudy', ja:'くもり', 'zh-TW':'多雲', ru:'Облачно', fr:'Nuageux', es:'Nublado', ar:'غائم'},
'阴': {en:'Overcast', ja:'曇り', 'zh-TW':'陰', ru:'Пасмурно', fr:'Couvert', es:'Cubierto', ar:'غائم كلياً'},
'阵雨': {en:'Shower', ja:'にわか雨', 'zh-TW':'陣雨', ru:'Ливень', fr:'Averses', es:'Chubascos', ar:'زخات'},
'雷阵雨': {en:'Thunder Shower', ja:'雷雨', 'zh-TW':'雷陣雨', ru:'Гроза', fr:'Orages', es:'Tormentas', ar:'عواصف رعدية'},
'小雨': {en:'Light Rain', ja:'小雨', 'zh-TW':'小雨', ru:'Небольшой дождь', fr:'Petite pluie', es:'Lluvia ligera', ar:'أمطار خفيفة'},
'中雨': {en:'Moderate Rain', ja:'中雨', 'zh-TW':'中雨', ru:'Умеренный дождь', fr:'Pluie modérée', es:'Lluvia moderada', ar:'أمطار متوسطة'},
'大雨': {en:'Heavy Rain', ja:'大雨', 'zh-TW':'大雨', ru:'Сильный дождь', fr:'Forte pluie', es:'Lluvia fuerte', ar:'أمطار غزيرة'},
'暴雨': {en:'Storm', ja:'豪雨', 'zh-TW':'暴雨', ru:'Ливень', fr:'Pluie torrentielle', es:'Lluvia torrencial', ar:'أمطار غزيرة جداً'},
'小雪': {en:'Light Snow', ja:'小雪', 'zh-TW':'小雪', ru:'Небольшой снег', fr:'Petite neige', es:'Nieve ligera', ar:'ثلوج خفيفة'},
'中雪': {en:'Moderate Snow', ja:'中雪', 'zh-TW':'中雪', ru:'Умеренный снег', fr:'Neige modérée', es:'Nieve moderada', ar:'ثلوج متوسطة'},
'大雪': {en:'Heavy Snow', ja:'大雪', 'zh-TW':'大雪', ru:'Сильный снег', fr:'Forte neige', es:'Nieve fuerte', ar:'ثلوج كثيفة'},
'暴雪': {en:'Blizzard', ja:'猛吹雪', 'zh-TW':'暴雪', ru:'Метель', fr:'Blizzard', es:'Ventisca', ar:'عاصفة ثلجية'},
'雾': {en:'Fog', ja:'霧', 'zh-TW':'霧', ru:'Туман', fr:'Brouillard', es:'Niebla', ar:'ضباب'},
'霾': {en:'Haze', ja:'煙霧', 'zh-TW':'霾', ru:'Дымка', fr:'Brume', es:'Neblina', ar:'ضباب دخاني'},
'沙尘暴': {en:'Sandstorm', ja:'砂嵐', 'zh-TW':'沙塵暴', ru:'Песчаная буря', fr:'Tempête de sable', es:'Tormenta de arena', ar:'عاصفة رملية'},
'雨夹雪': {en:'Sleet', ja:'みぞれ', 'zh-TW':'雨夾雪', ru:'Дождь со снегом', fr:'Neige fondue', es:'Aguanieve', ar:'مطر ممزوج بالثلج'},
'浮尘': {en:'Dust', ja:'ほこり', 'zh-TW':'浮塵', ru:'Пыль', fr:'Poussière', es:'Polvo', ar:'غبار'},
'扬沙': {en:'Sand', ja:'砂', 'zh-TW':'揚沙', ru:'Песок', fr:'Sable', es:'Arena', ar:'رمال'},
'强沙尘暴': {en:'Severe Sandstorm', ja:'強い砂嵐', 'zh-TW':'強沙塵暴', ru:'Сильная песчаная буря', fr:'Forte tempête de sable', es:'Fuerte tormenta de arena', ar:'عاصفة رملية قوية'},
'冻雨': {en:'Freezing Rain', ja:'氷雨', 'zh-TW':'凍雨', ru:'Ледяной дождь', fr:'Pluie verglaçante', es:'Lluvia helada', ar:'مطر متجمد'},
'雷阵雨伴有冰雹': {en:'Thunder Shower with Hail', ja:'ひょうを伴う雷雨', 'zh-TW':'雷陣雨伴有冰雹', ru:'Гроза с градом', fr:'Orages avec grêle', es:'Tormenta con granizo', ar:'عواصف رعدية مع برد'}
};
let weatherStr = w.weather;
if(weatherMap[w.weather] && weatherMap[w.weather][lang]) weatherStr = weatherMap[w.weather][lang];
let weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ 湿度${w.humidity}% ${w.winddirection}${w.windpower}级`;
if(lang==='en') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ Humidity ${w.humidity}% ${w.winddirection}${w.windpower}`;
else if(lang==='ja') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ 湿度${w.humidity}% ${w.winddirection}${w.windpower}`;
else if(lang==='zh-TW') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ 濕度${w.humidity}% ${w.winddirection}${w.windpower}級`;
else if(lang==='ru') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ Влажн.${w.humidity}% ${w.winddirection}${w.windpower}`;
else if(lang==='fr') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ Humidité ${w.humidity}% ${w.winddirection}${w.windpower}`;
else if(lang==='es') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ Humedad ${w.humidity}% ${w.winddirection}${w.windpower}`;
else if(lang==='ar') weatherText = `${w.city} ${weatherStr} ${w.temperature}℃ رطوبة${w.humidity}% ${w.winddirection}${w.windpower}`;
document.getElementById('weather').textContent = weatherText;
} else {
let failMsg = '天气获取失败';
if(lang === 'en') failMsg = 'Failed to get weather';
else if(lang === 'zh-TW') failMsg = '天氣獲取失敗';
else if(lang === 'ja') failMsg = '天気取得失敗';
else if(lang === 'ru') failMsg = 'Не удалось получить погоду';
else if(lang === 'fr') failMsg = 'Échec de la météo';
else if(lang === 'es') failMsg = 'No se pudo obtener el clima';
else if(lang === 'ar') failMsg = 'فشل في جلب الطقس';
document.getElementById('weather').textContent = failMsg;
}
} catch {
let failMsg = '天气获取失败';
if(lang === 'en') failMsg = 'Failed to get weather';
else if(lang === 'zh-TW') failMsg = '天氣獲取失敗';
else if(lang === 'ja') failMsg = '天気取得失敗';
else if(lang === 'ru') failMsg = 'Не удалось получить погоду';
else if(lang === 'fr') failMsg = 'Échec de la météo';
else if(lang === 'es') failMsg = 'No se pudo obtener el clima';
else if(lang === 'ar') failMsg = 'فشل في جلب الطقس';
document.getElementById('weather').textContent = failMsg;
}
}
updateWeather();
// ========== 搜索引擎 ========== //
const ENGINES = [
{icon:'icons/bing.png', url:'https://www.bing.com/search?q=%s', names:{zh:'必应', 'zh-TW':'必應', en:'Bing', ja:'Bing', fr:'Bing', ru:'Bing', es:'Bing', ar:'Bing'}},
{icon:'icons/baidu.png', url:'https://www.baidu.com/s?wd=%s', names:{zh:'百度', 'zh-TW':'百度', en:'Baidu', ja:'百度', fr:'Baidu', ru:'Baidu', es:'Baidu', ar:'Baidu'}},
{icon:'icons/google.png', url:'https://www.google.com/search?q=%s', names:{zh:'谷歌', 'zh-TW':'Google', en:'Google', ja:'Google', fr:'Google', ru:'Google', es:'Google', ar:'Google'}},
{icon:'icons/yahoo.png', url:'https://search.yahoo.com/search?p=%s', names:{zh:'雅虎', 'zh-TW':'雅虎', en:'Yahoo!', ja:'Yahoo!', fr:'Yahoo!', ru:'Yahoo!', es:'Yahoo!', ar:'Yahoo!'}},
{icon:'icons/yandex.png', url:'https://yandex.com/search/?text=%s', names:{zh:'Yandex', 'zh-TW':'Yandex', en:'Yandex', ja:'Yandex', fr:'Yandex', ru:'Яндекс', es:'Yandex', ar:'Yandex'}},
{icon:'icons/duckduckgo.png', url:'https://duckduckgo.com/?q=%s', names:{zh:'DuckDuckGo', 'zh-TW':'DuckDuckGo', en:'DuckDuckGo', ja:'DuckDuckGo', fr:'DuckDuckGo', ru:'DuckDuckGo', es:'DuckDuckGo', ar:'DuckDuckGo'}},
{icon:'icons/360.png', url:'https://www.so.com/s?q=%s', names:{zh:'360', 'zh-TW':'360', en:'360', ja:'360', fr:'360', ru:'360', es:'360', ar:'360'}},
{icon:'icons/sogou.png', url:'https://www.sogou.com/web?query=%s', names:{zh:'搜狗', 'zh-TW':'搜狗', en:'Sogou', ja:'Sogou', fr:'Sogou', ru:'Sogou', es:'Sogou', ar:'Sogou'}},
{icon:'icons/bilibili.png', url:'https://search.bilibili.com/all?keyword=%s', names:{zh:'哔哩哔哩', 'zh-TW':'嗶哩嗶哩', en:'Bilibili', ja:'ビリビリ', fr:'Bilibili', ru:'Bilibili', es:'Bilibili', ar:'Bilibili'}},
{icon:'icons/github.png', url:'https://github.com/search?q=%s', names:{zh:'GitHub', 'zh-TW':'GitHub', en:'GitHub', ja:'GitHub', fr:'GitHub', ru:'GitHub', es:'GitHub', ar:'GitHub'}},
{icon:'icons/weibo.png', url:'https://s.weibo.com/weibo/%s', names:{zh:'微博', 'zh-TW':'微博', en:'Weibo', ja:'Weibo', fr:'Weibo', ru:'Weibo', es:'Weibo', ar:'Weibo'}},
{icon:'icons/xiaohongshu.png', url:'https://www.xiaohongshu.com/search_result?keyword=%s', names:{zh:'小红书', 'zh-TW':'小紅書', en:'Xiaohongshu', ja:'RED', fr:'RED', ru:'RED', es:'RED', ar:'RED'}},
{icon:'icons/zhihu.png', url:'https://www.zhihu.com/search?type=content&q=%s', names:{zh:'知乎', 'zh-TW':'知乎', en:'Zhihu', ja:'Zhihu', fr:'Zhihu', ru:'Zhihu', es:'Zhihu', ar:'Zhihu'}},
{icon:'icons/douyin.png', url:'https://www.douyin.com/search/%s', names:{zh:'抖音', 'zh-TW':'抖音', en:'Douyin', ja:'TikTok', fr:'TikTok', ru:'TikTok', es:'TikTok', ar:'TikTok'}},
{icon:'icons/youtube.png', url:'https://www.youtube.com/results?search_query=%s', names:{zh:'YouTube', 'zh-TW':'YouTube', en:'YouTube', ja:'YouTube', fr:'YouTube', ru:'YouTube', es:'YouTube', ar:'YouTube'}},
{icon:'icons/facebook.png', url:'https://www.facebook.com/search/top/?q=%s', names:{zh:'Facebook', 'zh-TW':'Facebook', en:'Facebook', ja:'Facebook', fr:'Facebook', ru:'Facebook', es:'Facebook', ar:'Facebook'}},
{icon:'icons/x.png', url:'https://x.com/search?q=%s', names:{zh:'X', 'zh-TW':'X', en:'X', ja:'X', fr:'X', ru:'X', es:'X', ar:'X'}},
{icon:'icons/instagram.png', url:'https://www.instagram.com/explore/tags/%s/', names:{zh:'Instagram', 'zh-TW':'Instagram', en:'Instagram', ja:'Instagram', fr:'Instagram', ru:'Instagram', es:'Instagram', ar:'Instagram'}},
{icon:'icons/taobao.png', url:'https://s.taobao.com/search?q=%s', names:{zh:'淘宝', 'zh-TW':'淘寶', en:'Taobao', ja:'Taobao', fr:'Taobao', ru:'Taobao', es:'Taobao', ar:'Taobao'}},
{icon:'icons/jd.png', url:'https://search.jd.com/Search?keyword=%s', names:{zh:'京东', 'zh-TW':'京東', en:'JD.com', ja:'JD.com', fr:'JD.com', ru:'JD.com', es:'JD.com', ar:'JD.com'}},
];
function getAllEngines() {
return ENGINES;
}
function getEngineIndex() {
return parseInt(localStorage.getItem('engineIndex') || '0', 10);
}
function setEngineIndex(idx) {
localStorage.setItem('engineIndex', idx);
}
function renderEngineBtn() {
const idx = getEngineIndex();
const all = getAllEngines();
const lang = localStorage.getItem('lang') || 'zh';
document.getElementById('engine-icon').src = all[idx].icon;
document.getElementById('engine-icon').alt = all[idx].names[lang] || all[idx].names['en'];
}
function renderEngineList() {
const list = document.getElementById('engine-list');
const all = getAllEngines();
const lang = localStorage.getItem('lang') || 'zh';
list.innerHTML = all.map((e,i) =>
`<div class="engine-item" data-idx="${i}"><img src="${e.icon}" style="width:1.5em;height:1.5em;margin-right:0.5em;">${e.names[lang] || e.names['en']}</div>`
).join('');
}
renderEngineBtn();
renderEngineList();
// 事件绑定
const engineBtn = document.getElementById('engine-btn');
const engineList = document.getElementById('engine-list');
engineBtn.onclick = function(e) {
e.stopPropagation();
if (engineList.classList.contains('open')) {
engineList.classList.remove('open');
setTimeout(()=>engineList.classList.add('hidden'), 180);
} else {
engineList.classList.remove('hidden');
setTimeout(()=>engineList.classList.add('open'), 10);
}
if (!engineList.classList.contains('hidden')) {
document.body.classList.add('engine-list-open');
} else {
document.body.classList.remove('engine-list-open');
}
};
engineList.onclick = function(e) {
let item = e.target;
while(item && !item.classList.contains('engine-item')) item = item.parentElement;
if(item) {
const idx = item.getAttribute('data-idx');
setEngineIndex(idx);
renderEngineBtn();
engineList.classList.remove('open');
setTimeout(()=>engineList.classList.add('hidden'), 180);
document.body.classList.remove('engine-list-open');
}
};
document.addEventListener('click', function(e) {
if(!engineList.contains(e.target) && e.target.id!=='engine-btn' && e.target.id!=='engine-icon') {
engineList.classList.remove('open');
setTimeout(()=>engineList.classList.add('hidden'), 180);
document.body.classList.remove('engine-list-open');
}
});
// 搜索栏聚焦毛玻璃
searchInput.addEventListener('focus', () => {
document.body.classList.add('input-focus');
});
searchInput.addEventListener('blur', () => {
document.body.classList.remove('input-focus');
});
// 搜索
function doSearch() {
const kw = document.getElementById('search-input').value.trim();
if(!kw) return;
const engines = getAllEngines();
const idx = getEngineIndex();
if(idx >= 0 && idx < engines.length) {
const engine = engines[idx];
addSearchHistory(kw);
if(engine.url) {
const target = getNewTabEnabled() ? '_blank' : '_self';
window.open(engine.url.replace('%s', encodeURIComponent(kw)), target);
}
}
}
document.getElementById('search-btn').onclick = doSearch;
searchInput.addEventListener('keydown', function(e) {
if(e.key === 'Enter') doSearch();
});
// ========== 设置面板重构 ========== //
function openSettingsPanel() {
document.body.classList.add('settings-open');
settingsPanel.classList.add('show');
if(settingsBgMask) settingsBgMask.classList.add('show');
}
function closeSettingsPanel() {
if(window.innerWidth <= 700) {
// 手机UA直接隐藏
document.body.classList.remove('settings-open');
settingsPanel.classList.remove('show');
if(settingsBgMask) settingsBgMask.classList.remove('show');
return;
}
// 电脑UA加动画
settingsPanel.classList.remove('show');
settingsPanel.classList.add('hide');
if(settingsBgMask) settingsBgMask.classList.remove('show');
setTimeout(()=>{
document.body.classList.remove('settings-open');
settingsPanel.classList.remove('hide');
}, 350);
}
settingsBtn.onclick = function(e) {
e.stopPropagation();
if(document.body.classList.contains('settings-open')) {
closeSettingsPanel();
} else {
openSettingsPanel();
}
};
if(settingsBgMask) {
settingsBgMask.onclick = function(e) {
e.stopPropagation();
closeSettingsPanel();
};
}
settingsPanel.onclick = function(e) {
e.stopPropagation();
};
document.addEventListener('click', function(e) {
if(document.body.classList.contains('settings-open') &&
!settingsPanel.contains(e.target) &&
e.target !== settingsBtn) {
closeSettingsPanel();
}
});
// 主题色切换
function setThemeColor(color) {
// 兼容所有浏览器,直接设置body和:root
document.documentElement.style.setProperty('--theme-color', color);
document.body.style.setProperty('--theme-color', color);
localStorage.setItem('themeColor', color);
if(themeColorPicker) themeColorPicker.value = color;
}
if(themeColorPicker) {
themeColorPicker.oninput = function() {
setThemeColor(this.value);
};
// 页面加载时自动应用主题色
const savedColor = localStorage.getItem('themeColor') || '#0099ff';
setThemeColor(savedColor);
}
// 语言列表配置
const langListArr = [
{key:'zh', name:'简体中文(China mainland)', flag:'cn.png'},
{key:'zh-TW', name:'繁體中文(Taiwan/Hong Kong)', flag:'hk.png'},
{key:'en', name:'English(United States)', flag:'us.png'},
{key:'ja', name:'日本語(Japan)', flag:'jp.png'},
{key:'fr', name:'Français(France)', flag:'fr.png'},
{key:'ru', name:'Русский(Russia)', flag:'ru.png'},
{key:'es', name:'Español(Spain)', flag:'es.png'},
{key:'ar', name:'العربية(Arab)', flag:'ar.png'}
];
// 渲染自定义语言列表
function renderLangList() {
const langList = document.getElementById('lang-list');
if (!langList) return;
const curLang = localStorage.getItem('lang') || 'zh';
langList.innerHTML = langListArr.map(l =>
`<div class="lang-item${l.key===curLang?' selected':''}" data-lang="${l.key}">
<img src="icons/flag/${l.flag}" class="lang-flag"> ${l.name}
</div>`
).join('');
// 当前显示
const cur = langListArr.find(l=>l.key===curLang) || langListArr[0];
const langFlagEl = document.getElementById('lang-flag');
const langCurNameEl = document.getElementById('lang-current-name');
if(langFlagEl) langFlagEl.src = 'icons/flag/' + cur.flag;
if(langCurNameEl) langCurNameEl.textContent = cur.name;
}
renderLangList();
// 展开/收起逻辑
const langSelectCustom = document.getElementById('lang-select-custom');
const langCurrent = document.getElementById('lang-current');
const langList = document.getElementById('lang-list');
if(langCurrent && langSelectCustom) {
langCurrent.onclick = function(e) {
e.stopPropagation();
langSelectCustom.classList.toggle('open');
};
document.addEventListener('click', function() {
langSelectCustom.classList.remove('open');
});
}
if(langList) {
langList.onclick = function(e) {
const item = e.target.closest('.lang-item');
if(item) {
const lang = item.getAttribute('data-lang');
setLang(lang);
langSelectCustom.classList.remove('open');
renderLangList();
}
};
}
// 切换语言时同步更新自定义列表
const oldSetLang = setLang;
setLang = function(lang) {
oldSetLang(lang);
renderLangList();
// 同步滑块label
const l12h = document.getElementById('label-12h');
const lShowSec = document.getElementById('label-show-seconds');
if(l12h) l12h.textContent = l12h.getAttribute('data-' + lang) || l12h.getAttribute('data-en') || l12h.getAttribute('data-zh');
if(lShowSec) lShowSec.textContent = lShowSec.getAttribute('data-' + lang) || lShowSec.getAttribute('data-en') || lShowSec.getAttribute('data-zh');
};
// 多语言支持
const langMap = {
zh: {name: '简体中文(China)', flag: 'cn.png'},
'zh-TW': {name: '繁體中文(Hong Kong SAR)', flag: 'hk.png'},
en: {name: 'English(United States)', flag: 'us.png'},
ja: {name: '日本語(Japan)', flag: 'jp.png'},
de: {name: 'Deutsch(Germany)', flag: 'de.png'},
fr: {name: 'Français(France)', flag: 'fr.png'},
ru: {name: 'Русский(Russia)', flag: 'ru.png'},
es: {name: 'Español(Spain)', flag: 'es.png'},
pt: {name: 'Português(Portugal)', flag: 'pt.png'},
ar: {name: 'العربية(Arab)', flag: 'ar.png'}
};
if(langSelect) {
langSelect.value = localStorage.getItem('lang') || 'zh';
langSelect.onchange = function() {
setLang(this.value);
};
}
function setLang(lang) {
localStorage.setItem('lang', lang);
document.body.setAttribute('lang', lang);
document.querySelectorAll('[data-zh]').forEach(el => {
let val = el.getAttribute('data-' + lang);
if(val === null || val === undefined) {
val = el.getAttribute('data-en') || el.getAttribute('data-zh');
}
if (el.tagName === 'INPUT' && el.type === 'text') {
el.placeholder = val;
} else {
el.textContent = val;
}
});
if(langSelect) langSelect.value = lang;
if(langFlag && langMap[lang]) langFlag.src = 'icons/flag/' + langMap[lang].flag;
// 多语言标题
const titleMap = {
zh: '起始页',
'zh-TW': '起始頁',
en: 'Start Page',
fr: "Page d'accueil",
ru: 'Стартовая страница',
es: 'Página de inicio',
ar: 'الصفحة الرئيسية',
ja: 'スタートページ'
};
document.title = titleMap[lang] || titleMap['zh'];
updateTime(lang);
updateFooterInfo(lang);
updateWeather();
renderEngineList();
if(resetBtn) resetBtn.textContent = resetBtn.getAttribute('data-' + lang) || resetBtn.getAttribute('data-en') || resetBtn.getAttribute('data-zh');
if(clearHistoryBtn) clearHistoryBtn.textContent = clearHistoryBtn.getAttribute('data-' + lang) || clearHistoryBtn.getAttribute('data-en') || clearHistoryBtn.getAttribute('data-zh');
}
setLang(localStorage.getItem('lang') || 'zh');
function updateFooterInfo(lang) {
// 页脚内容切换
const start = document.getElementById('footer-start');
const author = document.getElementById('footer-author');
const home = document.getElementById('footer-home');
const blog = document.getElementById('footer-blog');
if(start) {
let val = start.getAttribute('data-' + lang);
if(val === null || val === undefined) val = start.getAttribute('data-en') || start.getAttribute('data-zh');
start.textContent = val;
}
if(author) {
let val = author.getAttribute('data-' + lang);
if(val === null || val === undefined) val = author.getAttribute('data-en') || author.getAttribute('data-zh');
author.textContent = val;
}
if(home) {
let val = home.getAttribute('data-' + lang);
if(val === null || val === undefined) val = home.getAttribute('data-en') || home.getAttribute('data-zh');
home.textContent = val;
}
if(blog) {
let val = blog.getAttribute('data-' + lang);
if(val === null || val === undefined) val = blog.getAttribute('data-en') || blog.getAttribute('data-zh');
blog.textContent = val;
}
}
// 昼夜模式切换
function setNightMode(night) {
if(night) {
document.body.classList.add('night');
localStorage.setItem('nightMode', '1');
} else {
document.body.classList.remove('night');
localStorage.setItem('nightMode', '0');
}
}
if(modeSwitch) {
modeSwitch.checked = localStorage.getItem('nightMode') === '1';
setNightMode(modeSwitch.checked);
modeSwitch.onchange = function() {
setNightMode(this.checked);
};
}
// 专注模式按钮功能
if(blurBtn) {
blurBtn.onclick = function(e) {
e.stopPropagation();
if (focusModeActive) return;
focusModeActive = true;
document.body.classList.add('focus-fadeout');
document.getElementById('glass-bg').classList.add('fadeout');
blurBtn.style.display = 'none';
document.querySelectorAll('button, .engine-btn, .search-btn, .lang-toggle, .footer-btn, .mode-toggle, .search-section, .time-section, .footer-info').forEach(el => {
if(el !== blurBtn) el.style.visibility = 'hidden';
});
document.body.addEventListener('click', exitFocusMode, {capture:true});
};
}
function exitFocusMode() {
if(!focusModeActive) return;
focusModeActive = false;
document.body.classList.remove('focus-fadeout');
document.getElementById('glass-bg').classList.remove('fadeout');
blurBtn.style.display = '';
document.querySelectorAll('button, .engine-btn, .search-btn, .lang-toggle, .footer-btn, .mode-toggle, .search-section, .time-section, .footer-info').forEach(el => {
el.style.visibility = '';
});
document.body.removeEventListener('click', exitFocusMode, {capture:true});
}
// 搜索历史记录
const searchHistoryKey = 'searchHistory';
const searchHistoryList = document.getElementById('search-history-list');
function getSearchHistory() {
return JSON.parse(localStorage.getItem(searchHistoryKey) || '[]');
}
function setSearchHistory(arr) {
localStorage.setItem(searchHistoryKey, JSON.stringify(arr));
}
function addSearchHistory(keyword) {
let arr = getSearchHistory();
arr = arr.filter(item => item !== keyword);
arr.unshift(keyword);
if(arr.length > 8) arr = arr.slice(0,8);
setSearchHistory(arr);
}
function renderSearchHistory() {
const arr = getSearchHistory();
if(arr.length === 0) {
searchHistoryList.classList.remove('show');
return;
}
searchHistoryList.innerHTML = arr.map((kw,i) =>
`<div class="search-history-item" data-kw="${kw}">
<span>${kw}</span>
<button class="search-history-del" data-idx="${i}" title="删除"><img src="icons/delete.png" alt="删除"></button>
</div>`
).join('');
searchHistoryList.classList.add('show');
}
searchInput.addEventListener('focus', renderSearchHistory);
searchInput.addEventListener('input', function() {
const kw = this.value.trim();
if (!kw || !getSuggestEnabled()) {
hideSuggestList();
return;
}
const idx = getEngineIndex();
fetchSuggest(kw, idx);
});
searchInput.addEventListener('blur', () => setTimeout(()=>{searchHistoryList.classList.remove('show');}, 200));
searchHistoryList.addEventListener('mousedown', function(e) {
const delBtn = e.target.closest('.search-history-del');
if(delBtn) {
e.preventDefault();
const idx = +delBtn.getAttribute('data-idx');
let arr = getSearchHistory();
arr.splice(idx,1);
setSearchHistory(arr);
renderSearchHistory();
return;
}
let item = e.target.closest('.search-history-item');
if(item) {
const kw = item.getAttribute('data-kw');
searchInput.value = kw;
searchHistoryList.classList.remove('show');
// 记录到历史(移到第一位)
addSearchHistory(kw);
renderSearchHistory();
// 跳转
const idx = getEngineIndex();
const engine = getAllEngines()[idx];
if(engine && engine.url) {
const target = getNewTabEnabled() ? '_blank' : '_self';
window.open(engine.url.replace('%s', encodeURIComponent(kw)), target);
}
}
});
// 多语言确认弹窗内容
const confirmMsgMap = {
zh: {reset: '确定要恢复默认设置吗?', clear: '确定要清空历史记录吗?', ok: '确定', cancel: '取消'},
'zh-TW': {reset: '確定要恢復預設設定嗎?', clear: '確定要清空歷史記錄嗎?', ok: '確定', cancel: '取消'},
en: {reset: 'Reset all settings?', clear: 'Clear all history?', ok: 'OK', cancel: 'Cancel'},
ja: {reset: 'デフォルトに戻しますか?', clear: '履歴を消去しますか?', ok: 'OK', cancel: 'キャンセル'},
fr: {reset: 'Réinitialiser tous les paramètres ?', clear: 'Effacer tout l\'historique ?', ok: 'OK', cancel: 'Annuler'},
ru: {reset: 'Сбросить все настройки?', clear: 'Очистить всю историю?', ok: 'ОК', cancel: 'Отмена'},
es: {reset: '¿Restablecer todos los ajustes?', clear: '¿Borrar todo el historial?', ok: 'OK', cancel: 'Cancelar'},
ar: {reset: 'هل تريد استعادة الإعدادات الافتراضية؟', clear: 'هل تريد مسح كل السجل؟', ok: 'موافق', cancel: 'إلغاء'}
};
function showCustomConfirm(type) {
return new Promise((resolve) => {
const lang = localStorage.getItem('lang') || 'zh';
const msgObj = confirmMsgMap[lang] || confirmMsgMap['zh'];
document.getElementById('custom-confirm-message').textContent = msgObj[type];
document.getElementById('custom-confirm-ok').textContent = msgObj.ok;
document.getElementById('custom-confirm-cancel').textContent = msgObj.cancel;
const mask = document.getElementById('custom-confirm-mask');
mask.style.display = 'flex';
function cleanup() {
mask.style.display = 'none';
okBtn.removeEventListener('click', okHandler);
cancelBtn.removeEventListener('click', cancelHandler);
}
const okBtn = document.getElementById('custom-confirm-ok');
const cancelBtn = document.getElementById('custom-confirm-cancel');
function okHandler() { cleanup(); resolve(true); }
function cancelHandler() { cleanup(); resolve(false); }
okBtn.addEventListener('click', okHandler);
cancelBtn.addEventListener('click', cancelHandler);
});
}
// 替换按钮事件为弹窗确认
if(resetBtn) {
resetBtn.onclick = async function() {
const ok = await showCustomConfirm('reset');
if(!ok) return;
// 清除所有本地存储
localStorage.clear();
// 主题色
setThemeColor('#0099ff');
if(themeColorPicker) themeColorPicker.value = '#0099ff';
// 夜间模式
setNightMode(false);
if(modeSwitch) modeSwitch.checked = false;
// 语言
setLang('zh');
if(langSelect) langSelect.value = 'zh';
// 搜索引擎
setEngineIndex(0);
renderEngineBtn();
renderEngineList();
// 搜索历史
setSearchHistory([]);
renderSearchHistory();
// 搜索建议
setSuggestEnabled(true);
if(suggestSwitch) suggestSwitch.checked = true;
// 新标签页打开(默认开启)
setNewTabEnabled(true);
// 时钟相关
setClock12h(false);
if(clock12hSwitch) clock12hSwitch.checked = false;
setShowSeconds(true);
if(showSecondsSwitch) showSecondsSwitch.checked = true;
// 壁纸
setWallpaperKey('bing');
renderWallpaperList();
// 时钟字体
setClockFontKey('default');
renderClockFontList();
// 语言下拉刷新
renderLangList();
showTopToast('reset');
closeSettingsPanel();
setTimeout(openSettingsPanel, 300);
};
}
if(clearHistoryBtn) {
clearHistoryBtn.onclick = async function() {
const ok = await showCustomConfirm('clear');
if(!ok) return;
setSearchHistory([]);
renderSearchHistory();
showTopToast('clear');
};
}
// 语言切换时同步确认弹窗按钮
const oldSetLang_confirm = setLang;
setLang = function(lang) {
oldSetLang_confirm(lang);
if(document.getElementById('custom-confirm-mask')) {
const msgObj = confirmMsgMap[lang] || confirmMsgMap['zh'];
document.getElementById('custom-confirm-ok').textContent = msgObj.ok;
document.getElementById('custom-confirm-cancel').textContent = msgObj.cancel;
}
};
// 多语言顶部提示内容
const toastMsgMap = {
zh: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return '早上好,今天要搜点什么?';
if (h < 13) return '中午好,今天要搜点什么?';
if (h < 18) return '下午好,今天要搜点什么?';
return '晚上好,今天要搜点什么?';
},
reset: '已恢复默认设置',
clear: '已清空浏览器记录'
},
'zh-TW': {
greet: () => {
const h = new Date().getHours();
if (h < 11) return '早安,今天想搜尋什麼?';
if (h < 13) return '午安,今天想搜尋什麼?';
if (h < 18) return '下午好,今天想搜尋什麼?';
return '晚安,今天想搜尋什麼?';
},
reset: '已恢復預設設定',
clear: '已清空瀏覽器記錄'
},
en: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return 'Good morning! What do you want to search today?';
if (h < 13) return 'Good noon! What do you want to search today?';
if (h < 18) return 'Good afternoon! What do you want to search today?';
return 'Good evening! What do you want to search today?';
},
reset: 'Settings have been reset',
clear: 'Browser history cleared'
},
ja: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return 'おはようございます。今日は何を検索しますか?';
if (h < 13) return 'こんにちは。今日は何を検索しますか?';
if (h < 18) return 'こんにちは。今日は何を検索しますか?';
return 'こんばんは。今日は何を検索しますか?';
},
reset: '設定を初期化しました',
clear: '履歴をクリアしました'
},
fr: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return 'Bonjour ! Que voulez-vous rechercher aujourd\'hui ?';
if (h < 13) return 'Bon midi ! Que voulez-vous rechercher aujourd\'hui ?';
if (h < 18) return 'Bon après-midi ! Que voulez-vous rechercher aujourd\'hui ?';
return 'Bonsoir ! Que voulez-vous rechercher aujourd\'hui ?';
},
reset: 'Paramètres réinitialisés',
clear: 'Historique du navigateur effacé'
},
ru: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return 'Доброе утро! Что ищем сегодня?';
if (h < 13) return 'Добрый день! Что ищем сегодня?';
if (h < 18) return 'Добрый день! Что ищем сегодня?';
return 'Добрый вечер! Что ищем сегодня?';
},
reset: 'Настройки сброшены',
clear: 'История очищена'
},
es: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return '¡Buenos días! ¿Qué quieres buscar hoy?';
if (h < 13) return '¡Buen mediodía! ¿Qué quieres buscar hoy?';
if (h < 18) return '¡Buenas tardes! ¿Qué quieres buscar hoy?';
return '¡Buenas noches! ¿Qué quieres buscar hoy?';
},
reset: 'Configuración restablecida',
clear: 'Historial del navegador borrado'
},
ar: {
greet: () => {
const h = new Date().getHours();
if (h < 11) return 'صباح الخير! ماذا تريد أن تبحث اليوم؟';
if (h < 13) return 'ظهر سعيد! ماذا تريد أن تبحث اليوم؟';
if (h < 18) return 'مساء الخير! ماذا تريد أن تبحث اليوم؟';
return 'مساء الخير! ماذا تريد أن تبحث اليوم؟';
},
reset: 'تمت استعادة الإعدادات الافتراضية',
clear: 'تم مسح سجل المتصفح'
}
};
function showTopToast(type = 'greet') {
const lang = localStorage.getItem('lang') || 'zh';
const msgObj = toastMsgMap[lang] || toastMsgMap['zh'];
let msg;
// 如果type是toastMsgMap的key,则取多语言内容,否则直接显示type本身
if (typeof msgObj[type] === 'function') {
msg = msgObj[type]();
} else if (typeof msgObj[type] === 'string') {
msg = msgObj[type];
} else {
msg = type; // 直接显示传入的字符串
}
const toast = document.getElementById('top-toast');
const toastText = document.getElementById('top-toast-text');
if (!toast || !toastText) return;
toastText.textContent = msg;
toast.classList.add('show');
clearTimeout(toast._timer);
toast._timer = setTimeout(() => {
toast.classList.remove('show');
}, 3200);
}
// 页面载入时显示问候
window.addEventListener('DOMContentLoaded', () => {
setTimeout(() => showTopToast('greet'), 400);
});
// 恢复默认设置时显示
// if (resetBtn) {
// const oldReset = resetBtn.onclick;
// resetBtn.onclick = function() {
// if (typeof oldReset === 'function') oldReset();
// showTopToast('reset');
// };
// }
// 清空历史时显示
// if (clearHistoryBtn) {
// const oldClear = clearHistoryBtn.onclick;
// clearHistoryBtn.onclick = function() {
// if (typeof oldClear === 'function') oldClear();
// showTopToast('clear');
// };
// }
// 搜索建议下拉
let suggestListEl = null;
function showSuggestList(list) {
if (!suggestListEl) {
suggestListEl = document.createElement('div');
suggestListEl.className = 'suggest-list';
suggestListEl.style.position = 'absolute';
suggestListEl.style.left = '0';
suggestListEl.style.right = '0';
suggestListEl.style.top = '110%';
suggestListEl.style.width = '100%';
suggestListEl.style.zIndex = '100';
suggestListEl.style.boxSizing = 'border-box';
document.querySelector('.search-bar-glass').appendChild(suggestListEl);
}
// 弹出建议时收回历史记录
if (searchHistoryList) searchHistoryList.classList.remove('show');
if (!list || list.length === 0) {
suggestListEl.style.display = 'none';
return;
}
suggestListEl.innerHTML = list.map(item => `<div class="suggest-item">${item}</div>`).join('');
suggestListEl.style.display = 'block';
}
function hideSuggestList() {
if (suggestListEl) suggestListEl.style.display = 'none';
}
// 绑定点击建议填充
if (!window._suggestBinded) {
document.addEventListener('mousedown', function(e) {
if (suggestListEl && e.target.classList.contains('suggest-item')) {
const kw = e.target.textContent;
searchInput.value = kw;
hideSuggestList();
// 记录到历史
addSearchHistory(kw);
renderSearchHistory();
// 直接跳转到当前引擎的搜索结果
const idx = getEngineIndex();
const engine = getAllEngines()[idx];
if(engine && engine.url) {
const target = getNewTabEnabled() ? '_blank' : '_self';
window.open(engine.url.replace('%s', encodeURIComponent(kw)), target);
}
} else if (suggestListEl && !suggestListEl.contains(e.target)) {
hideSuggestList();
}
});
window._suggestBinded = true;
}
// 搜索建议API
function fetchSuggest(keyword, engineIdx) {
if (!getSuggestEnabled()) return;
const engine = getAllEngines()[engineIdx];
if (!engine) return;
// 必应(Bing)用jsonp
if (engine.icon.includes('bing')) {
const cbName = 'bingSugCallback_' + Date.now();
window[cbName] = function(data) {
if(data.AS && data.AS.Results && data.AS.Results[0] && data.AS.Results[0].Suggests) {
showSuggestList(data.AS.Results[0].Suggests.map(s=>s.Txt));
} else {
hideSuggestList();
}
delete window[cbName];
};
const script = document.createElement('script');
script.src = `https://api.bing.com/qsonhs.aspx?type=cb&q=${encodeURIComponent(keyword)}&cb=${cbName}`;
document.body.appendChild(script);
setTimeout(()=>{if(script.parentNode)script.parentNode.removeChild(script);}, 800);
}
// 百度
else if (engine.icon.includes('baidu')) {
window.baiduSugCallback = function(res) {
if(res && res.s && res.s.length) {
showSuggestList(res.s);
} else {
hideSuggestList();
}
};
const script = document.createElement('script');
script.src = `https://suggestion.baidu.com/su?wd=${encodeURIComponent(keyword)}&cb=baiduSugCallback`;
document.body.appendChild(script);
setTimeout(()=>{if(script.parentNode)script.parentNode.removeChild(script);}, 800);
}
else {
hideSuggestList();
}
}
// 输入时触发建议
searchInput.addEventListener('input', function() {
const kw = this.value.trim();
if (!kw || !getSuggestEnabled()) {
hideSuggestList();
return;
}
const idx = getEngineIndex();
fetchSuggest(kw, idx);
});
// 切换引擎时隐藏建议
engineBtn && engineBtn.addEventListener('click', hideSuggestList);
// 失焦时隐藏建议
searchInput.addEventListener('blur', ()=>setTimeout(hideSuggestList, 200));
// setLang时同步label
const oldSetLang2 = setLang;
setLang = function(lang) {
oldSetLang2(lang);
const lSuggest = document.getElementById('label-suggest');
if(lSuggest) lSuggest.textContent = lSuggest.getAttribute('data-' + lang) || lSuggest.getAttribute('data-en') || lSuggest.getAttribute('data-zh');
};
function getSuggestEnabled() {
return localStorage.getItem('suggestEnabled') !== '0';
}
function setSuggestEnabled(val) {
localStorage.setItem('suggestEnabled', val ? '1' : '0');
if(suggestSwitch) suggestSwitch.checked = val;
}
if(suggestSwitch) {