Repository navigation
Expand file tree
/
Copy pathclient.js
More file actions
6550 lines (6094 loc) · 306 KB
/
Copy pathclient.js
File metadata and controls
6550 lines (6094 loc) · 306 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
/*!
* dsh-weather-panel 1.5.0 — browser bundle
* Generated by scripts/build.mjs from src/. Do not edit this file by hand.
* Locating, fetching, caching and rendering all run in this module; the Host
* half (index.js) only exists so the bundle row resolves.
*/
window.__ModuleLoader__.load({
id: "dsh-weather-panel",
factory(require) {
const React = require('react');
const h = React.createElement;
/* ---- src/lib/i18n.js ---- */
/**
* Locale dictionaries for the panel's own UI.
*
* The Host reads `locale/*.json` for the plugin's *display metadata* (title,
* description, icon). This table is what the panel, the startup notice and the
* typhoon view render, registered through the Client locale service so all of
* them follow the Harness language switch.
*/
const WEATHER_LOCALE_NAMESPACE = 'dsh-weather-panel';
const WEATHER_DICT = {
zh: {
'nav.label': '天气',
'panel.title': '天气面板',
'panel.subtitleNetwork': '网络定位 · {ip}',
'panel.subtitleManual': '手动选择的位置',
'panel.subtitleGps': '系统定位',
'panel.updated': '更新于 {time}',
'action.refresh': '刷新',
'action.retry': '重试',
'action.useImperial': '切换为 °F',
'action.useMetric': '切换为 °C',
'action.changeLocation': '更换位置',
'action.close': '关闭面板',
'action.cancel': '取消',
'state.locating': '正在定位…',
'state.loading': '正在获取天气…',
'state.updating': '更新中…',
'state.cached': '本地缓存',
'state.stale': '数据可能已过期',
'error.locate': '无法通过网络判断当前位置,可以手动搜索城市。',
'error.weather': '获取天气数据失败,请稍后重试。',
'error.timeout': '请求超时。',
'error.network': '网络不可用或被拦截。',
'error.http': '服务返回 HTTP {status}。',
'error.noResult': '没有找到匹配的城市。',
'error.gps': '无法获取系统定位(可能被系统拒绝)。',
'proxy.hint': '当前出口 IP 显示为「{country}」,可能开了代理/VPN。若定位不对,请手动切换城市。',
'proxy.action': '手动切换城市',
'now.title': '当前天气',
'now.feelsLike': '体感 {temp}',
'param.humidity': '湿度',
'param.pressure': '气压',
'param.wind': '风',
'param.gust': '阵风',
'param.precipitation': '降水',
'param.precipProbability': '降水概率',
'param.cloudCover': '云量',
'param.uv': '紫外线',
'param.sunrise': '日出',
'param.sunset': '日落',
'day.today': '今天',
'day.tomorrow': '明天',
'day.afterTomorrow': '后天',
'day.inDays': '{n} 天后',
'day.high': '最高',
'day.low': '最低',
'forecast.title': '未来 5 天',
'hourly.title': '未来 24 小时',
'hourly.now': '现在',
'chart.title': '逐小时降水',
'chart.amount': '降水量',
'chart.chance': '降水概率',
'chart.chanceScale': '降水概率 0–100%',
'chart.empty': '未来 24 小时基本无降水',
'tab.weather': '天气',
'tab.typhoon': '台风',
'tab.satellite': '卫星',
'zoom.title': '大图查看',
'zoom.openOriginal': '打开原图',
'zoom.close': '关闭',
'history.title': '历史气温',
'history.range': '近 {n} 天',
'history.high': '最高',
'history.low': '最低',
'history.mean': '平均',
'history.note': '数据:Open-Meteo 逐日统计 · 截至昨天(完整日)',
'history.empty': '暂无历史气温数据',
'history.error': '历史气温获取失败,稍后再试',
'tab.pro': '专业',
'pro.sst.title': '西北太平洋海表温度',
'pro.sst.region': '海域',
'pro.sst.date': '日期',
'pro.sst.older': '前一天',
'pro.sst.newer': '后一天',
'pro.sst.note': '按日更新,最多回看 15 天',
'pro.sst.unavailable': '该日期暂无海温图',
'pro.ecmwf.title': 'ECMWF 中国区域天气图',
'pro.ecmwf.code': '产品',
'pro.ecmwf.run': '起报时次',
'pro.ecmwf.hour': '预报时效',
'pro.ecmwf.note': '每天 00Z / 12Z 两次起报,最新时次出图会滞后几小时',
'pro.ecmwf.unavailable': '该时效暂无图',
'pro.attribution': '数据与图片:easterlywave.com(社区站点,非官方;仅作个人查看)', 'sat.title': '卫星云图',
'sat.source': '国家卫星气象中心 · 中国气象局',
'sat.product': '产品',
'sat.time': '时次',
'sat.prev': '更早一帧',
'sat.next': '更新一帧',
'sat.loading': '正在加载产品清单…',
'sat.empty': '该产品暂无影像',
'sat.error': '产品清单获取失败',
'sat.unavailable': '该时次暂无影像',
'sat.note': '官方产品图:风云四号 B 星每 15 分钟、风云二号每 30 分钟更新',
'sat.official': '打开官方页面',
'sat.zoomHint': '点击放大查看', 'radar.title': '雷达拼图',
'radar.source': '中央气象台 · 中国气象局',
'radar.region': '区域',
'radar.time': '时次',
'radar.prev': '上一时次',
'radar.next': '下一时次',
'radar.play': '播放',
'radar.pause': '暂停',
'radar.latest': '最新',
'radar.unavailable': '该时次暂无产品图',
'radar.note': '官方产品图,约 6 分钟更新;全国可回看 24 小时,分区约 2 小时。',
'radar.official': '打开官方雷达页',
'radar.openImage': '打开原图',
'radar.zoomHint': '点击放大查看',
'radar.zoomTitle': '雷达拼图大图',
'radar.close': '关闭',
'tab.radar': '雷达',
'alerts.title': '气象预警',
'alerts.none': '当前没有生效的预警',
'alerts.count': '{n} 条生效',
'alerts.scopeCity': '本市',
'alerts.scopeRegion': '本省',
'alerts.more': '另有 {n} 条',
'alerts.expand': '展开全部',
'alerts.collapse': '收起',
'alerts.source': '中央气象台 · 中国气象局',
'alerts.openAll': '查看全部预警',
'alerts.issued': '发布',
'alert.level.blue': '蓝色',
'alert.level.yellow': '黄色',
'alert.level.orange': '橙色',
'alert.level.red': '红色',
'notice.title': '天气提醒',
'notice.rainTitle': '今天有降水',
'notice.rainBody': '预计降水量 {amount},降水概率最高 {chance}。出门记得带伞。',
'notice.alertTitle': '收到气象预警',
'notice.alertBody': '当前有 {count} 条生效预警,最高等级:{level}。',
'notice.confirm': '知道了',
'notice.dismiss': '关闭提醒',
'notice.more': '还有 {n} 条',
'notice.source': '数据:Open-Meteo · 中央气象台',
'typhoon.title': '台风路径',
'typhoon.active': '活跃',
'typhoon.ended': '已结束',
'typhoon.none': '当前没有台风信息',
'typhoon.noActive': '近期无活跃台风',
'typhoon.noActiveHint': '中央气象台当前没有编号中的活跃台风。可查看最近一次台风的路径,或到官方页面确认。',
'typhoon.viewLatest': '查看最近一次',
'typhoon.hideLatest': '收起最近一次',
'typhoon.latest': '最近定位',
'typhoon.pressure': '中心气压',
'typhoon.wind': '最大风速',
'typhoon.move': '移动',
'typhoon.forecast': '未来路径',
'typhoon.peak': '最强强度',
'typhoon.meaning': '名称含义',
'typhoon.source': '中央气象台台风网',
'typhoon.official': '查看官方路径图',
'typhoon.land': '底图:Natural Earth(公有领域)',
'typhoon.select': '切换台风',
'typhoon.hint': '点击轨迹点查看该时刻详情',
'typhoon.backToCurrent': '回到当前时刻',
'typhoon.windRadius': '风圈半径',
'typhoon.windRadiusGrade': '{grade} 风圈',
'typhoon.updated': '更新于 {time}',
'typhoon.noForecast': '暂无预报路径',
'location.title': '位置来源',
'location.description': '默认按公网 IP 判断城市(城市级精度)。如果你开了网络代理 / VPN,IP 会变成代理出口,城市会判错——这种情况下请直接在下面搜索并手动切换城市,或用「系统定位」。',
'location.auto': '自动(网络定位)',
'location.network': '网络定位',
'location.system': '系统定位',
'location.mode': '定位方式',
'location.networkHint': '按公网 IP 判断城市(城市级精度;开了代理或 VPN 可能判错)。',
'location.systemHint': '使用浏览器 / 系统定位,精度更高;首次使用会请求一次授权,不可用时自动回退到网络定位。',
'location.manualActive': '当前为手动选择的城市,点上方任一方式可切回自动定位。',
'location.autoHint': '重新检测当前网络所在城市',
'location.gps': '使用系统定位',
'location.gpsHint': '调用浏览器地理位置,精度更高',
'location.precise': '高精度系统定位',
'location.preciseHint': '开启后每次启动都优先使用浏览器 / 系统定位(会请求一次定位权限);不可用时自动回退到 IP。',
'location.gpsFallback': '系统定位不可用,本次已回退到网络定位。',
'location.preciseOn': '已开启',
'location.preciseOff': '已关闭',
'location.previewNotice': '预览提醒弹窗',
'location.previewNoticeHint': '用一条演示用的台风红色预警,检查弹窗样式(不会写入真实预警)。',
'panel.subtitleGpsAccurate': '系统定位 · 精度约 {accuracy} 米',
'location.searchTitle': '搜索城市',
'location.placeholder': '输入城市名,例如 北京',
'location.searching': '搜索中…',
'location.noResult': '没有找到匹配的城市。',
'footer.weather': '天气数据',
'footer.location': '定位数据',
'footer.alerts': '预警数据',
'footer.license': 'CC BY 4.0',
'footer.note': '浏览器内直接请求,无需 API Key。',
'footer.feedback': '反馈 / 提 issue',
'aria.icon': '天气图标',
'aria.loading': '加载中'
},
en: {
'nav.label': 'Weather',
'panel.title': 'Weather panel',
'panel.subtitleNetwork': 'Network location · {ip}',
'panel.subtitleManual': 'Manually selected location',
'panel.subtitleGps': 'Device location',
'panel.updated': 'Updated {time}',
'action.refresh': 'Refresh',
'action.retry': 'Retry',
'action.useImperial': 'Switch to °F',
'action.useMetric': 'Switch to °C',
'action.changeLocation': 'Change location',
'action.close': 'Close panel',
'action.cancel': 'Cancel',
'state.locating': 'Locating…',
'state.loading': 'Loading weather…',
'state.updating': 'Updating…',
'state.cached': 'Cached',
'state.stale': 'May be out of date',
'error.locate': 'Could not determine this network’s location. Pick a city manually.',
'error.weather': 'Could not load the weather. Try again in a moment.',
'error.timeout': 'The request timed out.',
'error.network': 'Network unavailable or blocked.',
'error.http': 'The service returned HTTP {status}.',
'error.noResult': 'No matching city.',
'error.gps': 'Device location is unavailable (it may be denied).',
'proxy.hint': 'This network exits in “{country}”, which usually means a proxy or VPN is on. If the location is wrong, switch the city manually.',
'proxy.action': 'Pick a city',
'now.title': 'Now',
'now.feelsLike': 'Feels like {temp}',
'param.humidity': 'Humidity',
'param.pressure': 'Pressure',
'param.wind': 'Wind',
'param.gust': 'Gusts',
'param.precipitation': 'Precipitation',
'param.precipProbability': 'Precip. chance',
'param.cloudCover': 'Cloud cover',
'param.uv': 'UV index',
'param.sunrise': 'Sunrise',
'param.sunset': 'Sunset',
'day.today': 'Today',
'day.tomorrow': 'Tomorrow',
'day.afterTomorrow': 'In 2 days',
'day.inDays': 'In {n} days',
'day.high': 'High',
'day.low': 'Low',
'forecast.title': 'Next 5 days',
'hourly.title': 'Next 24 hours',
'hourly.now': 'Now',
'chart.title': 'Hourly precipitation',
'chart.amount': 'Amount',
'chart.chance': 'Chance',
'chart.chanceScale': 'Chance of precipitation 0–100%',
'chart.empty': 'Almost no rain in the next 24 hours',
'tab.weather': 'Weather',
'tab.typhoon': 'Typhoon',
'tab.satellite': 'Satellite',
'zoom.title': 'Enlarged image',
'zoom.openOriginal': 'Open the full image',
'zoom.close': 'Close',
'history.title': 'Temperature history',
'history.range': 'Last {n} days',
'history.high': 'High',
'history.low': 'Low',
'history.mean': 'Mean',
'history.note': 'Data: Open-Meteo daily statistics · up to yesterday (complete days)',
'history.empty': 'No historical temperature data',
'history.error': 'Could not load the temperature history',
'tab.pro': 'Pro',
'pro.sst.title': 'Sea surface temperature',
'pro.sst.region': 'Region',
'pro.sst.date': 'Date',
'pro.sst.older': 'Previous day',
'pro.sst.newer': 'Next day',
'pro.sst.note': 'Updated daily, up to 15 days of history',
'pro.sst.unavailable': 'No SST image for this date',
'pro.ecmwf.title': 'ECMWF charts · China',
'pro.ecmwf.code': 'Product',
'pro.ecmwf.run': 'Model run',
'pro.ecmwf.hour': 'Forecast hour',
'pro.ecmwf.note': 'Two runs a day (00Z / 12Z); the newest run appears with a few hours lag',
'pro.ecmwf.unavailable': 'No chart for this hour',
'pro.attribution': 'Data and imagery: easterlywave.com (community site, unofficial; personal viewing)', 'sat.title': 'Satellite imagery',
'sat.source': 'NSMC · China Meteorological Administration',
'sat.product': 'Product',
'sat.time': 'Time',
'sat.prev': 'Older frame',
'sat.next': 'Newer frame',
'sat.loading': 'Loading the product list…',
'sat.empty': 'No imagery for this product',
'sat.error': 'Could not load the product list',
'sat.unavailable': 'No imagery for this frame',
'sat.note': 'Official products: FY-4B every 15 minutes, FY-2 every 30 minutes',
'sat.official': 'Open the official page',
'sat.zoomHint': 'Click to enlarge', 'radar.title': 'Radar mosaic',
'radar.source': 'NMC · China Meteorological Administration',
'radar.region': 'Region',
'radar.time': 'Time',
'radar.prev': 'Previous frame',
'radar.next': 'Next frame',
'radar.play': 'Play',
'radar.pause': 'Pause',
'radar.latest': 'Latest',
'radar.unavailable': 'No image for this frame',
'radar.note': 'Official product images, updated about every 6 minutes; 24 hours for the nationwide mosaic, about 2 hours for regions.',
'radar.official': 'Open the official radar page',
'radar.openImage': 'Open the full image',
'radar.zoomHint': 'Click to enlarge',
'radar.zoomTitle': 'Radar mosaic, enlarged',
'radar.close': 'Close',
'tab.radar': 'Radar',
'alerts.title': 'Weather alerts',
'alerts.none': 'No active alerts',
'alerts.count': '{n} active',
'alerts.scopeCity': 'City',
'alerts.scopeRegion': 'Province',
'alerts.more': '{n} more',
'alerts.expand': 'Show all',
'alerts.collapse': 'Collapse',
'alerts.source': 'NMC · China Meteorological Administration',
'alerts.openAll': 'See all alerts',
'alerts.issued': 'Issued',
'alert.level.blue': 'Blue',
'alert.level.yellow': 'Yellow',
'alert.level.orange': 'Orange',
'alert.level.red': 'Red',
'notice.title': 'Weather notice',
'notice.rainTitle': 'Rain today',
'notice.rainBody': 'About {amount} expected, chance up to {chance}. Take an umbrella.',
'notice.alertTitle': 'Weather alert received',
'notice.alertBody': '{count} active alert(s), highest level: {level}.',
'notice.confirm': 'Got it',
'notice.dismiss': 'Dismiss',
'notice.more': '{n} more',
'notice.source': 'Data: Open-Meteo · NMC',
'typhoon.title': 'Typhoon track',
'typhoon.active': 'Active',
'typhoon.ended': 'Ended',
'typhoon.none': 'No typhoon information',
'typhoon.noActive': 'No active typhoon right now',
'typhoon.noActiveHint': 'The CMA has no numbered active typhoon at the moment. You can still look at the most recent track, or check the official page.',
'typhoon.viewLatest': 'View the most recent',
'typhoon.hideLatest': 'Hide the most recent',
'typhoon.latest': 'Latest fix',
'typhoon.pressure': 'Central pressure',
'typhoon.wind': 'Max wind',
'typhoon.move': 'Moving',
'typhoon.forecast': 'Forecast track',
'typhoon.peak': 'Peak intensity',
'typhoon.meaning': 'Name meaning',
'typhoon.source': 'NMC typhoon service',
'typhoon.official': 'Open official map',
'typhoon.land': 'Basemap: Natural Earth (public domain)',
'typhoon.select': 'Switch typhoon',
'typhoon.hint': 'Click a track point for that moment',
'typhoon.backToCurrent': 'Back to current',
'typhoon.windRadius': 'Wind radius',
'typhoon.windRadiusGrade': '{grade} force ring',
'typhoon.updated': 'Updated {time}',
'typhoon.noForecast': 'No forecast track yet',
'location.title': 'Location source',
'location.description': 'The city is derived from your public IP (city-level accuracy). If a proxy or VPN is on, the IP belongs to its exit and the city will be wrong — in that case search for your city below and switch manually, or use device location.',
'location.auto': 'Automatic (network)',
'location.network': 'Network',
'location.system': 'System',
'location.mode': 'Location mode',
'location.networkHint': 'Resolves the city from your public IP (city level; a proxy or VPN can pick the wrong one).',
'location.systemHint': 'Uses the browser / system location for better accuracy; asks permission once and falls back to the network when unavailable.',
'location.manualActive': 'A manually picked city is active — choose a mode above to go back to automatic.',
'location.autoHint': 'Detect the city this network belongs to',
'location.gps': 'Use device location',
'location.gpsHint': 'Uses the browser geolocation API for better accuracy',
'location.precise': 'High-accuracy device location',
'location.preciseHint': 'When on, every start prefers the browser / system location (asks for permission once) and falls back to the IP when unavailable.',
'location.gpsFallback': 'Device location unavailable; fell back to network location this time.',
'location.preciseOn': 'On',
'location.preciseOff': 'Off',
'location.previewNotice': 'Preview the notice',
'location.previewNoticeHint': 'Shows the dialog with a demo red typhoon warning (never touches real alerts).',
'panel.subtitleGpsAccurate': 'Device location · ~{accuracy} m',
'location.searchTitle': 'Search a city',
'location.placeholder': 'City name, e.g. Beijing',
'location.searching': 'Searching…',
'location.noResult': 'No matching city.',
'footer.weather': 'Weather data',
'footer.location': 'Location data',
'footer.alerts': 'Alert data',
'footer.license': 'CC BY 4.0',
'footer.note': 'Requested in the browser; no API key.',
'footer.feedback': 'Report an issue',
'aria.icon': 'Weather icon',
'aria.loading': 'Loading'
}
};
/** Replace `{name}` placeholders in a message. Unknown placeholders are kept. */
function interpolate(template, vars) {
const text = typeof template === 'string' ? template : String(template == null ? '' : template);
if (!vars) return text;
return text.replace(/\{(\w+)\}/g, (match, key) => {
const value = vars[key];
return value === undefined || value === null ? match : String(value);
});
}
/** Resolve a key from the bundled dictionary, falling back to the other language. */
function lookupMessage(lang, key) {
const primary = WEATHER_DICT[lang] || WEATHER_DICT.zh;
if (Object.prototype.hasOwnProperty.call(primary, key)) return primary[key];
const other = lang === 'en' ? WEATHER_DICT.zh : WEATHER_DICT.en;
if (Object.prototype.hasOwnProperty.call(other, key)) return other[key];
return key;
}
/**
* Build a translator on top of the Host translator.
*
* `rawTranslate` is `ctx.locale.bind(ns)`: it follows the active language but
* only knows the keys registered in its namespace dictionary. When it hands
* back the key itself (unknown key), the bundled table is used instead.
*/
function makeTranslate(rawTranslate, lang) {
return function translate(key, vars) {
let text = '';
if (typeof rawTranslate === 'function') {
try {
text = rawTranslate(key);
} catch (error) {
text = '';
}
}
if (!text || text === key) text = lookupMessage(lang, key);
return interpolate(text, vars);
};
}
/* ---- src/lib/links.js ---- */
/**
* Project links.
*
* One place to edit if the repository moves: the panel footer reads from here.
* Keep it in sync with the `repository` field in package.json.
*/
const PROJECT_OWNER = 'python3603';
const PROJECT_NAME = 'dsh-weather-panel';
const PROJECT_URL = `https://github.com/${PROJECT_OWNER}/${PROJECT_NAME}`;
const PROJECT_ISSUES_URL = `${PROJECT_URL}/issues`;
const PROJECT_NEW_ISSUE_URL = `${PROJECT_URL}/issues/new`;
/* ---- src/lib/wmo.js ---- */
/**
* WMO 4677 weather codes → stable presentation data.
*
* Open-Meteo reports `weather_code` as a WMO 4677 number. Mapping it here keeps
* wording, icon group and severity in one table instead of scattering `if`
* chains through the view, and it lets the whole table be unit-tested.
*/
/** Every code Open-Meteo can return, with neutral wording and a severity hint. */
const WMO_TABLE = {
0: { icon: 'clear', zh: '晴', en: 'Clear sky', severity: 0 },
1: { icon: 'mostly-clear', zh: '大部晴朗', en: 'Mainly clear', severity: 0 },
2: { icon: 'partly-cloudy', zh: '局部多云', en: 'Partly cloudy', severity: 0 },
3: { icon: 'overcast', zh: '阴', en: 'Overcast', severity: 1 },
45: { icon: 'fog', zh: '雾', en: 'Fog', severity: 1 },
48: { icon: 'fog', zh: '凇雾', en: 'Depositing rime fog', severity: 1 },
51: { icon: 'drizzle', zh: '小毛毛雨', en: 'Light drizzle', severity: 1 },
53: { icon: 'drizzle', zh: '毛毛雨', en: 'Moderate drizzle', severity: 1 },
55: { icon: 'drizzle', zh: '大毛毛雨', en: 'Dense drizzle', severity: 2 },
56: { icon: 'sleet', zh: '轻冻毛毛雨', en: 'Light freezing drizzle', severity: 2 },
57: { icon: 'sleet', zh: '冻毛毛雨', en: 'Dense freezing drizzle', severity: 2 },
61: { icon: 'rain', zh: '小雨', en: 'Slight rain', severity: 1 },
63: { icon: 'rain', zh: '中雨', en: 'Moderate rain', severity: 2 },
65: { icon: 'rain', zh: '大雨', en: 'Heavy rain', severity: 3 },
66: { icon: 'sleet', zh: '轻冻雨', en: 'Light freezing rain', severity: 2 },
67: { icon: 'sleet', zh: '冻雨', en: 'Heavy freezing rain', severity: 3 },
71: { icon: 'snow', zh: '小雪', en: 'Slight snow', severity: 1 },
73: { icon: 'snow', zh: '中雪', en: 'Moderate snow', severity: 2 },
75: { icon: 'snow', zh: '大雪', en: 'Heavy snow', severity: 3 },
77: { icon: 'snow', zh: '米雪', en: 'Snow grains', severity: 1 },
80: { icon: 'showers', zh: '小阵雨', en: 'Slight rain showers', severity: 1 },
81: { icon: 'showers', zh: '阵雨', en: 'Moderate rain showers', severity: 2 },
82: { icon: 'showers', zh: '强阵雨', en: 'Violent rain showers', severity: 3 },
85: { icon: 'snow', zh: '小阵雪', en: 'Slight snow showers', severity: 1 },
86: { icon: 'snow', zh: '阵雪', en: 'Heavy snow showers', severity: 2 },
95: { icon: 'thunder', zh: '雷暴', en: 'Thunderstorm', severity: 3 },
96: { icon: 'thunder', zh: '雷暴伴小冰雹', en: 'Thunderstorm with slight hail', severity: 3 },
99: { icon: 'thunder', zh: '雷暴伴大冰雹', en: 'Thunderstorm with heavy hail', severity: 3 }
};
/** Used for a missing or unknown code; never throws on odd upstream data. */
const WMO_FALLBACK = { icon: 'unknown', zh: '未知天气', en: 'Unknown', severity: 0 };
/**
* Describe one WMO code.
* @param {unknown} code raw `weather_code` from the API
* @returns {{code: number|null, icon: string, zh: string, en: string, severity: number}}
*/
function describeWeather(code) {
const numeric = Number(code);
if (!Number.isFinite(numeric)) return { code: null, ...WMO_FALLBACK };
const entry = WMO_TABLE[Math.trunc(numeric)];
if (!entry) return { code: Math.trunc(numeric), ...WMO_FALLBACK };
return { code: Math.trunc(numeric), ...entry };
}
/** Convert a WMO code into the drawing group used by the weather glyph. */
function weatherIconFor(code, isDay) {
const described = describeWeather(code);
if (described.icon === 'clear' && isDay === false) return 'moon';
return described.icon;
}
/** Localized label for a WMO code. */
function weatherLabel(code, lang) {
const described = describeWeather(code);
return lang === 'en' ? described.en : described.zh;
}
/* ---- src/lib/format.js ---- */
/**
* Pure formatting helpers.
*
* All of these are deliberately free of DOM, React and locale-service access so
* they can be unit-tested in Node and reused by both languages.
*/
const METRIC = 'metric';
const IMPERIAL = 'imperial';
const EN_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/** 16-point compass, Chinese names first so the two arrays stay in sync. */
const COMPASS_ZH = [
'北', '北东北', '东北', '东北东',
'东', '东南东', '东南', '南东南',
'南', '南西南', '西南', '西南西',
'西', '西北西', '西北', '北西北'
];
const COMPASS_EN = [
'N', 'NNE', 'NE', 'ENE',
'E', 'ESE', 'SE', 'SSE',
'S', 'SSW', 'SW', 'WSW',
'W', 'WNW', 'NW', 'NNW'
];
/** UV index bands (WHO scale) with both languages. */
const UV_BANDS = [
{ max: 2, zh: '低', en: 'Low' },
{ max: 5, zh: '中等', en: 'Moderate' },
{ max: 7, zh: '高', en: 'High' },
{ max: 10, zh: '很高', en: 'Very high' },
{ max: Infinity, zh: '极高', en: 'Extreme' }
];
function isNumber(value) {
return typeof value === 'number' && Number.isFinite(value);
}
function roundTo(value, digits) {
if (!isNumber(value)) return null;
const factor = Math.pow(10, digits);
return Math.round(value * factor) / factor;
}
function celsiusToFahrenheit(value) {
return value * 9 / 5 + 32;
}
function kmhToMph(value) {
return value * 0.621371;
}
function mmToInch(value) {
return value / 25.4;
}
function hpaToInHg(value) {
return value * 0.02953;
}
/** Round a Celsius value into the active unit system. */
function convertTemperature(celsius, units) {
if (!isNumber(celsius)) return null;
return units === IMPERIAL ? celsiusToFahrenheit(celsius) : celsius;
}
/** `23°` in the active unit; `—` when the value is missing. */
function formatTemperature(celsius, units) {
const value = convertTemperature(celsius, units);
return value === null ? '—' : `${Math.round(value)}°`;
}
/** Unit suffix for numeric labels, e.g. `km/h` or `mph`. */
function windUnit(units) {
return units === IMPERIAL ? 'mph' : 'km/h';
}
/** Unit suffix for distances of precipitation. */
function precipitationUnit(units) {
return units === IMPERIAL ? 'in' : 'mm';
}
function formatWindSpeed(kmh, units) {
if (!isNumber(kmh)) return '—';
const value = units === IMPERIAL ? kmhToMph(kmh) : kmh;
return `${Math.round(value)} ${windUnit(units)}`;
}
function formatPrecipitation(mm, units) {
if (!isNumber(mm)) return '—';
const value = units === IMPERIAL ? mmToInch(mm) : mm;
const digits = units === IMPERIAL ? 2 : (value >= 10 ? 0 : 1);
return `${roundTo(value, digits)} ${precipitationUnit(units)}`;
}
function formatPressure(hpa, units) {
if (!isNumber(hpa)) return '—';
if (units === IMPERIAL) return `${Math.round(hpaToInHg(hpa) * 100) / 100} inHg`;
return `${Math.round(hpa)} hPa`;
}
function formatPercent(value) {
if (!isNumber(value)) return '—';
return `${Math.round(value)}%`;
}
function formatUv(value) {
if (!isNumber(value)) return '—';
return `${roundTo(value, 1)}`;
}
function uvBand(value, lang) {
if (!isNumber(value)) return '';
const band = UV_BANDS.find(item => value <= item.max) || UV_BANDS[UV_BANDS.length - 1];
return lang === 'en' ? band.en : band.zh;
}
/** Compass label for a meteorological wind direction in degrees. */
function windDirectionLabel(degrees, lang) {
if (!isNumber(degrees)) return '';
const normalized = ((degrees % 360) + 360) % 360;
const index = Math.round(normalized / 22.5) % 16;
return (lang === 'en' ? COMPASS_EN : COMPASS_ZH)[index];
}
/** Split an Open-Meteo local timestamp such as `2026-10-22T06:12` without TZ math. */
function isoParts(value) {
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/.exec(String(value || ''));
if (!match) return null;
return {
year: Number(match[1]),
month: Number(match[2]),
day: Number(match[3]),
hour: match[4] === undefined ? null : Number(match[4]),
minute: match[5] === undefined ? null : Number(match[5])
};
}
/** `06:12` from an API timestamp; `—` when absent. */
function formatClock(value) {
const parts = isoParts(value);
if (!parts || parts.hour === null) return '—';
return `${String(parts.hour).padStart(2, '0')}:${String(parts.minute).padStart(2, '0')}`;
}
/** `06:12` from a local `Date` (used for the "updated at" line). */
function formatClockFromDate(date) {
if (!(date instanceof Date) || Number.isNaN(date.getTime())) return '—';
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
/** Short weekday for a `YYYY-MM-DD` date, independent of the viewer's time zone. */
function formatWeekday(isoDate, lang) {
const parts = isoParts(isoDate);
if (!parts) return '—';
const utc = Date.UTC(parts.year, parts.month - 1, parts.day, 12);
try {
return new Intl.DateTimeFormat(lang === 'en' ? 'en-US' : 'zh-CN', {
weekday: 'short',
timeZone: 'UTC'
}).format(new Date(utc));
} catch (error) {
return new Date(utc).toUTCString().slice(0, 3);
}
}
/** `10月23日` / `Oct 23` for a `YYYY-MM-DD` date. */
function formatMonthDay(isoDate, lang) {
const parts = isoParts(isoDate);
if (!parts) return '';
if (lang === 'en') return `${EN_MONTHS[parts.month - 1]} ${parts.day}`;
return `${parts.month}月${parts.day}日`;
}
/** Human label for a forecast offset: 1 → tomorrow, 2 → the day after, … */
function formatDayOffset(offset, lang, translate) {
if (offset === 0) return translate('day.today');
if (offset === 1) return translate('day.tomorrow');
if (offset === 2) return translate('day.afterTomorrow');
return translate('day.inDays', { n: offset });
}
/** `36.06°N 120.38°E` — a readable fallback when no place name is available. */
function formatCoordinates(lat, lon) {
if (!isNumber(lat) || !isNumber(lon)) return '';
const ns = lat >= 0 ? 'N' : 'S';
const ew = lon >= 0 ? 'E' : 'W';
const latText = Math.abs(lat).toFixed(2);
const lonText = Math.abs(lon).toFixed(2);
return `${latText}°${ns} ${lonText}°${ew}`;
}
/** Stale-data hint in whole minutes. */
function formatAgeMinutes(timestamp, nowMs) {
if (!isNumber(timestamp)) return null;
const reference = isNumber(nowMs) ? nowMs : Date.now();
const elapsed = Math.max(0, reference - timestamp);
return Math.floor(elapsed / 60000);
}
/* ---- src/lib/cache.js ---- */
/**
* Minimal TTL cache over a synchronous storage (localStorage, or an in-memory
* stand-in when storage is unavailable).
*
* The panel paints cached values immediately and only revalidates when they
* are stale, which is what keeps reopening the panel cheap and keeps the
* network quiet while the user switches sessions.
*/
function createTtlCache(storage, prefix, now) {
const clock = typeof now === 'function' ? now : () => Date.now();
const namespace = typeof prefix === 'string' && prefix ? prefix : 'dshw:';
function storageKey(key) {
return `${namespace}${key}`;
}
function readRaw(key) {
try {
return storage.getItem(storageKey(key));
} catch (error) {
return null;
}
}
function isExpired(entry) {
return typeof entry.expiresAt === 'number' && entry.expiresAt <= clock();
}
return {
/**
* @returns {*} the stored value, or `undefined` when absent / expired / corrupt
*/
get(key) {
const raw = readRaw(key);
if (!raw) return undefined;
let entry;
try {
entry = JSON.parse(raw);
} catch (error) {
return undefined;
}
if (!entry || typeof entry !== 'object' || !('value' in entry)) return undefined;
if (isExpired(entry)) {
this.delete(key);
return undefined;
}
return entry.value;
},
/**
* @param {string} key
* @param {*} value JSON-serializable value
* @param {number} ttlMs lifetime in milliseconds
* @returns {boolean} whether the write happened
*/
set(key, value, ttlMs) {
const lifetime = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : 0;
const entry = { value, savedAt: clock(), expiresAt: clock() + lifetime };
try {
storage.setItem(storageKey(key), JSON.stringify(entry));
return true;
} catch (error) {
return false;
}
},
/** Timestamp of the stored value, or `null` when nothing is stored. */
savedAt(key) {
const raw = readRaw(key);
if (!raw) return null;
try {
const entry = JSON.parse(raw);
return entry && typeof entry.savedAt === 'number' ? entry.savedAt : null;
} catch (error) {
return null;
}
},
delete(key) {
try {
storage.removeItem(storageKey(key));
} catch (error) {
/* storage may be full or blocked; dropping is best-effort */
}
}
};
}
/**
* Storage that degrades to memory instead of throwing.
*
* `localStorage` throws in private modes and when the quota is full; the panel
* must keep working in both cases, so every access is guarded.
*/
function createSafeStorage(probeKey) {
const memory = new Map();
let persistent = false;
try {
const probe = probeKey || 'dshw:probe';
window.localStorage.setItem(probe, '1');
window.localStorage.removeItem(probe);
persistent = true;
} catch (error) {
persistent = false;
}
return {
persistent,
getItem(key) {
if (!persistent) return memory.has(key) ? memory.get(key) : null;
try {
return window.localStorage.getItem(key);
} catch (error) {
return memory.has(key) ? memory.get(key) : null;
}
},
setItem(key, value) {
memory.set(key, value);
if (!persistent) return;
try {
window.localStorage.setItem(key, value);
} catch (error) {
/* keep the in-memory copy only */
}
},
removeItem(key) {
memory.delete(key);
if (!persistent) return;
try {
window.localStorage.removeItem(key);
} catch (error) {
/* ignore */
}
}
};
}
/* ---- src/lib/alerts.js ---- */
/**
* 中央气象台(中国气象局)预警信号。
*
* 数据源:`https://www.nmc.cn/rest/findAlarm`,实测返回 `Access-Control-Allow-Origin: *`,
* 因此浏览器可直接读取,不需要 Host 代理。返回的是**全国**当前有效预警(按发布时间倒序),
* 每页最多 100 条;本模块负责翻页、把标题解析成「类型 + 等级」,并按用户所在地过滤。
*
* 标题格式固定为:`<省><市>气象台发布<类型><等级>预警信号`,例如
* `内蒙古自治区呼伦贝尔市气象台发布大风蓝色预警信号`。
* 因此「类型/等级」从标题解析比额外请求详情页可靠:详情页 `publish/alarm/*.html` 不带 CORS。
*/
const ALARM_ENDPOINT = 'https://www.nmc.cn/rest/findAlarm';
const ALARM_PAGE_SIZE = 100;
const ALARM_MAX_PAGES = 3;
/** 等级从低到高;rank 用于排序与「最高等级」判断。 */
const ALERT_LEVELS = [
{ key: 'blue', zh: '蓝色', en: 'Blue', rank: 1 },
{ key: 'yellow', zh: '黄色', en: 'Yellow', rank: 2 },
{ key: 'orange', zh: '橙色', en: 'Orange', rank: 3 },
{ key: 'red', zh: '红色', en: 'Red', rank: 4 }
];
/** 常见预警类型;只用于中英互译与顺序,不限制解析。 */
const ALERT_TYPES = [
{ zh: '台风', en: 'Typhoon' },
{ zh: '暴雨', en: 'Rainstorm' },
{ zh: '暴雪', en: 'Snowstorm' },
{ zh: '寒潮', en: 'Cold wave' },
{ zh: '大风', en: 'Gale' },
{ zh: '沙尘暴', en: 'Sandstorm' },
{ zh: '高温', en: 'Heat' },
{ zh: '干旱', en: 'Drought' },
{ zh: '雷电', en: 'Lightning' },
{ zh: '冰雹', en: 'Hail' },
{ zh: '霜冻', en: 'Frost' },
{ zh: '大雾', en: 'Dense fog' },
{ zh: '霾', en: 'Haze' },
{ zh: '道路结冰', en: 'Road icing' },
{ zh: '海上大风', en: 'Gale at sea' },
{ zh: '海浪', en: 'Wave' },
{ zh: '风暴潮', en: 'Storm surge' },
{ zh: '森林火险', en: 'Forest fire risk' },
{ zh: '强对流', en: 'Severe convection' },
{ zh: '低温', en: 'Low temperature' }
];
/**
* 预警类型图标(emoji,纯展示,不参与解析)。
* 未收录的类型统一用 ⚠️,保证任何类型都有可见标识。
*/
const ALERT_TYPE_ICONS = {
台风: '🌀',
暴雨: '🌧️',
暴雪: '❄️',
寒潮: '🥶',
大风: '💨',
沙尘暴: '🌪️',
沙尘: '🌪️',
高温: '🌡️',
干旱: '🌵',
雷电: '⚡',
雷雨大风: '⛈️',
冰雹: '🧊',
霜冻: '🧊',
大雾: '🌫️',
霾: '😷',
道路结冰: '⛸️',
海上大风: '🌊',
海浪: '🌊',
风暴潮: '🌊',
森林火险: '🔥',
强对流: '⛈️',
低温: '🥶',
地质灾害: '⛰️',
渍涝: '💧'
};
const ALERT_TYPE_FALLBACK_ICON = '⚠️';
function alertTypeIcon(type) {
const key = String(type || '').trim();
return ALERT_TYPE_ICONS[key] || ALERT_TYPE_FALLBACK_ICON;
}
/** Build one page URL; `pageSize` is capped by the service at 100. */
function buildAlarmPageUrl(pageNo, pageSize) {
const page = Number.isFinite(pageNo) && pageNo > 0 ? Math.floor(pageNo) : 1;
const size = Number.isFinite(pageSize) && pageSize > 0 ? Math.min(100, Math.floor(pageSize)) : ALARM_PAGE_SIZE;
return `${ALARM_ENDPOINT}?pageNo=${page}&pageSize=${size}`;
}
/** `2026/10/22 20:12` → epoch ms (treated as Asia/Shanghai wall clock). */
function parseIssueTime(value) {
const match = /^(\d{4})\/(\d{2})\/(\d{2})\s+(\d{2}):(\d{2})/.exec(String(value || '').trim());
if (!match) return null;
const utc = Date.UTC(
Number(match[1]), Number(match[2]) - 1, Number(match[3]),
Number(match[4]) - 8, Number(match[5])
);
return Number.isFinite(utc) ? utc : null;
}
/** Parse `…发布大风蓝色预警信号` into structured fields. */
function parseAlertTitle(title) {
const text = String(title || '');
const level = ALERT_LEVELS.find(item => text.includes(`${item.zh}`)) || null;
const ordered = ALERT_TYPES.slice().sort((left, right) => right.zh.length - left.zh.length);
let typeZh = '';
for (const candidate of ordered) {
if (text.includes(`${candidate.zh}${level ? level.zh : ''}`)) {
typeZh = candidate.zh;
break;
}
}
if (!typeZh && level) {
const stripped = text.replace(/^.*?发布/, '').replace(new RegExp(`${level.zh}.*$`), '');
typeZh = stripped.replace(/预警.*$/, '').trim();
}