Repository navigation
Expand file tree
/
Copy pathweather.js
More file actions
2231 lines (2046 loc) · 143 KB
/
Copy pathweather.js
File metadata and controls
2231 lines (2046 loc) · 143 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
(function WeatherApp() {
'use strict';
// --- CONFIGURATION ---
const CONFIG = {
API_BASE_URL: "https://api.open-meteo.com/v1/forecast",
AIR_QUALITY_API_BASE_URL: "https://air-quality-api.open-meteo.com/v1/air-quality",
PARTICLE_DENSITY_SNOW_DIVISOR: 25000,
PARTICLE_DENSITY_RAIN_DIVISOR: 18000,
MAX_PARTICLES: 250,
MODAL_ACTIVE_CLASS: 'active',
REFRESH_INTERVAL_MINUTES: 60,
REQUEST_TIMEOUT_MS: 15 * 1000,
WEATHER_DETAIL_CACHE_KEY: 'weather_detail_cache_v8_trend_precip_priority_notice_fit',
AIR_QUALITY_CACHE_KEY: 'air_quality_cache_v4',
WMO_MAP: {0:{description:"맑음",icon:"☀️",effect:null},1:{description:"대체로 맑음",icon:"🌤️",effect:null},2:{description:"부분적 흐림",icon:"🌥️",effect:null},3:{description:"흐림",icon:"☁️",effect:null},45:{description:"안개",icon:"🌫️",effect:null},48:{description:"서리 안개",icon:"🌫️❄️",effect:null},51:{description:"가벼운 가랑비",icon:"💧",effect:"rain"},53:{description:"보통 가랑비",icon:"💧",effect:"rain"},55:{description:"강한 가랑비",icon:"💧",effect:"rain"},56:{description:"가벼운 어는 가랑비",icon:"🥶💧",effect:"rain_snow"},57:{description:"강한 어는 가랑비",icon:"🥶💧",effect:"rain_snow"},61:{description:"가벼운 비",icon:"🌧️",effect:"rain"},63:{description:"보통 비",icon:"🌧️",effect:"rain"},65:{description:"강한 비",icon:"🌧️",effect:"rain"},66:{description:"가벼운 어는 비",icon:"🥶🌧️",effect:"rain_snow"},67:{description:"강한 어는 비",icon:"🥶🌧️",effect:"rain_snow"},71:{description:"가벼운 눈",icon:"❄️",effect:"snow"},73:{description:"보통 눈",icon:"❄️",effect:"snow"},75:{description:"강한 눈",icon:"❄️",effect:"snow"},77:{description:"싸락눈",icon:"❄️",effect:"snow"},80:{description:"가벼운 소나기",icon:"🌦️",effect:"rain"},81:{description:"보통 소나기",icon:"🌦️",effect:"rain"},82:{description:"강한 소나기",icon:"⛈️",effect:"rain"},85:{description:"가벼운 소낙눈",icon:"🌨️",effect:"snow"},86:{description:"강한 소낙눈",icon:"🌨️",effect:"snow"},95:{description:"뇌우",icon:"⛈️",effect:"rain"},96:{description:"가벼운 우박 동반 뇌우",icon:"⛈️🧊",effect:"rain"},99:{description:"강한 우박 동반 뇌우",icon:"⛈️🧊",effect:"rain"}},
// [수정] WHO 기준으로 미세먼지 등급 기준을 변경합니다.
AQI_WHO_STANDARDS: {
pm2_5: [
{ limit: 9, level: '좋음', class: 'level-good' },
{ limit: 15, level: '보통', class: 'level-moderate' },
{ limit: 50, level: '나쁨', class: 'level-unhealthy' },
{ limit: Infinity, level: '매우 나쁨', class: 'level-very-unhealthy' }
],
pm10: [
{ limit: 22, level: '좋음', class: 'level-good' },
{ limit: 45, level: '보통', class: 'level-moderate' },
{ limit: 100, level: '나쁨', class: 'level-unhealthy' },
{ limit: Infinity, level: '매우 나쁨', class: 'level-very-unhealthy' }
]
}
};
const urlParams = new URLSearchParams(window.location.search);
const parseCoordinateParam = (value, min, max) => {
const rawValue = String(value ?? '').trim();
if (!/^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(rawValue)) return null;
const numberValue = Number(rawValue);
return Number.isFinite(numberValue) && numberValue >= min && numberValue <= max ? numberValue : null;
};
const LAT = parseCoordinateParam(urlParams.get('lat'), -90, 90);
const LON = parseCoordinateParam(urlParams.get('lon'), -180, 180);
const THEME = urlParams.get('theme') === 'dark' ? 'dark' : 'light';
const getClosestElement = (target, selector) => {
const isTextNode = typeof Node !== 'undefined' && target?.nodeType === Node.TEXT_NODE;
const element = isTextNode ? target.parentElement : target;
return element && typeof element.closest === 'function' ? element.closest(selector) : null;
};
const clearWeatherCaches = () => {
try {
localStorage.removeItem(CONFIG.WEATHER_DETAIL_CACHE_KEY);
localStorage.removeItem(CONFIG.AIR_QUALITY_CACHE_KEY);
} catch (removeError) {
console.warn('날씨 캐시 삭제 실패:', removeError);
}
};
const removeWeatherCacheEntry = (key) => {
try {
localStorage.removeItem(key);
} catch (removeError) {
console.warn('날씨 캐시 정리 실패:', removeError);
}
};
const hasValidTimeSeries = (section, requiredFields) => {
if (!section || typeof section !== 'object' || !Array.isArray(section.time) || section.time.length === 0) {
return false;
}
const itemCount = section.time.length;
const hasValidTimes = section.time.every(time => (
typeof time === 'string'
&& time.trim() !== ''
&& !Number.isNaN(new Date(time).getTime())
));
return hasValidTimes && requiredFields.every(field => (
Array.isArray(section[field]) && section[field].length >= itemCount
));
};
const isWeatherCachePayloadValid = data => {
if (!data || typeof data !== 'object') return false;
const current = data.current || data.current_weather;
const temperature = current?.temperature_2m ?? current?.temperature;
const weatherCode = current?.weather_code ?? current?.weathercode;
const isDay = toFiniteNumber(current?.is_day);
return Boolean(
current
&& typeof current === 'object'
&& toFiniteNumber(temperature) !== null
&& toFiniteNumber(weatherCode) !== null
&& (isDay === 0 || isDay === 1)
&& hasValidTimeSeries(data.hourly, [
'temperature_2m',
'precipitation_probability',
'weather_code',
'is_day'
])
&& hasValidTimeSeries(data.daily, [
'weather_code',
'temperature_2m_max',
'temperature_2m_min'
])
);
};
const isAirQualityCachePayloadValid = data => Boolean(
data
&& typeof data === 'object'
&& data.current
&& typeof data.current === 'object'
&& hasValidTimeSeries(data.hourly, ['pm10', 'pm2_5', 'us_aqi'])
);
const readFreshWeatherCache = (key, now, payloadValidator) => {
const cachedString = localStorage.getItem(key);
if (!cachedString) return null;
try {
const parsed = JSON.parse(cachedString);
const timestamp = toFiniteNumber(parsed?.timestamp);
const cachedLat = toFiniteNumber(parsed?.lat);
const cachedLon = toFiniteNumber(parsed?.lon);
const age = now - timestamp;
const isValid = cachedLat !== null
&& cachedLon !== null
&& cachedLat === LAT
&& cachedLon === LON
&& timestamp !== null
&& age >= 0
&& age < CONFIG.REFRESH_INTERVAL_MINUTES * 60 * 1000
&& payloadValidator(parsed?.data);
if (isValid) {
// 검증에는 숫자로 정규화한 값을 사용하면서 원본 문자열을 그대로 반환하면
// Date 생성 시 Invalid Date가 되거나 좌표/시각의 타입이 호출 경로마다 달라집니다.
return { ...parsed, timestamp, lat: cachedLat, lon: cachedLon };
}
} catch (error) {
console.warn(`날씨 캐시(${key})를 읽지 못해 새로 갱신합니다.`, error);
}
// 시계가 뒤로 바뀌어 미래 타임스탬프가 되었거나 페이로드가 손상된 캐시는
// 유효한 1시간 캐시로 간주하지 않고 제거한 뒤 네트워크에서 다시 가져옵니다.
removeWeatherCacheEntry(key);
return null;
};
// 날씨와 대기질은 서로 다른 시각의 캐시/응답이 한 화면에 함께 쓰일 수 있습니다.
// 화면의 "마지막 업데이트"는 가장 오래된 실제 원본보다 새롭게 표시되어서는 안 됩니다.
const getOldestWeatherSourceTimestamp = (...timestamps) => {
const validTimestamps = timestamps
.map(toFiniteNumber)
.filter(timestamp => timestamp !== null && timestamp > 0);
return validTimestamps.length > 0 ? Math.min(...validTimestamps) : Date.now();
};
const ICON_ANIMATION_MAP = {
'☀️': ['sun'],
'☁️': ['anim-cloud-drift', 'gentleBob-active'],
'🌥️': ['anim-cloud-drift', 'gentleBob-active'],
'🌤️': ['anim-cloud-drift', 'gentleBob-active'],
'🌧️': ['anim-rain-drop', 'gentleBob-active'],
'💧': ['anim-rain-drop', 'gentleBob-active'],
'🌦️': ['anim-rain-drop', 'gentleBob-active'],
'⛈️': ['anim-rain-drop', 'gentleBob-active'],
'❄️': ['anim-snow-flake', 'gentleBob-active'],
'🌨️': ['anim-snow-flake', 'gentleBob-active'],
'default': ['gentleBob-active']
};
// --- DOM ELEMENT CACHING ---
const DOM = {
appContainer: document.getElementById('appContainer'),
loadingSkeleton: document.getElementById('loadingSkeleton'),
forecastContainer: document.getElementById('forecastContainer'),
forecastTrendNotice: document.getElementById('forecastTrendNotice'),
twoWeekTrendSection: document.getElementById('twoWeekTrendSection'),
twoWeekTrendList: document.getElementById('twoWeekTrendList'),
errorMessage: document.getElementById('error'),
weatherEffectsCanvas: document.getElementById('weather-effects-canvas'),
hourlyModal: document.getElementById('hourlyModal'),
closeModalButton: document.getElementById('closeModalButton'),
hourlyForecastList: document.getElementById('hourlyForecastList'),
modalTitle: document.getElementById('modalTitle'),
aqiSection: document.getElementById('aqiSection'),
themeToggleButton: document.getElementById('themeToggle'),
lastUpdated: document.getElementById('lastUpdated'),
mainTitle: document.getElementById('mainTitle'),
subTitle: document.getElementById('subTitle'),
currentWeatherIcon: document.getElementById('currentWeatherIcon'),
currentTemp: document.getElementById('currentTemp'),
currentWeatherDesc: document.getElementById('currentWeatherDesc'),
currentApparentTemp: document.getElementById('currentApparentTemp'),
currentHumidity: document.getElementById('currentHumidity'),
currentWindSpeed: document.getElementById('currentWindSpeed'),
currentWindDir: document.getElementById('currentWindDir'),
currentPrecipitation: document.getElementById('currentPrecipitation'),
currentTime: document.getElementById('currentTime'),
detailedObservationGrid: document.getElementById('detailedObservationGrid'),
weatherBriefingList: document.getElementById('weatherBriefingList'),
weatherBriefingMoreSection: document.getElementById('weatherBriefingMoreSection'),
weatherBriefingMoreList: document.getElementById('weatherBriefingMoreList'),
next24HoursList: document.getElementById('next24HoursList'),
weeklyTempChartCanvas: document.getElementById('weeklyTempChart'),
hourlyTempChartCanvas: document.getElementById('hourlyTempChart'),
currentPm10Value: document.getElementById('currentPm10Value'),
currentPm10Level: document.getElementById('currentPm10Level'),
currentPm25Value: document.getElementById('currentPm25Value'),
currentPm25Level: document.getElementById('currentPm25Level'),
currentUsAqiValue: document.getElementById('currentUsAqiValue'),
currentUsAqiLevel: document.getElementById('currentUsAqiLevel'),
currentUvValue: document.getElementById('currentUvValue'),
currentUvLabel: document.getElementById('currentUvLabel'),
currentUvLevel: document.getElementById('currentUvLevel'),
currentNo2Value: document.getElementById('currentNo2Value'),
currentNo2Note: document.getElementById('currentNo2Note'),
currentOzoneValue: document.getElementById('currentOzoneValue'),
currentOzoneNote: document.getElementById('currentOzoneNote'),
outfitWeatherSection: document.getElementById('outfitWeatherSection'),
outfitClosetGrid: document.getElementById('outfitClosetGrid'),
outfitPieceCount: document.getElementById('outfitPieceCount'),
outfitBasisPill: document.getElementById('outfitBasisPill'),
outfitEmoji: document.getElementById('outfitEmoji'),
outfitTitle: document.getElementById('outfitTitle'),
outfitSummary: document.getElementById('outfitSummary'),
outfitAdviceList: document.getElementById('outfitAdviceList'),
outfitTipsList: document.getElementById('outfitTipsList'),
outfitTagChips: document.getElementById('outfitTagChips'),
outfitColdBar: document.getElementById('outfitColdBar'),
outfitHeatBar: document.getElementById('outfitHeatBar'),
outfitWeatherBar: document.getElementById('outfitWeatherBar'),
outfitColdScore: document.getElementById('outfitColdScore'),
outfitHeatScore: document.getElementById('outfitHeatScore'),
outfitWeatherScore: document.getElementById('outfitWeatherScore'),
};
const weatherEffectsCtx = DOM.weatherEffectsCanvas.getContext('2d');
// --- APP STATE ---
const _appState = {
hourlyFullData: null,
airQualityFullData: null,
weeklyTempChartInstance: null,
hourlyTempChartInstance: null,
weatherEffect: {
animationFrameId: null,
particles: [],
currentEffectType: null
}
};
const OUTFIT_GARMENTS = Object.freeze({
heattech: { label: '히트텍/내의', note: '속부터 보온 🔥', art: 'heattech', emoji: '🔥' },
tshirt: { label: '반팔 티셔츠', note: '가볍게 통풍 👕', art: 'tshirt', emoji: '👕' },
longSleeve: { label: '긴팔 티셔츠', note: '기본 레이어 👚', art: 'longsleeve', emoji: '👚' },
shirt: { label: '얇은 셔츠', note: '일교차 대응 🧺', art: 'shirt', emoji: '👔' },
sweater: { label: '니트/맨투맨', note: '포근한 중간층 🧶', art: 'sweater', emoji: '🧶' },
cardigan: { label: '가디건', note: '입고 벗기 쉬움 🌿', art: 'cardigan', emoji: '🧥' },
jacket: { label: '자켓/바람막이', note: '바람 차단 🌬️', art: 'jacket', emoji: '🧥' },
coat: { label: '코트', note: '쌀쌀한 날씨용 🧥', art: 'coat', emoji: '🧥' },
padding: { label: '패딩/롱패딩', note: '강력 방한 🧊', art: 'padding', emoji: '🧥' },
raincoat: { label: '방수 겉옷', note: '비바람 대비 ☔', art: 'raincoat', emoji: '🧥' },
pants: { label: '긴바지', note: '무난한 하의 👖', art: 'pants', emoji: '👖' },
linen: { label: '얇은 긴바지', note: '린넨/면 추천 🌬️', art: 'linen', emoji: '👖' },
shorts: { label: '반바지', note: '더운 날 시원하게 🩳', art: 'shorts', emoji: '🩳' },
scarf: { label: '목도리', note: '목 보온 🧣', art: 'scarf', emoji: '🧣' },
gloves: { label: '장갑', note: '손끝 방한 🧤', art: 'gloves', emoji: '🧤' },
cap: { label: '모자', note: '햇빛/보온 🧢', art: 'cap', emoji: '🧢' },
umbrella: { label: '우산', note: '비·눈 대비 ☂️', art: 'umbrella', emoji: '☂️' },
shoes: { label: '운동화', note: '걷기 편하게 👟', art: 'shoes', emoji: '👟' },
boots: { label: '방수 신발/부츠', note: '눈·비·추위 대응 🥾', art: 'boots', emoji: '🥾' },
sunglasses: { label: '선글라스', note: '햇빛 강할 때 😎', art: 'sunglasses', emoji: '😎' },
socks: { label: '도톰한 양말', note: '발 보온 🧦', art: 'socks', emoji: '🧦' }
});
const OUTFIT_BANDS = Object.freeze([
{
max: -5,
emoji: '🧊',
title: '강력 방한 모드',
summary: '체감 온도가 매우 낮습니다. 롱패딩급 겉옷과 보온 소품을 모두 챙기시는 편이 좋습니다.',
pieces: ['heattech', 'sweater', 'padding', 'pants', 'socks', 'scarf', 'gloves', 'boots', 'cap'],
advice: ['롱패딩 또는 두꺼운 패딩을 가장 바깥에 입어 주세요.', '상의는 내의 + 니트/맨투맨처럼 2겹 이상이 좋습니다.', '목도리·장갑·도톰한 양말로 노출 부위를 줄이면 체감 추위가 크게 줄어듭니다.'],
tips: ['실외 대기 시간이 길다면 핫팩 🔥도 유용합니다.', '빙판 가능성이 있으면 미끄럼 적은 신발을 고르세요.'],
cold: 96,
heat: 4
},
{
max: 0,
emoji: '🥶',
title: '두꺼운 겨울 외투 추천',
summary: '매우 춥게 느껴질 수 있어 패딩이나 두꺼운 코트가 어울립니다.',
pieces: ['heattech', 'sweater', 'padding', 'pants', 'socks', 'scarf', 'gloves', 'boots'],
advice: ['패딩, 두꺼운 코트, 누빔 점퍼 중 하나는 꼭 입어 주세요.', '속에는 긴팔 이너와 니트류를 겹쳐 입으면 안정적입니다.', '바람이 있으면 목 주변 보온이 특히 중요합니다.'],
tips: ['실내가 더울 수 있으니 안쪽은 벗기 쉬운 레이어로 구성하세요.', '손이 자주 시리면 장갑 🧤을 챙기시는 편이 좋습니다.'],
cold: 88,
heat: 8
},
{
max: 5,
emoji: '🧥',
title: '코트·패딩이 편한 쌀쌀함',
summary: '체감상 겨울 느낌이 남아 있습니다. 두꺼운 겉옷을 중심으로 입으시면 무난합니다.',
pieces: ['longSleeve', 'sweater', 'coat', 'pants', 'socks', 'scarf', 'shoes'],
advice: ['울코트, 두꺼운 자켓, 가벼운 패딩이 잘 맞습니다.', '니트나 맨투맨을 안에 입어 체온을 유지하세요.', '오래 걷는 일정이면 발목이 드러나지 않는 양말을 추천합니다.'],
tips: ['아침·밤 외출이라면 목도리 🧣를 추가하세요.', '추위를 많이 타시면 히트텍을 한 겹 더하세요.'],
cold: 78,
heat: 14
},
{
max: 10,
emoji: '🍂',
title: '가벼운 겨울/초봄 레이어',
summary: '꽤 쌀쌀합니다. 자켓이나 트렌치, 도톰한 니트를 조합해 주세요.',
pieces: ['longSleeve', 'sweater', 'jacket', 'pants', 'socks', 'shoes'],
advice: ['자켓·트렌치·가벼운 코트 같은 겉옷이 필요합니다.', '상의는 긴팔 + 니트/맨투맨 조합이 안정적입니다.', '바람이 강하면 얇은 바람막이를 추가하면 좋습니다.'],
tips: ['실내 활동이 많다면 겉옷을 벗기 쉬운 조합으로 입으세요.', '손발이 찬 편이면 양말을 조금 두껍게 신으세요.'],
cold: 64,
heat: 24
},
{
max: 15,
emoji: '🌼',
title: '가디건·자켓이 딱 좋은 날',
summary: '선선한 편입니다. 얇은 겉옷을 챙기면 하루 종일 편합니다.',
pieces: ['longSleeve', 'shirt', 'cardigan', 'pants', 'shoes'],
advice: ['긴팔 티셔츠나 셔츠 위에 가디건·자켓을 걸치세요.', '하의는 긴바지나 슬랙스가 무난합니다.', '해가 지면 서늘해질 수 있어 겉옷을 챙기는 편이 좋습니다.'],
tips: ['카페·지하철처럼 실내외 온도차가 있으면 레이어가 유리합니다.', '가방에 넣기 쉬운 얇은 겉옷을 추천합니다.'],
cold: 48,
heat: 36
},
{
max: 20,
emoji: '🌤️',
title: '얇은 겉옷 또는 긴팔 단독',
summary: '대체로 쾌적합니다. 긴팔 단독도 가능하지만 바람이 있으면 얇은 겉옷이 좋습니다.',
pieces: ['longSleeve', 'shirt', 'cardigan', 'linen', 'shoes'],
advice: ['긴팔 티셔츠, 셔츠, 얇은 니트가 잘 맞습니다.', '얇은 가디건이나 셔츠형 아우터를 챙기면 온도 변화에 대응하기 쉽습니다.', '두꺼운 외투는 실내에서 덥게 느껴질 수 있습니다.'],
tips: ['걷는 시간이 길면 땀이 차지 않는 면·린넨 소재가 좋습니다.', '밤늦게 귀가하면 얇은 겉옷을 챙기세요.'],
cold: 30,
heat: 50
},
{
max: 24,
emoji: '😊',
title: '가벼운 옷차림 추천',
summary: '따뜻하고 활동하기 좋은 날씨입니다. 반팔 위에 얇은 셔츠를 걸쳐도 좋습니다.',
pieces: ['tshirt', 'shirt', 'linen', 'shoes'],
advice: ['반팔 또는 얇은 긴팔이 적당합니다.', '실내 냉방이 걱정되면 얇은 셔츠나 가디건을 하나 챙기세요.', '하의는 얇은 면바지나 린넨 바지가 편합니다.'],
tips: ['햇빛이 강하면 모자 🧢가 유용합니다.', '많이 걷는다면 통풍 좋은 신발을 추천합니다.'],
cold: 18,
heat: 62
},
{
max: 28,
emoji: '☀️',
title: '초여름처럼 가볍게',
summary: '따뜻하거나 약간 덥게 느껴질 수 있습니다. 통풍 좋은 상의와 얇은 하의를 추천합니다.',
pieces: ['tshirt', 'linen', 'cap', 'shoes'],
advice: ['반팔, 얇은 셔츠, 린넨 소재가 잘 맞습니다.', '두꺼운 데님이나 니트는 답답할 수 있습니다.', '햇빛이 강하면 모자나 선글라스를 챙기세요.'],
tips: ['습도가 높으면 몸에 붙지 않는 여유 있는 핏이 좋습니다.', '물병 💧을 챙기면 장시간 외출에 도움이 됩니다.'],
cold: 8,
heat: 76
},
{
max: 32,
emoji: '🌴',
title: '더운 날씨 · 통풍 우선',
summary: '덥습니다. 반팔, 반바지, 린넨처럼 가볍고 잘 마르는 소재를 추천합니다.',
pieces: ['tshirt', 'shorts', 'cap', 'sunglasses', 'shoes'],
advice: ['반팔과 반바지 또는 얇은 린넨 하의를 추천합니다.', '몸에 달라붙는 두꺼운 소재는 피하는 편이 좋습니다.', '모자·선글라스 등 햇빛 차단 아이템을 챙기세요.'],
tips: ['땀이 많다면 여벌 티셔츠 👕도 좋습니다.', '뜨거운 시간대에는 그늘 위주로 이동하세요.'],
cold: 3,
heat: 90
},
{
max: Infinity,
emoji: '🔥',
title: '폭염 대비 가벼운 차림',
summary: '매우 덥게 느껴질 수 있습니다. 최대한 가볍고 통풍·흡습이 좋은 옷차림이 좋습니다.',
pieces: ['tshirt', 'shorts', 'cap', 'sunglasses', 'shoes'],
advice: ['통풍 좋은 반팔과 반바지를 추천합니다.', '검고 두꺼운 옷보다는 밝고 얇은 소재가 편합니다.', '모자, 선글라스, 물을 꼭 챙기세요.'],
tips: ['장시간 야외 활동은 무리하지 마시고 휴식 시간을 자주 두세요.', '냉방 실내를 오래 이용한다면 아주 얇은 셔츠를 추가해도 좋습니다.'],
cold: 0,
heat: 100
}
]);
const OUTFIT_WET_CODES = new Set([51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82, 95, 96, 99]);
const OUTFIT_SNOW_CODES = new Set([71, 73, 75, 77, 85, 86]);
const OUTFIT_STORM_CODES = new Set([95, 96, 99]);
const OUTFIT_SUNNY_CODES = new Set([0, 1]);
// --- UTILITY FUNCTIONS ---
function getWeatherDetails(wmoCode, isDay = true) {
const normalizedCode = toFiniteNumber(wmoCode);
if (normalizedCode === null) {
return { description: '정보 없음', icon: '❓', effect: null };
}
const details = CONFIG.WMO_MAP[normalizedCode];
if (details) {
let icon = details.icon;
if (!isDay) {
if (normalizedCode === 0) icon = "🌙";
else if (normalizedCode === 1) icon = "☁️🌙";
}
return { ...details, icon };
}
return { description: `코드 ${normalizedCode}`, icon: "❓", effect: null };
}
function formatTime(dateString, includeSeconds = false) {
if (!dateString) return "N/A";
try {
const date = new Date(dateString);
const options = { hour: '2-digit', minute: '2-digit', hour12: false };
if (includeSeconds) options.second = '2-digit';
return date.toLocaleTimeString('ko-KR', options);
} catch (e) {
console.error("Error formatting time:", dateString, e);
return "N/A";
}
}
function degreesToCardinal(deg) {
if (typeof deg !== 'number' || isNaN(deg)) return "N/A";
const cardinals = ["북", "북북동", "북동", "동북동", "동", "동남동", "남동", "남남동", "남", "남남서", "남서", "서남서", "서", "서북서", "북서", "북북서"];
return cardinals[Math.round(deg / 22.5) % 16];
}
function getAqiLevel(pollutant, value) {
if (value == null || isNaN(value)) {
return { level: '정보 없음', class: 'level-default' };
}
const standards = CONFIG.AQI_WHO_STANDARDS[pollutant];
if (!standards) {
return { level: '기준 없음', class: 'level-default' };
}
for (const standard of standards) {
if (value <= standard.limit) {
return { level: standard.level, class: standard.class };
}
}
return { level: '정보 없음', class: 'level-default' };
}
function escapeHTML(value) {
if (window.MothNoteSanitizer?.escapeHtml) {
return window.MothNoteSanitizer.escapeHtml(value);
}
return String(value ?? '').replace(/[&<>"']/g, (ch) => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[ch]));
}
function setSafeHTML(target, html) {
if (!target) return;
const value = String(html ?? '');
if (!value) {
target.textContent = '';
return;
}
if (window.MothNoteSanitizer?.setSanitizedRichHtml) {
window.MothNoteSanitizer.setSanitizedRichHtml(target, value);
return;
}
if (!setSafeHTML.warnedAboutMissingSanitizer) {
console.warn('MothNote sanitizer is unavailable; rendering HTML content as plain text.');
setSafeHTML.warnedAboutMissingSanitizer = true;
}
target.textContent = value;
}
function toFiniteNumber(value) {
if (value === null || value === undefined) return null;
if (typeof value === 'string' && value.trim() === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
}
function formatNumber(value, digits = 0, fallback = '—') {
const number = toFiniteNumber(value);
return number === null ? fallback : number.toFixed(digits);
}
function formatWithUnit(value, digits = 0, unit = '', fallback = '—') {
const number = formatNumber(value, digits, fallback);
return number === fallback ? fallback : `${number}${unit}`;
}
function calculateDewPoint(tempC, humidityPercent) {
const temp = toFiniteNumber(tempC);
const humidity = toFiniteNumber(humidityPercent);
if (temp === null || humidity === null || humidity <= 0) return null;
const a = 17.625;
const b = 243.04;
const gamma = Math.log(humidity / 100) + (a * temp) / (b + temp);
return (b * gamma) / (a - gamma);
}
function calculateWindChill(tempC, windKmh) {
const temp = toFiniteNumber(tempC);
const wind = toFiniteNumber(windKmh);
if (temp === null || wind === null || temp > 10 || wind < 4.8) return null;
return 13.12 + (0.6215 * temp) - (11.37 * (wind ** 0.16)) + (0.3965 * temp * (wind ** 0.16));
}
function getUvLevel(value) {
const uv = toFiniteNumber(value);
if (uv === null) return { level: '정보 없음', class: 'level-default', tone: '자외선 자료 없음' };
if (uv < 3) return { level: '낮음', class: 'level-uv-low', tone: '야외활동 부담이 낮습니다' };
if (uv < 6) return { level: '보통', class: 'level-uv-moderate', tone: '장시간 외출 시 차단이 좋습니다' };
if (uv < 8) return { level: '높음', class: 'level-uv-high', tone: '자외선 차단을 권장합니다' };
if (uv < 11) return { level: '매우 높음', class: 'level-uv-very-high', tone: '강한 차단이 필요합니다' };
return { level: '위험', class: 'level-uv-extreme', tone: '야외활동 최소화를 권합니다' };
}
function getUsAqiLevel(value) {
const aqi = toFiniteNumber(value);
if (aqi === null) return { level: '정보 없음', class: 'level-default', tone: 'US AQI 자료 없음' };
if (aqi <= 50) return { level: '좋음', class: 'level-good', tone: '대체로 쾌적합니다' };
if (aqi <= 100) return { level: '보통', class: 'level-moderate', tone: '민감군은 컨디션을 살펴 주세요' };
if (aqi <= 150) return { level: '민감군 나쁨', class: 'level-unhealthy', tone: '호흡기 민감군은 주의가 필요합니다' };
if (aqi <= 200) return { level: '나쁨', class: 'level-very-unhealthy', tone: '장시간 야외활동을 줄여 주세요' };
if (aqi <= 300) return { level: '매우 나쁨', class: 'level-very-unhealthy', tone: '외출 강도를 낮추는 편이 좋습니다' };
return { level: '위험', class: 'level-very-unhealthy', tone: '실내 활동을 권합니다' };
}
function getOutfitAdvice(feelsLike) {
const value = toFiniteNumber(feelsLike);
if (value === null) return { tag: '확인 필요', tone: 'info', text: '체감온도 자료가 부족합니다. 실제 바람과 햇볕을 함께 확인하세요.' };
if (value <= -5) return { tag: '혹한 대비', tone: 'danger', text: '두꺼운 외투, 장갑, 목도리처럼 노출 부위를 줄이는 옷차림이 좋습니다. 🧣' };
if (value <= 5) return { tag: '매우 추움', tone: 'warn', text: '두꺼운 겉옷과 보온성 있는 이너를 추천드립니다. 🧥' };
if (value <= 12) return { tag: '쌀쌀함', tone: 'info', text: '자켓이나 니트처럼 보온이 되는 겉옷이 편안합니다. 🧶' };
if (value <= 20) return { tag: '선선함', tone: 'good', text: '가벼운 겉옷을 챙기면 아침·저녁 변화에 대응하기 좋습니다. 🧢' };
if (value <= 27) return { tag: '쾌적', tone: 'good', text: '대체로 가벼운 옷차림이 좋고, 활동량이 많다면 통풍을 고려하세요. 👕' };
if (value <= 32) return { tag: '더움', tone: 'warn', text: '통풍이 좋은 옷, 물, 모자 준비를 권합니다. 야외 장시간 활동은 쉬어가세요. 🧃' };
return { tag: '폭염 체감', tone: 'danger', text: '그늘, 수분, 휴식이 중요합니다. 낮 시간대 무리한 야외활동은 피하는 편이 안전합니다. 🥵' };
}
function clampOutfitScore(value, min = 0, max = 100) {
const number = toFiniteNumber(value);
if (number === null) return min;
return Math.max(min, Math.min(max, number));
}
function roundOutfitNumber(value, digits = 1) {
const number = toFiniteNumber(value);
if (number === null) return null;
const scale = 10 ** digits;
return Math.round(number * scale) / scale;
}
function getOutfitBaseBand(temp, feels) {
const safeTemp = toFiniteNumber(temp) ?? toFiniteNumber(feels) ?? 18;
const safeFeels = toFiniteNumber(feels) ?? safeTemp;
const comfortTemp = roundOutfitNumber((safeFeels * 0.72) + (safeTemp * 0.28), 1);
const band = OUTFIT_BANDS.find((item) => comfortTemp <= item.max) || OUTFIT_BANDS[OUTFIT_BANDS.length - 1];
return { band, comfortTemp };
}
function dedupeOutfitPieces(pieces) {
return [...new Set(pieces)].filter((key) => OUTFIT_GARMENTS[key]);
}
function scoreOutfitWeatherProtection({ code, precipitation, precipitationProbability, wind, gust, snowfall }) {
let score = 10;
if (OUTFIT_WET_CODES.has(Number(code)) || (toFiniteNumber(precipitation) ?? 0) > 0 || (toFiniteNumber(precipitationProbability) ?? 0) >= 60) score += 45;
if (OUTFIT_SNOW_CODES.has(Number(code)) || (toFiniteNumber(snowfall) ?? 0) > 0) score += 22;
if (OUTFIT_STORM_CODES.has(Number(code))) score += 25;
if ((toFiniteNumber(wind) ?? 0) >= 18) score += 18;
if ((toFiniteNumber(gust) ?? 0) >= 30) score += 18;
return clampOutfitScore(score);
}
function buildOutfitWeatherSnapshot(current, hourly, dailyData, aqiData) {
if (!current) return null;
const closestIndex = getClosestHourlyIndex(current.time, hourly);
const startIndex = getHourlyStartIndex(hourly, current.time);
const air = getAirQualityMetrics(aqiData, dailyData, current.time);
const temperature = current.temperature_2m ?? current.temperature ?? getHourlyValue(hourly, 'temperature_2m', closestIndex);
const apparent = current.apparent_temperature ?? getHourlyValue(hourly, 'apparent_temperature', closestIndex) ?? temperature;
const precipitation = current.precipitation ?? getHourlyValue(hourly, 'precipitation', closestIndex) ?? 0;
const precipitationProbability = getHourlyValue(hourly, 'precipitation_probability', closestIndex) ?? maxNextHourly(hourly, 'precipitation_probability', startIndex, 6) ?? 0;
return {
temperature_2m: temperature,
apparent_temperature: apparent,
relative_humidity_2m: current.relative_humidity_2m ?? getHourlyValue(hourly, 'relative_humidity_2m', closestIndex),
precipitation,
precipitation_probability: precipitationProbability,
precipitation_probability_24h: maxNextHourly(hourly, 'precipitation_probability', startIndex, 24),
snowfall: current.snowfall ?? getHourlyValue(hourly, 'snowfall', closestIndex) ?? dailyData?.snowfall_sum?.[0] ?? 0,
weather_code: current.weather_code ?? current.weathercode ?? getHourlyValue(hourly, 'weather_code', closestIndex),
cloud_cover: current.cloud_cover ?? getHourlyValue(hourly, 'cloud_cover', closestIndex),
wind_speed_10m: current.wind_speed_10m ?? current.windspeed ?? getHourlyValue(hourly, 'wind_speed_10m', closestIndex),
wind_gusts_10m: current.wind_gusts_10m ?? getHourlyValue(hourly, 'wind_gusts_10m', closestIndex) ?? maxNextHourly(hourly, 'wind_gusts_10m', startIndex, 6),
max_wind_gust_24h: Math.max(
toFiniteNumber(maxNextHourly(hourly, 'wind_gusts_10m', startIndex, 24)) ?? 0,
toFiniteNumber(dailyData?.wind_gusts_10m_max?.[0]) ?? 0,
toFiniteNumber(current.wind_gusts_10m) ?? 0
),
is_day: current.is_day ?? getHourlyValue(hourly, 'is_day', closestIndex) ?? 1,
uv_index: air.uvValue ?? getHourlyValue(hourly, 'uv_index', closestIndex) ?? dailyData?.uv_index_max?.[0] ?? null,
daily_high: dailyData?.temperature_2m_max?.[0] ?? null,
daily_low: dailyData?.temperature_2m_min?.[0] ?? null,
time: current.time
};
}
function makeOutfitRecommendation(weather) {
const temp = toFiniteNumber(weather.temperature_2m);
const feels = toFiniteNumber(weather.apparent_temperature) ?? temp;
const humidity = toFiniteNumber(weather.relative_humidity_2m) ?? 0;
const precipitation = toFiniteNumber(weather.precipitation) ?? 0;
const precipitationProbability = toFiniteNumber(weather.precipitation_probability_24h ?? weather.precipitation_probability) ?? 0;
const snowfall = toFiniteNumber(weather.snowfall) ?? 0;
const wind = toFiniteNumber(weather.wind_speed_10m) ?? 0;
const gust = toFiniteNumber(weather.max_wind_gust_24h ?? weather.wind_gusts_10m) ?? wind;
const code = Number(weather.weather_code);
const cloud = toFiniteNumber(weather.cloud_cover) ?? 0;
const uv = toFiniteNumber(weather.uv_index);
const isDay = Number(weather.is_day ?? 1);
const { band, comfortTemp } = getOutfitBaseBand(temp, feels);
const dailyHigh = toFiniteNumber(weather.daily_high);
const dailyLow = toFiniteNumber(weather.daily_low);
const dailyRange = dailyHigh !== null && dailyLow !== null ? dailyHigh - dailyLow : null;
const pieces = [...band.pieces];
const advice = [...band.advice];
const tips = [...band.tips];
const tags = [`🌡️ 체감 ${formatNumber(feels, 1, '--')}°C`, `🧮 추천 기준 ${formatNumber(comfortTemp, 1, '--')}°C`];
const hasWetSignal = OUTFIT_WET_CODES.has(code) || precipitation > 0 || precipitationProbability >= 55;
if (hasWetSignal) {
pieces.push('umbrella', feels <= 20 ? 'raincoat' : 'cap');
const probabilityText = precipitationProbability > 0 ? `앞으로 24시간 최대 강수확률이 ${formatWithUnit(precipitationProbability, 0, '%')} 수준입니다.` : '강수 신호가 잡혀 있습니다.';
advice.push(`${probabilityText} 우산 또는 방수 겉옷을 챙기시는 편이 좋습니다.`);
tips.push('젖으면 체감 온도가 더 낮아질 수 있으니 신발과 양말도 신경 써 주세요.');
tags.push('☔ 강수 대비');
}
if (OUTFIT_SNOW_CODES.has(code) || snowfall > 0) {
pieces.push('boots', 'gloves', 'scarf');
advice.push('눈 신호가 있어 미끄럼 적고 물이 덜 스며드는 신발을 추천합니다.');
tips.push('눈이 녹은 길에서는 발이 젖기 쉬우니 방수 신발이나 여분 양말을 고려하세요.');
tags.push('❄️ 눈 대비');
}
if (OUTFIT_STORM_CODES.has(code)) {
advice.push('뇌우가 잡힌 상태라면 우산만 믿기보다 가능한 실내 이동 동선을 우선해 주세요.');
tips.push('강풍과 낙뢰 가능성이 있으면 넓게 열린 공간은 피하는 편이 안전합니다.');
tags.push('⛈️ 뇌우 주의');
}
if ((wind >= 18 || gust >= 30) && feels <= 22) {
pieces.push('jacket');
advice.push('바람이 체감 추위를 키울 수 있어 바람막이 성격의 겉옷이 유리합니다.');
tags.push('🌬️ 바람 조정');
}
if (humidity >= 80 && feels >= 23) {
advice.push('습도가 높아 끈적하게 느껴질 수 있으니 몸에 붙지 않는 통풍 좋은 옷을 고르세요.');
tips.push('땀이 잘 마르는 소재와 여유 있는 핏이 쾌적합니다.');
tags.push('💧 습도 높음');
}
if (isDay && (OUTFIT_SUNNY_CODES.has(code) || (uv !== null && uv >= 6)) && (cloud <= 55 || uv >= 6) && feels >= 20) {
pieces.push('cap', 'sunglasses');
advice.push('햇빛이나 자외선이 강하게 느껴질 수 있어 모자나 선글라스를 챙기면 좋습니다.');
tips.push('낮 시간대 야외 이동이 길면 그늘 휴식과 물을 함께 챙기세요.');
tags.push('😎 햇빛 대비');
}
if (temp !== null && feels !== null && feels - temp <= -3 && feels <= 18) {
advice.push('실제 기온보다 체감이 낮습니다. 얇은 겉옷 한 겹을 추가하면 안정적입니다.');
tags.push('🧊 체감 낮음');
}
if (dailyRange !== null && dailyRange >= 10) {
pieces.push(feels >= 20 ? 'shirt' : 'cardigan');
tips.push(`오늘 일교차가 약 ${formatWithUnit(dailyRange, 1, '°C')}입니다. 낮과 밤에 벗고 입기 쉬운 레이어가 유리합니다.`);
tags.push('🌗 일교차 큼');
}
const protection = scoreOutfitWeatherProtection({ code, precipitation, precipitationProbability, wind, gust, snowfall });
const cleanPieces = dedupeOutfitPieces(pieces).slice(0, 9);
const coldScore = clampOutfitScore(Math.round(band.cold + Math.max(0, 12 - (feels ?? 12)) * 1.4 + (wind >= 18 ? 8 : 0)));
const heatScore = clampOutfitScore(Math.round(band.heat + Math.max(0, (feels ?? 18) - 24) * 2 + (humidity >= 80 && (feels ?? 0) >= 23 ? 8 : 0)));
return {
title: band.title,
emoji: band.emoji,
summary: band.summary,
pieces: cleanPieces,
advice: advice.slice(0, 6),
tips: tips.slice(0, 5),
tags: [...new Set(tags)].slice(0, 7),
comfortTemp,
coldScore,
heatScore,
weatherScore: protection
};
}
function renderOutfitList(list, target) {
if (!target) return;
const emojis = ['✅', '🧥', '🌡️', '🌬️', '☔', '✨'];
setSafeHTML(target, list.map((text, index) => `<li><span class="bullet">${emojis[index % emojis.length]}</span><span>${escapeHTML(text)}</span></li>`).join(''));
}
function renderOutfitTags(tags) {
if (!DOM.outfitTagChips) return;
setSafeHTML(DOM.outfitTagChips, tags.map((tag) => `<span class="outfit-chip">${escapeHTML(tag)}</span>`).join(''));
}
function renderOutfitCloset(pieceKeys) {
if (!DOM.outfitClosetGrid) return;
if (!pieceKeys.length) {
setSafeHTML(DOM.outfitClosetGrid, '<div class="empty-closet">추천 의류가 없습니다. 🧦</div>');
if (DOM.outfitPieceCount) DOM.outfitPieceCount.textContent = '👚 0개';
return;
}
setSafeHTML(DOM.outfitClosetGrid, pieceKeys.map((key) => {
const item = OUTFIT_GARMENTS[key];
return `
<article class="clothing-card" aria-label="${escapeHTML(item.label)}">
<div class="garment ${escapeHTML(item.art)}" aria-hidden="true">
<span class="s1"></span><span class="s2"></span><span class="s3"></span><span class="s4"></span>
</div>
<div><strong>${item.emoji} ${escapeHTML(item.label)}</strong><span class="note">${escapeHTML(item.note)}</span></div>
</article>
`;
}).join(''));
if (DOM.outfitPieceCount) DOM.outfitPieceCount.textContent = `👚 ${pieceKeys.length}개`;
}
function renderOutfitScores(rec) {
if (DOM.outfitColdBar) DOM.outfitColdBar.style.setProperty('--value', `${rec.coldScore}%`);
if (DOM.outfitHeatBar) DOM.outfitHeatBar.style.setProperty('--value', `${rec.heatScore}%`);
if (DOM.outfitWeatherBar) DOM.outfitWeatherBar.style.setProperty('--value', `${rec.weatherScore}%`);
if (DOM.outfitColdScore) DOM.outfitColdScore.textContent = String(rec.coldScore);
if (DOM.outfitHeatScore) DOM.outfitHeatScore.textContent = String(rec.heatScore);
if (DOM.outfitWeatherScore) DOM.outfitWeatherScore.textContent = String(rec.weatherScore);
}
function renderOutfitFeature(current, hourly, dailyData, aqiData) {
if (!DOM.outfitWeatherSection) return;
const snapshot = buildOutfitWeatherSnapshot(current, hourly, dailyData, aqiData);
if (!snapshot) {
if (DOM.outfitTitle) DOM.outfitTitle.textContent = '추천을 만들 수 없습니다';
if (DOM.outfitSummary) DOM.outfitSummary.textContent = '현재 날씨 데이터가 부족해 옷차림 추천을 표시하지 못했습니다.';
renderOutfitList(['현재 날씨 데이터를 불러온 뒤 다시 확인해 주세요.'], DOM.outfitAdviceList);
renderOutfitList(['기온·바람·강수 정보를 확인할 수 없습니다.'], DOM.outfitTipsList);
renderOutfitTags([]);
renderOutfitCloset([]);
return;
}
const rec = makeOutfitRecommendation(snapshot);
if (DOM.outfitBasisPill) DOM.outfitBasisPill.textContent = `🌡️ 기준 ${formatNumber(rec.comfortTemp, 1, '--')}°C`;
if (DOM.outfitEmoji) DOM.outfitEmoji.textContent = rec.emoji;
if (DOM.outfitTitle) DOM.outfitTitle.textContent = rec.title;
if (DOM.outfitSummary) DOM.outfitSummary.textContent = rec.summary;
renderOutfitList(rec.advice, DOM.outfitAdviceList);
renderOutfitList(rec.tips, DOM.outfitTipsList);
renderOutfitTags(rec.tags);
renderOutfitCloset(rec.pieces);
renderOutfitScores(rec);
}
function getOutdoorActivityAdvice(uv, gust, weatherCode, air) {
const uvValue = toFiniteNumber(uv);
const gustValue = toFiniteNumber(gust);
const stormy = [82, 95, 96, 99].includes(Number(weatherCode));
if (stormy) return { tag: '뇌우 유의', tone: 'danger', text: '천둥·번개 가능성이 있으므로 개활지, 산행, 수상 활동은 피하는 것이 좋습니다. ⚡' };
if (gustValue !== null && gustValue >= 50) return { tag: '강풍 유의', tone: 'danger', text: '돌풍이 강할 수 있습니다. 간판, 우산, 자전거, 해안가 활동에 주의하세요. 🌬️' };
if (uvValue !== null && uvValue >= 8) return { tag: '자외선 강함', tone: 'warn', text: '자외선이 매우 강합니다. 모자, 선글라스, 자외선 차단제를 준비하세요. 🧴' };
if (uvValue !== null && uvValue >= 6) return { tag: '차단 권장', tone: 'warn', text: '낮 시간대 햇볕이 강할 수 있습니다. 긴 야외활동은 그늘 휴식을 섞어주세요. 🕶️' };
if (air?.hasAirQualityWarning) return { tag: '대기질 주의', tone: 'warn', text: '대기질 주의 신호가 있습니다. 기온이나 바람이 무난해도 야외활동에 적합하다고 판단할 수 없으므로 외출 전 대기질을 확인해 주세요.' };
if (!air?.hasAirQualityAssessment || uvValue === null || gustValue === null || toFiniteNumber(weatherCode) === null) return { tag: '자료 확인', tone: 'info', text: '대기질 또는 기상 자료가 부족해 야외활동 적합 여부를 판단할 수 없습니다. 외출 전 최신 정보를 확인해 주세요.' };
return { tag: '활동 무난', tone: 'good', text: '위험 신호가 크지 않습니다. 다만 시간별 강수와 바람 변화는 한 번 더 확인하세요. 🚶' };
}
function getDiurnalRangeBriefing(dailyData) {
const todayHigh = toFiniteNumber(dailyData?.temperature_2m_max?.[0]);
const todayLow = toFiniteNumber(dailyData?.temperature_2m_min?.[0]);
if (todayHigh === null || todayLow === null) {
return { tag: '확인 필요', tone: 'info', text: '오늘 최고·최저기온 자료가 부족합니다. 시간별 기온 변화를 함께 확인해 주세요.' };
}
const range = todayHigh - todayLow;
const base = `오늘 최고기온은 ${formatWithUnit(todayHigh, 1, '°C')}, 최저기온은 ${formatWithUnit(todayLow, 1, '°C')}로 일교차가 ${formatWithUnit(range, 1, '°C')}입니다.`;
if (range >= 10) {
return { tag: '일교차 큼', tone: 'warn', text: `${base} 아침·저녁 옷차림 조절을 권장합니다.` };
}
return { tag: '일교차 무난', tone: 'good', text: `${base} 온도 변화가 큰 편은 아닙니다.` };
}
function average(values) {
const numeric = (Array.isArray(values) ? values : []).map(toFiniteNumber).filter((value) => value !== null);
if (!numeric.length) return null;
return numeric.reduce((sum, value) => sum + value, 0) / numeric.length;
}
function sumNextHourly(hourly, variable, startIndex, hours) {
const values = getNextHourlyNumbers(hourly, variable, startIndex, hours);
return values.length ? values.reduce((sum, value) => sum + value, 0) : null;
}
function getHourlyEntry(hourly, variable, index) {
const value = getHourlyValue(hourly, variable, index);
const numeric = toFiniteNumber(value);
if (numeric === null || !hourly?.time?.[index]) return null;
return { value: numeric, index, time: hourly.time[index] };
}
function maxNextHourlyEntry(hourly, variable, startIndex, hours) {
if (!hourly?.time?.length || !Array.isArray(hourly[variable]) || startIndex < 0) return null;
let best = null;
const endIndex = Math.min(startIndex + hours, hourly.time.length, hourly[variable].length);
for (let index = startIndex; index < endIndex; index += 1) {
const entry = getHourlyEntry(hourly, variable, index);
if (!entry) continue;
if (!best || entry.value > best.value) best = entry;
}
return best;
}
function minNextHourlyEntry(hourly, variable, startIndex, hours) {
if (!hourly?.time?.length || !Array.isArray(hourly[variable]) || startIndex < 0) return null;
let best = null;
const endIndex = Math.min(startIndex + hours, hourly.time.length, hourly[variable].length);
for (let index = startIndex; index < endIndex; index += 1) {
const entry = getHourlyEntry(hourly, variable, index);
if (!entry) continue;
if (!best || entry.value < best.value) best = entry;
}
return best;
}
function isPrecipitationWeatherCode(code) {
return [51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 71, 73, 75, 77, 80, 81, 82, 85, 86, 95, 96, 99].includes(Number(code));
}
function addHoursToIsoLikeString(iso, hours = 1) {
if (!iso || !String(iso).includes('T')) return iso || '';
const [datePart, timePart = '00:00'] = String(iso).split('T');
const [year, month, day] = datePart.split('-').map(Number);
const [hour = 0, minute = 0] = timePart.split(':').map(Number);
const date = new Date(year, (month || 1) - 1, day || 1, hour || 0, minute || 0);
date.setHours(date.getHours() + hours);
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
const h = String(date.getHours()).padStart(2, '0');
const min = String(date.getMinutes()).padStart(2, '0');
return `${y}-${m}-${d}T${h}:${min}`;
}
function formatHourRange(hourly, startIndex, endIndex) {
if (!hourly?.time?.[startIndex]) return '시간대 정보 없음';
const nextEnd = hourly.time[endIndex + 1] || addHoursToIsoLikeString(hourly.time[endIndex], 1);
return `${formatTime(hourly.time[startIndex])}~${formatTime(nextEnd)}`;
}
function describeIndexRanges(hourly, indices, maxRanges = 2) {
if (!Array.isArray(indices) || !indices.length) return '';
const sorted = [...new Set(indices)].sort((a, b) => a - b);
const ranges = [];
let start = sorted[0];
let previous = sorted[0];
for (let i = 1; i < sorted.length; i += 1) {
if (sorted[i] === previous + 1) {
previous = sorted[i];
continue;
}
ranges.push([start, previous]);
start = previous = sorted[i];
}
ranges.push([start, previous]);
return ranges.slice(0, maxRanges).map(([s, e]) => formatHourRange(hourly, s, e)).join(', ');
}
function findPrecipitationWindow(hourly, startIndex, hours = 24) {
if (!hourly?.time?.length || startIndex < 0) return null;
const indices = [];
const endIndex = Math.min(startIndex + hours, hourly.time.length);
for (let index = startIndex; index < endIndex; index += 1) {
const probability = toFiniteNumber(getHourlyValue(hourly, 'precipitation_probability', index)) ?? 0;
const precipitation = toFiniteNumber(getHourlyValue(hourly, 'precipitation', index)) ?? 0;
const code = getHourlyValue(hourly, 'weather_code', index);
if (probability >= 40 || precipitation >= 0.1 || isPrecipitationWeatherCode(code)) indices.push(index);
}
if (!indices.length) return null;
return {
indices,
label: describeIndexRanges(hourly, indices),
peak: maxNextHourlyEntry(hourly, 'precipitation_probability', startIndex, hours)
};
}
function calculateRollingHourlyAverage(hourly, variable, currentTime, hours = 24) {
if (!hourly?.time?.length || !Array.isArray(hourly[variable])) return null;
let currentIndex = -1;
const key = String(currentTime || hourly.time[0]);
for (let index = 0; index < hourly.time.length; index += 1) {
if (String(hourly.time[index]) <= key) currentIndex = index;
}
if (currentIndex < 0) currentIndex = getClosestHourlyIndex(currentTime, hourly);
const start = Math.max(0, currentIndex - hours + 1);
const values = hourly[variable].slice(start, currentIndex + 1).map(toFiniteNumber).filter((value) => value !== null);
return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
}
function getAirQualityMetrics(aqiData, dailyData, currentTime) {
const current = aqiData?.current || null;
const hourly = aqiData?.hourly || null;
const pm10Current = current?.pm10 ?? null;
const pm25Current = current?.pm2_5 ?? null;
const pm10Avg24 = calculateRollingHourlyAverage(hourly, 'pm10', current?.time || currentTime, 24) ?? pm10Current;
const pm25Avg24 = calculateRollingHourlyAverage(hourly, 'pm2_5', current?.time || currentTime, 24) ?? pm25Current;
const usAqi = current?.us_aqi ?? null;
const uvCurrent = current?.uv_index ?? null;
const uvDailyMax = dailyData?.uv_index_max?.[0] ?? null;
const uvValue = uvCurrent ?? uvDailyMax;
const uvSource = uvCurrent != null ? '현재 자외선 지수' : '오늘 최대 자외선';
const pm10Info = getAqiLevel('pm10', pm10Avg24);
const pm25Info = getAqiLevel('pm2_5', pm25Avg24);
// 결측치를 양호한 값으로 간주하지 않습니다. 종합 AQI 또는 두 미세먼지
// 지표가 있어야 긍정 판정을 하되, 확인된 나쁜 지표의 경고는 항상 유지합니다.
const hasAirQualityAssessment = toFiniteNumber(usAqi) !== null
|| (toFiniteNumber(pm10Avg24) !== null && toFiniteNumber(pm25Avg24) !== null);
const hasAirQualityWarning = (toFiniteNumber(usAqi) ?? 0) > 100
|| ['나쁨', '매우 나쁨'].includes(pm10Info.level)
|| ['나쁨', '매우 나쁨'].includes(pm25Info.level);
return {
pm10Current,
pm25Current,
pm10Avg24,
pm25Avg24,
pm10Info,
pm25Info,
hasAirQualityAssessment,
hasAirQualityWarning,
usAqi,
usAqiInfo: getUsAqiLevel(usAqi),
uvValue,
uvSource,
uvInfo: getUvLevel(uvValue),
no2: current?.nitrogen_dioxide ?? null,
ozone: current?.ozone ?? null
};
}
function getToneFromSeverity(severity) {
if (severity >= 3) return 'danger';
if (severity >= 2) return 'warn';
if (severity >= 1) return 'info';
return 'good';
}
function buildRiskSignals(current, hourly, dailyData, aqiData, startIndex) {
const risks = [];
const maxRainProb = maxNextHourly(hourly, 'precipitation_probability', startIndex, 24);
const rainSum24 = sumNextHourly(hourly, 'precipitation', startIndex, 24);
const maxGust = Math.max(
toFiniteNumber(maxNextHourly(hourly, 'wind_gusts_10m', startIndex, 24)) ?? 0,
toFiniteNumber(dailyData?.wind_gusts_10m_max?.[0]) ?? 0,
toFiniteNumber(current?.wind_gusts_10m) ?? 0
);
const uvValue = getAirQualityMetrics(aqiData, dailyData, current?.time).uvValue;
const air = getAirQualityMetrics(aqiData, dailyData, current?.time);
const todayHigh = toFiniteNumber(dailyData?.temperature_2m_max?.[0]);
const todayLow = toFiniteNumber(dailyData?.temperature_2m_min?.[0]);
const diurnalRange = todayHigh !== null && todayLow !== null ? todayHigh - todayLow : null;
const humidity = toFiniteNumber(current?.relative_humidity_2m ?? getHourlyValue(hourly, 'relative_humidity_2m', startIndex));
const minVisibility = minNextHourly(hourly, 'visibility', startIndex, 12);
if ((toFiniteNumber(maxRainProb) ?? 0) >= 65 || (toFiniteNumber(rainSum24) ?? 0) >= 5) risks.push({ label: `강수 ${formatWithUnit(maxRainProb, 0, '%')}`, severity: 3 });
else if ((toFiniteNumber(maxRainProb) ?? 0) >= 40 || (toFiniteNumber(rainSum24) ?? 0) > 0) risks.push({ label: `비 가능성 ${formatWithUnit(maxRainProb, 0, '%')}`, severity: 2 });
if (maxGust >= 50) risks.push({ label: `돌풍 ${formatWithUnit(maxGust, 0, ' km/h')}`, severity: 3 });
else if (maxGust >= 35) risks.push({ label: `바람 ${formatWithUnit(maxGust, 0, ' km/h')}`, severity: 2 });
if ((toFiniteNumber(uvValue) ?? 0) >= 8) risks.push({ label: `자외선 ${formatNumber(uvValue, 1)}`, severity: 3 });
else if ((toFiniteNumber(uvValue) ?? 0) >= 6) risks.push({ label: `자외선 ${formatNumber(uvValue, 1)}`, severity: 2 });
if (air.hasAirQualityWarning) risks.push({ label: '대기질 주의', severity: 2 });
else if (!air.hasAirQualityAssessment) risks.push({ label: '대기질 자료 확인', severity: 1 });
if (toFiniteNumber(uvValue) === null) risks.push({ label: '자외선 자료 확인', severity: 1 });
if (diurnalRange !== null && diurnalRange >= 10) risks.push({ label: `일교차 ${formatWithUnit(diurnalRange, 1, '°C')}`, severity: 2 });
if (humidity !== null && humidity >= 85) risks.push({ label: `높은 습도 ${formatWithUnit(humidity, 0, '%')}`, severity: 1 });
if (minVisibility !== null && minVisibility < 5000) risks.push({ label: `시정 저하`, severity: minVisibility < 1000 ? 3 : 2 });