-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
2164 lines (1889 loc) · 104 KB
/
Copy pathapp.js
File metadata and controls
2164 lines (1889 loc) · 104 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
// app.js
// [설계 전제 / 수정 금지선]
// 이 앱은 여러 탭에서 동일한 문서를 동시에 편집하는 것 자체를 지원하지 않고, 가정하지도 않습니다.
// 저장 안정화 코드는 단일 활성 문서의 비동기 작업 순서와 복구 안정성을 위한 것이며,
// cross-tab 동기화, 문서 컨텍스트 간 병합, localStorage lease lock, storage event 기반 조정으로 확장하지 않습니다.
import { state, subscribe, setState, findFolder, findNote, CONSTANTS, buildNoteMap } from './state.js';
import { loadData, handleExport, handleImport, setupImportHandler, saveSession, sanitizeSettings } from './storage.js';
import {
folderList, noteList, addFolderBtn, addNoteBtn, emptyTrashBtn, searchInput, clearSearchBtn, noteSortSelect,
noteTitleInput, noteContentTextarea, noteContentView, shortcutGuideBtn, settingsBtn,
showToast, showShortcutModal, sortNotes, showDatePickerPopover, showConfirm as showConfirmModal,
settingsModal, settingsModalCloseBtn, settingsTabs,
settingsCol1Width, settingsCol2Width,
settingsEditorFontFamily, settingsEditorFontSize,
settingsWeatherLat, settingsWeatherLon,
settingsExportBtn, settingsImportBtn, settingsResetBtn, settingsSaveBtn,
settingsWeatherCitySearch, settingsWeatherCitySearchBtn, settingsWeatherCityResults,
// [기능 추가] 새로 추가된 요소를 가져옵니다.
settingsStorageUsage,
editorContainer,
habitTrackerBtn, habitTrackerContainer, habitTrackerIframe, closeHabitTrackerBtn,
// [기능 추가] 다이어트 챌린지 관련 요소
dietChallengeBtn, dietChallengeContainer, dietChallengeIframe, closeDietChallengeBtn
} from './components.js';
import { renderAll, clearSortedNotesCache } from './renderer.js';
// [버그 수정] itemActions.js에서 handleRestoreItem, handleTextareaKeyDown 함수를 가져옵니다.
import {
handleAddFolder, handleAddNote, handleEmptyTrash, handlePinNote,
handleDelete,
handleRestoreItem,
handlePermanentlyDeleteItem,
startRename, handleUserInput, saveCurrentNoteIfChanged, handleToggleFavorite, setCalendarRenderer,
finishPendingRename,
toYYYYMMDD,
parseYYYYMMDDLocal,
updateNoteCreationDates,
forceResolvePendingRename,
getPendingRenameEmergencySnapshot,
persistEmergencyChangesBackupEntry,
performTransactionalUpdate,
performDeleteItem,
handleTextareaKeyDown,
} from './itemActions.js';
import {
changeActiveFolder, changeActiveNote, handleSearchInput,
handleClearSearch, handleSortChange, confirmNavigation, cancelPendingSearchRequest
} from './navigationActions.js';
let appSettings = JSON.parse(JSON.stringify(CONSTANTS.DEFAULT_SETTINGS));
let isSavingSettings = false;
let weatherCitySearchRequestId = 0;
let weatherCitySearchAbortController = null;
const persistAppSettings = (settingsToPersist) => {
const sanitizedSettings = sanitizeSettings(settingsToPersist);
try {
localStorage.setItem(CONSTANTS.LS_KEY_SETTINGS, JSON.stringify(sanitizedSettings));
return sanitizedSettings;
} catch (error) {
console.error('Settings persistence failed:', error);
showToast('설정을 저장하지 못했습니다. 저장 공간 또는 브라우저 권한을 확인해주세요.', CONSTANTS.TOAST_TYPE.ERROR);
return null;
}
};
const clearDashboardWeatherCache = () => {
try {
localStorage.removeItem(CONSTANTS.DASHBOARD.WEATHER_CACHE_KEY);
} catch (error) {
console.warn('Weather cache removal failed:', error);
}
};
const DASHBOARD_WEATHER_CACHE_DURATION_MS = 60 * 60 * 1000;
const DASHBOARD_WEATHER_LAST_KNOWN_WARNING_MS = 12 * 60 * 60 * 1000;
const DASHBOARD_WEATHER_REQUEST_TIMEOUT_MS = 15 * 1000;
const toFiniteDashboardWeatherNumber = value => {
if (value === null || value === undefined) return null;
if (typeof value === 'string' && value.trim() === '') return null;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
};
const normalizeWeatherCoordinateForCache = (value) => {
const parsed = toFiniteDashboardWeatherNumber(value);
return parsed === null ? null : Number(parsed.toFixed(4));
};
const getWeatherLocationKey = (weather = {}) => {
const lat = normalizeWeatherCoordinateForCache(weather.lat);
const lon = normalizeWeatherCoordinateForCache(weather.lon);
return `${lat},${lon}`;
};
const isSameWeatherLocation = (a = {}, b = {}) => {
const coordinates = [a.lat, a.lon, b.lat, b.lon].map(toFiniteDashboardWeatherNumber);
return coordinates.every(value => value !== null)
&& getWeatherLocationKey(a) === getWeatherLocationKey(b);
};
const readDashboardWeatherCache = (cacheKey, weatherSettings) => {
const rawCache = localStorage.getItem(cacheKey);
if (!rawCache) return null;
let cachedData;
try {
cachedData = JSON.parse(rawCache);
} catch (error) {
console.warn('Invalid dashboard weather cache was removed.', error);
try {
localStorage.removeItem(cacheKey);
} catch (removeError) {
console.warn('Weather cache removal failed:', removeError);
}
return null;
}
const timestamp = toFiniteDashboardWeatherNumber(cachedData?.timestamp);
const temp = toFiniteDashboardWeatherNumber(cachedData?.data?.temp);
const cachedLat = toFiniteDashboardWeatherNumber(cachedData?.lat);
const cachedLon = toFiniteDashboardWeatherNumber(cachedData?.lon);
const weather = cachedData?.data?.weather;
if (timestamp === null
|| temp === null
|| cachedLat === null
|| cachedLon === null
|| !weather
|| typeof weather !== 'object'
|| typeof weather.text !== 'string'
|| weather.text.trim() === ''
|| weather.icon === undefined
|| weather.icon === null
|| String(weather.icon).trim() === ''
|| !isSameWeatherLocation(cachedData, weatherSettings)) {
return null;
}
return {
timestamp,
lat: cachedLat,
lon: cachedLon,
data: {
weather: { icon: String(weather.icon), text: weather.text },
temp: Math.round(temp)
}
};
};
const formatWeatherCacheAge = (ageMs) => {
const minutes = Math.max(1, Math.round(ageMs / (60 * 1000)));
if (minutes < 60) return `${minutes}분 전`;
const hours = Math.max(1, Math.round(minutes / 60));
if (hours < 24) return `${hours}시간 전`;
const days = Math.max(1, Math.round(hours / 24));
if (days < 30) return `${days}일 전`;
const months = Math.max(1, Math.round(days / 30));
return `${months}개월 전`;
};
const getDashboardWeatherRefreshStatus = (cacheAge) => {
const ageText = formatWeatherCacheAge(cacheAge);
if (cacheAge >= DASHBOARD_WEATHER_LAST_KNOWN_WARNING_MS) {
return `오래된 날씨(${ageText}) · 백그라운드에서 갱신 중`;
}
return `마지막 업데이트: ${ageText} · 백그라운드에서 갱신 중`;
};
const getDashboardWeatherRefreshFailureStatus = (cacheAge) => {
const ageText = formatWeatherCacheAge(cacheAge);
if (cacheAge >= DASHBOARD_WEATHER_LAST_KNOWN_WARNING_MS) {
return `최신 갱신 실패 · 오래된 날씨 표시 중 (${ageText})`;
}
return `최신 갱신 실패 · 이전 날씨 표시 중 (${ageText})`;
};
const buildDashboardWeatherTitle = (weather, temp, statusLine = '') => {
const status = statusLine ? `\n${statusLine}` : '';
return `${weather.text}, ${temp}°C${status}\n\n(클릭해서 상세 날씨 보기)`;
};
const parseStrictNumberInput = (value) => {
const rawValue = String(value ?? '').trim();
if (!/^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(rawValue)) return null;
const numberValue = Number(rawValue);
return Number.isFinite(numberValue) ? numberValue : null;
};
const isSupportedFontFamily = (fontFamily) => {
if (!fontFamily) return false;
if (typeof CSS === 'undefined' || typeof CSS.supports !== 'function') {
return true;
}
return CSS.supports('font-family', fontFamily);
};
// CSS.escape가 없는 환경에서도 data-id 기반 선택자가 깨지지 않도록 안전한 폴백을 제공합니다.
// MothNote는 ID를 내부에서 생성하지만, 백업 가져오기/복구 경로에서는 예외적인 값이 유입될 수 있습니다.
const escapeCssAttributeValue = (value) => {
const stringValue = String(value ?? '');
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
return CSS.escape(stringValue);
}
return stringValue
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/[\n\r\f]/g, ' ');
};
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 isEditableElement = (element) => {
const tagName = String(element?.tagName || '').toUpperCase();
return ['INPUT', 'SELECT', 'TEXTAREA'].includes(tagName) || Boolean(element?.isContentEditable);
};
const ensureThemeApplied = () => {
document.body?.classList.add('theme-applied');
};
const applyStoredTheme = (themeToggleBtn = null, { reveal = true } = {}) => {
try {
const currentTheme = localStorage.getItem('theme');
const isDarkMode = currentTheme === 'dark';
document.body?.classList.toggle('dark-mode', isDarkMode);
if (themeToggleBtn) {
themeToggleBtn.textContent = isDarkMode ? '☀️' : '🌙';
}
} catch (error) {
console.warn('Saved theme could not be applied. Continuing with the default theme.', error);
} finally {
// style.css는 body.theme-applied 전까지 화면을 숨깁니다.
// 테마 버튼이 없거나 초기화 중 예외가 나도 앱/오류 메시지가 보이도록 호출부에서 반드시 해제합니다.
if (reveal) ensureThemeApplied();
}
};
const settingsCol1Input = document.getElementById('settings-col1-input');
const settingsCol2Input = document.getElementById('settings-col2-input');
const settingsZenMaxWidth = document.getElementById('settings-zen-max-width');
const settingsZenMaxInput = document.getElementById('settings-zen-max-input');
const applySettings = (settings, { refreshWeather = false, forceWeatherRefresh = false } = {}) => {
const root = document.documentElement;
if (!settings) return;
root.style.setProperty('--column-folders-width', `${settings.layout.col1}%`);
root.style.setProperty('--column-notes-width', `${settings.layout.col2}%`);
root.style.setProperty('--zen-max-width', `${settings.zenMode.maxWidth}px`);
root.style.setProperty('--editor-font-family', settings.editor.fontFamily);
root.style.setProperty('--editor-font-size', `${settings.editor.fontSize}px`);
// 레이아웃/글꼴 적용과 날씨 새로고침을 분리합니다.
// 기존처럼 설정 적용마다 fetchWeather()를 호출하면 저장/초기화 흐름에서 불필요한 로딩 표시가 반복될 수 있습니다.
if (dashboard && refreshWeather) {
dashboard.fetchWeather({ forceRefresh: forceWeatherRefresh });
}
};
const loadAndApplySettings = () => {
try {
const storedSettings = localStorage.getItem(CONSTANTS.LS_KEY_SETTINGS);
const parsedSettings = storedSettings ? JSON.parse(storedSettings) : {};
appSettings = sanitizeSettings(parsedSettings);
} catch (e) {
// JSON 손상이나 일시적인 localStorage 접근 오류가 발생해도 유일한 설정 원문을
// 삭제하지 않습니다. 현재 세션에만 안전한 기본값을 적용하면 사용자가 진단하거나
// 저장소 문제가 해소된 뒤 원본을 다시 확인할 수 있습니다.
console.warn("Could not load settings; the stored value was preserved and defaults are used for this session.", e);
appSettings = JSON.parse(JSON.stringify(CONSTANTS.DEFAULT_SETTINGS));
}
applySettings(appSettings);
};
// [기능 추가] 저장소 사용량을 계산하고 표시하는 함수
const updateStorageUsageDisplay = async () => {
// settingsStorageUsage 요소가 없으면 함수를 종료합니다.
if (!settingsStorageUsage) return;
settingsStorageUsage.textContent = '계산 중...';
try {
// chrome.storage.local API가 사용 가능한지 확인합니다.
if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
// 현재 사용량을 비동기적으로 가져옵니다.
const usedBytes = await new Promise((resolve, reject) => {
// null을 전달하여 전체 사용량을 가져옵니다.
chrome.storage.local.getBytesInUse(null, (bytes) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve(bytes);
});
});
// 숫자를 쉼표가 있는 문자열로 변환합니다.
const usedFormatted = usedBytes.toLocaleString('ko-KR');
// 최종 문자열을 생성하여 UI에 업데이트합니다.
settingsStorageUsage.textContent = `${usedFormatted} bytes`;
} else {
// API를 사용할 수 없는 경우
settingsStorageUsage.textContent = '사용량 확인 불가';
}
} catch (error) {
console.error("저장소 사용량 확인 실패:", error);
settingsStorageUsage.textContent = '사용량 확인 실패';
}
};
const openSettingsModal = async () => {
if (!(await finishPendingRename())) {
showToast('이름 변경 저장에 실패하여 설정을 열지 않았습니다.', CONSTANTS.TOAST_TYPE.ERROR);
return;
}
if (!(await saveCurrentNoteIfChanged())) {
showToast('노트 저장에 실패하여 설정을 열지 않았습니다.', CONSTANTS.TOAST_TYPE.ERROR);
return;
}
// [기능 추가] 모달이 열릴 때마다 저장소 사용량을 업데이트합니다.
updateStorageUsageDisplay();
settingsCol1Width.value = appSettings.layout.col1;
settingsCol1Input.value = appSettings.layout.col1;
settingsCol2Width.value = appSettings.layout.col2;
settingsCol2Input.value = appSettings.layout.col2;
settingsZenMaxWidth.value = appSettings.zenMode.maxWidth;
settingsZenMaxInput.value = appSettings.zenMode.maxWidth;
settingsEditorFontFamily.value = appSettings.editor.fontFamily;
settingsEditorFontSize.value = appSettings.editor.fontSize;
settingsWeatherLat.value = appSettings.weather.lat;
settingsWeatherLon.value = appSettings.weather.lon;
settingsWeatherCitySearch.value = '';
settingsWeatherCityResults.innerHTML = '';
settingsWeatherCityResults.style.display = 'none';
settingsModal.showModal();
};
const handleSettingsSave = () => {
isSavingSettings = true;
const newFontFamily = settingsEditorFontFamily.value.trim();
let finalFontFamily = appSettings.editor.fontFamily;
if (newFontFamily && isSupportedFontFamily(newFontFamily)) {
finalFontFamily = newFontFamily;
} else if (newFontFamily) {
showToast(CONSTANTS.MESSAGES.ERROR.INVALID_FONT_NAME, CONSTANTS.TOAST_TYPE.ERROR);
settingsEditorFontFamily.value = finalFontFamily;
isSavingSettings = false;
return;
} else {
finalFontFamily = CONSTANTS.DEFAULT_SETTINGS.editor.fontFamily;
settingsEditorFontFamily.value = finalFontFamily;
}
let lat = parseStrictNumberInput(settingsWeatherLat.value);
let lon = parseStrictNumberInput(settingsWeatherLon.value);
if (lat === null || lat < -90 || lat > 90) {
showToast(CONSTANTS.MESSAGES.ERROR.INVALID_LATITUDE, CONSTANTS.TOAST_TYPE.ERROR); isSavingSettings = false; return;
}
if (lon === null || lon < -180 || lon > 180) {
showToast(CONSTANTS.MESSAGES.ERROR.INVALID_LONGITUDE, CONSTANTS.TOAST_TYPE.ERROR); isSavingSettings = false; return;
}
const previousWeather = appSettings.weather;
// HTML의 min/max는 직접 입력·가져오기·스크립트 변경을 완전히 막지 못하므로
// 저장 직전에도 중앙 정제 함수를 거쳐 안전한 범위만 영구 저장합니다.
const persistedSettings = persistAppSettings({
layout: {
col1: settingsCol1Input.value,
col2: settingsCol2Input.value
},
zenMode: {
maxWidth: settingsZenMaxInput.value
},
editor: {
fontFamily: finalFontFamily,
fontSize: settingsEditorFontSize.value
},
weather: { lat, lon }
});
if (!persistedSettings) {
isSavingSettings = false;
return;
}
appSettings = persistedSettings;
settingsCol1Width.value = appSettings.layout.col1;
settingsCol1Input.value = appSettings.layout.col1;
settingsCol2Width.value = appSettings.layout.col2;
settingsCol2Input.value = appSettings.layout.col2;
settingsZenMaxWidth.value = appSettings.zenMode.maxWidth;
settingsZenMaxInput.value = appSettings.zenMode.maxWidth;
settingsEditorFontSize.value = appSettings.editor.fontSize;
const weatherLocationChanged = !isSameWeatherLocation(previousWeather, appSettings.weather);
if (weatherLocationChanged) {
clearDashboardWeatherCache();
}
applySettings(appSettings);
showToast(CONSTANTS.MESSAGES.SUCCESS.SETTINGS_SAVED);
settingsModal.close();
isSavingSettings = false;
if (weatherLocationChanged && dashboard) {
dashboard._refreshWeatherLocationViews();
}
};
const handleSettingsReset = async () => {
const ok = await showConfirmModal({
title: '⚙️ 설정 초기화', message: '모든 설정을 기본값으로 되돌리시겠습니까? 이 작업은 즉시 저장됩니다.',
confirmText: '🔄 초기화 및 저장', confirmButtonType: 'danger'
});
if (ok) {
const previousWeather = appSettings.weather;
const persistedSettings = persistAppSettings(CONSTANTS.DEFAULT_SETTINGS);
if (!persistedSettings) return;
appSettings = persistedSettings;
const weatherLocationChanged = !isSameWeatherLocation(previousWeather, appSettings.weather);
if (weatherLocationChanged) {
clearDashboardWeatherCache();
}
settingsCol1Width.value = appSettings.layout.col1; settingsCol1Input.value = appSettings.layout.col1;
settingsCol2Width.value = appSettings.layout.col2; settingsCol2Input.value = appSettings.layout.col2;
settingsZenMaxWidth.value = appSettings.zenMode.maxWidth; settingsZenMaxInput.value = appSettings.zenMode.maxWidth;
settingsEditorFontFamily.value = appSettings.editor.fontFamily;
settingsEditorFontSize.value = appSettings.editor.fontSize;
settingsWeatherLat.value = appSettings.weather.lat;
settingsWeatherLon.value = appSettings.weather.lon;
applySettings(appSettings);
if (weatherLocationChanged && dashboard) {
dashboard._refreshWeatherLocationViews();
}
showToast(CONSTANTS.MESSAGES.SUCCESS.SETTINGS_RESET);
// [BUG FIX] 브라우저가 CSS 변수 변경을 렌더링할 수 있도록 짧은 지연을 줍니다.
// 50ms는 사용자가 인지하기 어려운 시간이지만 렌더링에는 충분합니다.
await new Promise(resolve => setTimeout(resolve, 50));
settingsModal.close();
}
};
const handleWeatherCitySearch = async () => {
if (!settingsWeatherCitySearch || !settingsWeatherCityResults) return;
const query = settingsWeatherCitySearch.value.trim();
const requestId = ++weatherCitySearchRequestId;
if (weatherCitySearchAbortController) {
weatherCitySearchAbortController.abort();
weatherCitySearchAbortController = null;
}
if (query.length < 2) {
settingsWeatherCityResults.innerHTML = '';
settingsWeatherCityResults.style.display = 'none';
return;
}
// 요청 전에 이전 결과를 즉시 초기화하여 사용자 혼란을 방지합니다.
settingsWeatherCityResults.innerHTML = '';
settingsWeatherCityResults.style.display = 'none';
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
weatherCitySearchAbortController = controller;
try {
const response = await fetch(
`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=5&language=en&format=json`,
controller ? { signal: controller.signal } : undefined
);
if (!response.ok) throw new Error('Network response was not ok.');
const data = await response.json();
// 느린 이전 요청이 늦게 도착해 최신 검색어 결과를 덮어쓰는 경합을 차단합니다.
if (requestId !== weatherCitySearchRequestId || settingsWeatherCitySearch.value.trim() !== query) {
return;
}
if (data.results && data.results.length > 0) {
data.results.forEach(city => {
const li = document.createElement('li');
let displayName = city.name;
if (city.admin1) displayName += `, ${city.admin1}`;
if (city.country) displayName += `, ${city.country}`;
li.textContent = displayName;
li.dataset.lat = city.latitude; li.dataset.lon = city.longitude;
li.addEventListener('click', () => {
settingsWeatherLat.value = parseFloat(city.latitude).toFixed(4);
settingsWeatherLon.value = parseFloat(city.longitude).toFixed(4);
settingsWeatherCitySearch.value = displayName;
settingsWeatherCityResults.style.display = 'none';
showToast(CONSTANTS.MESSAGES.SUCCESS.WEATHER_LOCATION_UPDATED);
});
settingsWeatherCityResults.appendChild(li);
});
settingsWeatherCityResults.style.display = 'block';
} else {
showToast(CONSTANTS.MESSAGES.ERROR.WEATHER_CITY_NOT_FOUND, CONSTANTS.TOAST_TYPE.ERROR);
}
} catch (error) {
if (error?.name === 'AbortError') return;
console.error('Error fetching city data:', error);
// 목록은 이미 함수 시작 시 초기화되었으므로 추가 작업이 필요 없습니다.
} finally {
if (requestId === weatherCitySearchRequestId) {
weatherCitySearchAbortController = null;
}
}
};
const setupSettingsModal = () => {
// [BUG FIX] DOM 요소가 null일 경우를 대비하여 방어 코드를 추가합니다.
if (settingsBtn) settingsBtn.addEventListener('click', openSettingsModal);
if (settingsModalCloseBtn) settingsModalCloseBtn.addEventListener('click', () => settingsModal.close());
if (settingsSaveBtn) settingsSaveBtn.addEventListener('click', handleSettingsSave);
if (settingsResetBtn) settingsResetBtn.addEventListener('click', handleSettingsReset);
if (settingsExportBtn) settingsExportBtn.addEventListener('click', () => handleExport(appSettings));
if (settingsImportBtn) settingsImportBtn.addEventListener('click', () => handleImport());
if (settingsModal) {
settingsModal.addEventListener('close', () => {
if (!isSavingSettings) { applySettings(appSettings); }
isSavingSettings = false;
});
}
if (settingsTabs) {
settingsTabs.addEventListener('click', (e) => {
const target = getClosestElement(e.target, '.settings-tab-btn'); if (!target) return;
const activeTabBtn = document.querySelector('.settings-tab-btn.active');
if (activeTabBtn) activeTabBtn.classList.remove('active');
target.classList.add('active');
const activeTabPanel = document.querySelector('.settings-tab-panel.active');
if (activeTabPanel) activeTabPanel.classList.remove('active');
const tabPanel = document.getElementById(`settings-tab-${target.dataset.tab}`);
if (tabPanel) tabPanel.classList.add('active');
});
}
const bindSliderAndInput = (slider, input, cssVarName, unit) => {
// [BUG FIX] slider 또는 input이 null일 경우 함수를 즉시 종료합니다.
if (!slider || !input) return;
const updateStyle = (value) => { document.documentElement.style.setProperty(cssVarName, `${value}${unit}`); };
slider.addEventListener('input', () => { const value = slider.value; input.value = value; updateStyle(value); });
input.addEventListener('input', () => { const value = parseInt(input.value, 10); const min = parseInt(input.min, 10); const max = parseInt(input.max, 10); if (isNaN(value)) return; const clampedValue = Math.max(min, Math.min(value, max)); slider.value = clampedValue; updateStyle(clampedValue); });
input.addEventListener('blur', () => { let value = parseInt(input.value, 10); const min = parseInt(input.min, 10); const max = parseInt(input.max, 10); if (isNaN(value) || value < min) value = min; else if (value > max) value = max; input.value = value; slider.value = value; updateStyle(value); });
};
bindSliderAndInput(settingsCol1Width, settingsCol1Input, '--column-folders-width', '%');
bindSliderAndInput(settingsCol2Width, settingsCol2Input, '--column-notes-width', '%');
bindSliderAndInput(settingsZenMaxWidth, settingsZenMaxInput, '--zen-max-width', 'px');
if (settingsEditorFontFamily) {
settingsEditorFontFamily.addEventListener('input', (e) => { document.documentElement.style.setProperty('--editor-font-family', e.target.value); });
}
if (settingsEditorFontSize) {
settingsEditorFontSize.addEventListener('input', (e) => {
const rawValue = Number.parseInt(e.target.value, 10);
if (!Number.isFinite(rawValue)) return;
const min = Number.parseInt(e.target.min, 10) || 10;
const max = Number.parseInt(e.target.max, 10) || 30;
const clampedValue = Math.max(min, Math.min(rawValue, max));
document.documentElement.style.setProperty('--editor-font-size', `${clampedValue}px`);
});
}
if (settingsWeatherCitySearchBtn) settingsWeatherCitySearchBtn.addEventListener('click', handleWeatherCitySearch);
if (settingsWeatherCitySearch) {
settingsWeatherCitySearch.addEventListener('keydown', (e) => {
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter') { e.preventDefault(); handleWeatherCitySearch(); }
});
}
// settingsWeatherCityResults는 동적으로 내용이 채워지므로, 전역 클릭 이벤트는 null 체크 없이 유지합니다.
document.addEventListener('click', (e) => { if (settingsWeatherCityResults && settingsWeatherCitySearch && !settingsWeatherCitySearch.contains(e.target) && !settingsWeatherCityResults.contains(e.target)) { settingsWeatherCityResults.style.display = 'none'; } });
};
// [기능 추가] 모든 iframe 뷰를 닫는 헬퍼 함수
const _closeAllIFrames = () => {
if (!dashboard) return;
dashboard._closeWeatherView({ restorePanels: false });
dashboard._closeHabitTracker({ restorePanels: false });
dashboard._closeDietChallenge({ restorePanels: false });
dashboard._restoreMainPanels();
};
const prepareForDashboardNavigation = async (actionName = '화면 전환') => {
cancelPendingSearchRequest();
if (!(await finishPendingRename())) {
showToast(`이름 변경 저장에 실패하여 ${actionName}을 취소했습니다.`, CONSTANTS.TOAST_TYPE.ERROR);
return false;
}
if (!(await confirmNavigation())) {
showToast(`변경사항 저장에 실패하여 ${actionName}을 취소했습니다.`, CONSTANTS.TOAST_TYPE.ERROR);
return false;
}
return true;
};
class Dashboard {
constructor() {
this.dom = {
panel: document.getElementById('folders-panel'),
digitalClock: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.digitalClock),
analogClockCanvas: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.analogClockCanvas),
weatherContainer: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.weatherContainer),
calendarGrid: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.calendarGrid),
calendarMonthYear: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.calendarMonthYear),
prevMonthBtn: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.prevMonthBtn),
nextMonthBtn: document.getElementById(CONSTANTS.DASHBOARD.DOM_IDS.nextMonthBtn),
// 날씨 뷰 관련 DOM 요소 참조 정리
notesPanel: document.getElementById('notes-panel'),
splitter2: document.getElementById('splitter-2'),
mainContent: document.querySelector('.main-content'),
weatherViewContainer: document.getElementById('weather-view-container'),
weatherIframe: document.getElementById('weather-iframe'),
closeWeatherViewBtn: document.getElementById('close-weather-view-btn'),
// [기능 추가] 습관 트래커 관련 DOM 요소 참조
habitTrackerBtn: document.getElementById('habit-tracker-btn'),
habitTrackerContainer: document.getElementById('habit-tracker-container'),
habitTrackerIframe: document.getElementById('habit-tracker-iframe'),
closeHabitTrackerBtn: document.getElementById('close-habit-tracker-btn'),
// [기능 추가] 다이어트 챌린지 관련 DOM 요소 참조
dietChallengeBtn: document.getElementById('diet-challenge-btn'),
dietChallengeContainer: document.getElementById('diet-challenge-container'),
dietChallengeIframe: document.getElementById('diet-challenge-iframe'),
closeDietChallengeBtn: document.getElementById('close-diet-challenge-btn'),
};
this.internalState = { currentDate: state.dateFilter ? new Date(state.dateFilter) : new Date(), analogClockTimerId: null, digitalClockIntervalId: null, clockPanelVisible: true, weatherFetchController: null, weatherFetchPromise: null, weatherFetchKey: null, displayedMonth: null, clockFaceCache: null, };
this.observer = null;
}
init() {
this._setupVisibilityObserver(); this._initAnalogClock();
if (document.body) {
new MutationObserver(() => {
// [BUG FIX] 테마 변경 후 스타일이 완전히 적용된 다음 프레임에 시계를 다시 그리도록 수정합니다.
// 이렇게 하면 getComputedStyle이 정확한 테마의 색상 값을 가져오는 것을 보장하여 레이스 컨디션을 해결합니다.
requestAnimationFrame(() => this._initAnalogClock(true));
}).observe(document.body, { attributes: true, attributeFilter: ['class'] });
}
this._setupWeatherViewEvents();
this.fetchWeather(); this.renderCalendar(); this._setupCalendarEvents();
// [기능 추가] 습관 트래커 이벤트 설정
this._setupHabitTrackerEvents();
// [기능 추가] 다이어트 챌린지 이벤트 설정
this._setupDietChallengeEvents();
window.addEventListener('unload', () => { if (this.internalState.weatherFetchController) this.internalState.weatherFetchController.abort(); this._stopClocks(); });
}
// [기능 추가] 모든 패널을 숨기는 공통 헬퍼 함수
_hideMainPanels() {
if (this.dom.notesPanel) this.dom.notesPanel.style.display = 'none';
if (this.dom.splitter2) this.dom.splitter2.style.display = 'none';
if (this.dom.mainContent) this.dom.mainContent.style.display = 'none';
// 관련 없는 플로팅 액션 버튼 숨기기
const markdownToggleBtn = document.getElementById('markdown-toggle-btn');
const zenModeBtn = document.getElementById('zen-mode-toggle-btn');
if (markdownToggleBtn) markdownToggleBtn.style.display = 'none';
if (zenModeBtn) zenModeBtn.style.display = 'none';
}
// [기능 추가] 모든 패널을 복원하는 공통 헬퍼 함수
_restoreMainPanels() {
if (this.dom.notesPanel) this.dom.notesPanel.style.removeProperty('display');
if (this.dom.splitter2) this.dom.splitter2.style.removeProperty('display');
if (this.dom.mainContent) this.dom.mainContent.style.removeProperty('display');
// 숨겼던 플로팅 액션 버튼 복원
const markdownToggleBtn = document.getElementById('markdown-toggle-btn');
const zenModeBtn = document.getElementById('zen-mode-toggle-btn');
if (markdownToggleBtn) markdownToggleBtn.style.removeProperty('display');
if (zenModeBtn) zenModeBtn.style.removeProperty('display');
}
async _openWeatherView() {
if (!(await prepareForDashboardNavigation('날씨 화면 열기'))) return;
const { lat, lon } = appSettings.weather;
console.log("Opening weather view with settings:", appSettings.weather);
if (typeof lat !== 'number' || typeof lon !== 'number' || isNaN(lat) || isNaN(lon)) {
console.error("Invalid lat/lon values:", lat, lon);
showToast("날씨 위치 정보가 올바르지 않습니다. 설정에서 위치를 확인해주세요.", CONSTANTS.TOAST_TYPE.ERROR);
return;
}
// 다른 iframe 뷰가 열려있으면 닫습니다.
this._closeHabitTracker({ restorePanels: false });
this._closeDietChallenge({ restorePanels: false });
if (!this.dom.weatherIframe || !this.dom.weatherViewContainer) return;
this.dom.weatherIframe.src = this._getWeatherViewUrl();
this._hideMainPanels();
this.dom.weatherViewContainer.style.display = 'grid';
}
_getWeatherViewUrl() {
const { lat, lon } = appSettings.weather;
const theme = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
return `weather.html?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}&theme=${theme}`;
}
_refreshWeatherLocationViews() {
void this.fetchWeather({ forceRefresh: true });
if (this.dom.weatherViewContainer?.style.display === 'grid' && this.dom.weatherIframe) {
this.dom.weatherIframe.src = this._getWeatherViewUrl();
}
}
_closeWeatherView({ restorePanels = true } = {}) {
if (this.dom.weatherViewContainer) this.dom.weatherViewContainer.style.display = 'none';
if (this.dom.weatherIframe) this.dom.weatherIframe.src = 'about:blank';
if (restorePanels) this._restoreMainPanels();
}
// [기능 추가] 습관 트래커 열기 함수
async _openHabitTracker() {
if (!(await prepareForDashboardNavigation('습관 트래커 열기'))) return;
const theme = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
// 다른 iframe 뷰가 열려있으면 닫습니다.
this._closeWeatherView({ restorePanels: false });
this._closeDietChallenge({ restorePanels: false });
if (!this.dom.habitTrackerIframe || !this.dom.habitTrackerContainer) return;
this.dom.habitTrackerIframe.src = `habitTracker.html?theme=${theme}`;
this._hideMainPanels();
this.dom.habitTrackerContainer.style.display = 'grid';
}
// [기능 추가] 습관 트래커 닫기 함수
_closeHabitTracker({ restorePanels = true } = {}) {
if (this.dom.habitTrackerContainer) this.dom.habitTrackerContainer.style.display = 'none';
if (this.dom.habitTrackerIframe) this.dom.habitTrackerIframe.src = 'about:blank';
if (restorePanels) this._restoreMainPanels();
}
// [기능 추가] 다이어트 챌린지 열기 함수
async _openDietChallenge() {
if (!(await prepareForDashboardNavigation('다이어트 챌린지 열기'))) return;
const theme = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
// 다른 iframe 뷰가 열려있으면 닫습니다.
this._closeWeatherView({ restorePanels: false });
this._closeHabitTracker({ restorePanels: false });
if (!this.dom.dietChallengeIframe || !this.dom.dietChallengeContainer) return;
this.dom.dietChallengeIframe.src = `dietChallenge.html?theme=${theme}`;
this._hideMainPanels();
this.dom.dietChallengeContainer.style.display = 'grid';
}
// [기능 추가] 다이어트 챌린지 닫기 함수
_closeDietChallenge({ restorePanels = true } = {}) {
if (this.dom.dietChallengeContainer) this.dom.dietChallengeContainer.style.display = 'none';
if (this.dom.dietChallengeIframe) this.dom.dietChallengeIframe.src = 'about:blank';
if (restorePanels) this._restoreMainPanels();
}
// [버그 수정] 날씨 위젯의 title 속성을 동적으로 업데이트하도록 수정
_setupWeatherViewEvents() {
if (this.dom.weatherContainer) {
this.dom.weatherContainer.style.cursor = 'pointer';
if (!this.dom.weatherContainer.title) {
this.dom.weatherContainer.title = '날씨 정보 불러오는 중...';
}
this.dom.weatherContainer.addEventListener('click', () => { void this._openWeatherView(); });
}
if (this.dom.closeWeatherViewBtn) {
this.dom.closeWeatherViewBtn.addEventListener('click', () => this._closeWeatherView());
}
}
// [기능 추가] 습관 트래커 이벤트 리스너 설정
_setupHabitTrackerEvents() {
if (this.dom.habitTrackerBtn) {
this.dom.habitTrackerBtn.addEventListener('click', () => { void this._openHabitTracker(); });
}
if (this.dom.closeHabitTrackerBtn) {
this.dom.closeHabitTrackerBtn.addEventListener('click', () => this._closeHabitTracker());
}
}
// [기능 추가] 다이어트 챌린지 이벤트 리스너 설정
_setupDietChallengeEvents() {
if (this.dom.dietChallengeBtn) {
this.dom.dietChallengeBtn.addEventListener('click', () => { void this._openDietChallenge(); });
}
if (this.dom.closeDietChallengeBtn) {
this.dom.closeDietChallengeBtn.addEventListener('click', () => this._closeDietChallenge());
}
}
_setupVisibilityObserver() {
if (!this.dom.panel) return;
this.observer = new IntersectionObserver((entries) => { entries.forEach(entry => { this.internalState.clockPanelVisible = entry.isIntersecting; if (entry.isIntersecting) this._startClocks(); else this._stopClocks(); }); });
this.observer.observe(this.dom.panel);
}
_startClocks() { if (!this.internalState.digitalClockIntervalId) { this._updateDigitalClock(); this.internalState.digitalClockIntervalId = setInterval(this._updateDigitalClock.bind(this), 1000); } if (!this.internalState.analogClockTimerId) this._scheduleAnalogClockUpdates(); }
_stopClocks() { if (this.internalState.digitalClockIntervalId) { clearInterval(this.internalState.digitalClockIntervalId); this.internalState.digitalClockIntervalId = null; } if (this.internalState.analogClockTimerId) { clearTimeout(this.internalState.analogClockTimerId); this.internalState.analogClockTimerId = null; } }
_getWeatherInfo(wmoCode, isDay = true) {
let weather = CONSTANTS.DASHBOARD.WMO_MAP[wmoCode] ?? { icon: "❓", text: "알 수 없음" };
if (!isDay) {
if (wmoCode === 0) { // 맑음
weather = { icon: "🌙", text: "맑음 (밤)" };
} else if (wmoCode === 1) { // 대체로 맑음
weather = { icon: "☁️🌙", text: "대체로 맑음 (밤)" };
}
}
return weather;
}
_updateDigitalClock() { if (!this.dom.digitalClock) return; this.dom.digitalClock.textContent = new Date().toLocaleTimeString('ko-KR', { hour: 'numeric', minute: 'numeric', hour12: true }); }
_initAnalogClock(forceRedraw = false) { if (!this.dom.analogClockCanvas) return; if (this.internalState.analogClockTimerId) { clearTimeout(this.internalState.analogClockTimerId); this.internalState.analogClockTimerId = null; } if (forceRedraw || !this.internalState.clockFaceCache) this._drawStaticClockFace(); const ctx = this.dom.analogClockCanvas.getContext('2d'); const radius = this.dom.analogClockCanvas.height / 2; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.translate(radius, radius); this._drawHandsOnTop(); if (this.internalState.clockPanelVisible) this._scheduleAnalogClockUpdates({ drawImmediately: false }); }
// [개선] 시계 디자인을 더 미려하게 수정합니다. (시계판, 눈금, 숫자)
_drawStaticClockFace() {
if (!this.dom.analogClockCanvas) return;
const cacheCanvas = document.createElement('canvas');
cacheCanvas.width = this.dom.analogClockCanvas.width;
cacheCanvas.height = this.dom.analogClockCanvas.height;
const ctx = cacheCanvas.getContext('2d');
const radius = cacheCanvas.height / 2;
ctx.translate(radius, radius);
const style = getComputedStyle(document.documentElement);
// [BUG FIX] Canvas로 배경을 그리는 로직을 제거합니다. 이제 CSS가 배경을 담당합니다.
// 시계 테두리
ctx.beginPath();
ctx.arc(0, 0, radius * 0.98, 0, 2 * Math.PI);
ctx.strokeStyle = style.getPropertyValue('--divider-color').trim();
ctx.lineWidth = radius * 0.04;
ctx.stroke();
// 시/분 눈금
ctx.strokeStyle = style.getPropertyValue('--font-color-dim').trim();
for(let i = 0; i < 60; i++){
const angle = (i / 60) * 2 * Math.PI;
ctx.rotate(angle);
ctx.beginPath();
if (i % 5 === 0) { // 시 눈금
ctx.lineWidth = radius * 0.03;
ctx.moveTo(radius * 0.85, 0);
} else { // 분 눈금
ctx.lineWidth = radius * 0.02;
ctx.moveTo(radius * 0.9, 0);
}
ctx.lineTo(radius * 0.95, 0);
ctx.stroke();
ctx.rotate(-angle);
}
// 숫자
ctx.font = `bold ${radius * 0.18}px sans-serif`;
// [BUG FIX] 다크 모드일 때 숫자 색상을 명시적으로 지정하여 가독성 확보
const isDarkMode = document.body.classList.contains('dark-mode');
ctx.fillStyle = isDarkMode ? '#EEE8D5' : style.getPropertyValue('--font-color').trim();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let num = 1; num <= 12; num++) {
const angle = num * Math.PI / 6;
ctx.fillText(num.toString(), radius * 0.72 * Math.sin(angle), -radius * 0.72 * Math.cos(angle));
}
this.internalState.clockFaceCache = cacheCanvas;
}
// [개선] 시침/분침 디자인을 개선하고 그림자를 추가합니다. 초침은 제거합니다.
_drawHandsOnTop() {
if (!this.dom.analogClockCanvas) return;
const ctx = this.dom.analogClockCanvas.getContext('2d');
const radius = this.dom.analogClockCanvas.height / 2;
ctx.clearRect(-radius, -radius, this.dom.analogClockCanvas.width, this.dom.analogClockCanvas.height);
if (this.internalState.clockFaceCache) {
ctx.drawImage(this.internalState.clockFaceCache, -radius, -radius);
}
const style = getComputedStyle(document.documentElement);
const accentColor = style.getPropertyValue('--accent-color').trim();
// [BUG FIX] 다크 모드일 때 시침/분침 색상을 명시적으로 지정하여 가독성 확보
const isDarkMode = document.body.classList.contains('dark-mode');
const fontColor = isDarkMode ? '#EEE8D5' : style.getPropertyValue('--font-color').trim();
const shadowColor = 'rgba(0,0,0,0.2)';
const now = new Date();
const h = now.getHours();
const m = now.getMinutes();
const drawHand = (angle, length, width, color) => {
ctx.save();
ctx.beginPath();
ctx.rotate(angle);
ctx.lineWidth = width;
ctx.lineCap = 'round';
ctx.strokeStyle = color;
ctx.shadowColor = shadowColor;
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.moveTo(0, 0);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.restore();
};
// 시침 그리기
const hourAngle = (h % 12 + m / 60) * (Math.PI / 6);
drawHand(hourAngle, radius * 0.5, radius * 0.07, fontColor);
// 분침 그리기
const minuteAngle = m * (Math.PI / 30);
drawHand(minuteAngle, radius * 0.75, radius * 0.05, fontColor);
// 시계 중심축
ctx.beginPath();
ctx.arc(0, 0, radius * 0.06, 0, 2 * Math.PI);
ctx.fillStyle = accentColor;
ctx.fill();
ctx.beginPath();
ctx.arc(0, 0, radius * 0.02, 0, 2 * Math.PI);
ctx.fillStyle = style.getPropertyValue('--solar-base3').trim();
ctx.fill();
}
_scheduleAnalogClockUpdates({ drawImmediately = true } = {}) {
if (drawImmediately) this._drawHandsOnTop();
const scheduleNextMinute = () => {
// 초침이 없는 시계는 분 경계에서만 다시 그리면 됩니다. 매 프레임 RAF를
// 돌리면 새 탭이 열려 있는 내내 불필요한 CPU·배터리를 사용합니다.
const delayUntilNextMinute = 60000 - (Date.now() % 60000) + 50;
this.internalState.analogClockTimerId = setTimeout(() => {
this._drawHandsOnTop();
scheduleNextMinute();
}, delayUntilNextMinute);
};
scheduleNextMinute();
}
_setDashboardWeatherContent(icon, temp = null) {
if (!this.dom.weatherContainer) return;
this.dom.weatherContainer.replaceChildren();
const iconSpan = document.createElement('span');
iconSpan.id = 'weather-icon';
iconSpan.textContent = String(icon ?? '');
this.dom.weatherContainer.appendChild(iconSpan);
if (temp !== null && temp !== undefined) {
this.dom.weatherContainer.appendChild(document.createTextNode(' '));
const tempSpan = document.createElement('span');
tempSpan.id = 'weather-temp';
tempSpan.textContent = `${temp}°C`;
this.dom.weatherContainer.appendChild(tempSpan);
}
}