Repository navigation
Expand file tree
/
Copy pathhabitTracker.js
More file actions
2818 lines (2547 loc) · 147 KB
/
Copy pathhabitTracker.js
File metadata and controls
2818 lines (2547 loc) · 147 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
document.addEventListener('DOMContentLoaded', () => {
// --- MODIFIED: 신규 업적 대량 추가 ---
const achievementList = {
'first_habit': { title: '첫걸음', description: '첫 습관을 추가했습니다.', icon: '🌱' },
'perfect_day': { title: '완벽한 하루', description: '하루의 모든 습관을 완료했습니다.', icon: '💯' },
'7_day_streak': { title: '불타는 일주일', description: '한 습관을 7일 연속으로 달성했습니다.', icon: '🔥' },
'perfect_week': { title: '완벽한 한 주', description: '7일 연속으로 모든 습관을 완료했습니다.', icon: '📅' },
'30_day_streak': { title: '한 달의 위업', description: '한 습관을 30일 연속으로 달성했습니다.', icon: '🗓️' },
'100_completions': { title: '성실함의 증표', description: '한 습관을 100회 완료했습니다.', icon: '👑' },
'5_habits': { title: '습관 부자', description: '5개 이상의 활성 습관을 만들었습니다.', icon: '🏦' },
'10_habits': { title: '습관 콜렉터', description: '10개 이상의 활성 습관을 만들었습니다.', icon: '📚' },
'archivist': { title: '정리정돈', description: '첫 습관을 보관했습니다.', icon: '📦' },
'perfect_month': { title: '완벽한 한 달', description: '한 달 내내 모든 습관을 100% 달성했습니다.', icon: '🏅' },
'180_day_streak': { title: '반년의 끈기', description: '한 습관을 180일 연속으로 달성했습니다.', icon: '🦾' },
'365_day_streak': { title: '1년의 위업', description: '한 습관을 365일 연속으로 달성했습니다.', icon: '🎉' },
'500_completions': { title: '장인정신', description: '한 습관을 500회 완료했습니다.', icon: '💎' },
'1000_completions': { title: '습관의 대가', description: '한 습관을 1000회 완료했습니다.', icon: '🌌' },
'explorer': { title: '탐험가', description: '모든 주요 메뉴를 한 번씩 사용했습니다.', icon: '🧭' },
'data_guardian': { title: '데이터 지킴이', description: '데이터를 처음으로 백업했습니다.', icon: '🛡️' },
'comeback_king': { title: '돌아온 탕자', description: '7일 이상 쉬고 다시 습관을 시작했습니다.', icon: '💪' },
};
let draggedItem = null;
let dropPlaceholder = null;
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 getPreviousCalendarYearRangeStart = (endDate) => {
const sourceDate = endDate instanceof Date ? new Date(endDate.getTime()) : new Date(endDate);
if (Number.isNaN(sourceDate.getTime())) return null;
// 2월 29일에 setFullYear()를 직접 호출하면 3월로 넘친 뒤 일자를 한 번 더
// 더하는 과정에서 연간 통계 시작일이 최대 한 달 가까이 밀릴 수 있습니다.
const sourceMonth = sourceDate.getMonth();
const sourceDay = sourceDate.getDate();
sourceDate.setDate(1);
sourceDate.setFullYear(sourceDate.getFullYear() - 1);
sourceDate.setMonth(sourceMonth);
const lastDayOfTargetMonth = new Date(
sourceDate.getFullYear(),
sourceMonth + 1,
0
).getDate();
sourceDate.setDate(Math.min(sourceDay, lastDayOfTargetMonth));
sourceDate.setDate(sourceDate.getDate() + 1);
return sourceDate;
};
// [MAJOR BUG FIX] Number.MAX_SAFE_INTEGER는 1을 더해도 같은 값으로 반올림될 수 있습니다.
// 손상/외부 백업에 최대 안전 정수 ID가 중복되면 단순 증가 루프가 끝나지 않으므로,
// 충돌 시 안전한 대체 시작점으로 이동하고 Set 크기에 비례한 횟수 안에서만 탐색합니다.
const allocateUniqueHabitId = (preferredValue, usedIds, fallbackSeed = Date.now()) => {
const preferredId = Number(preferredValue);
if (Number.isSafeInteger(preferredId)
&& preferredId > 0
&& !usedIds.has(String(preferredId))) {
usedIds.add(String(preferredId));
return preferredId;
}
const numericFallback = Number(fallbackSeed);
let candidate = Number.isSafeInteger(numericFallback) && numericFallback > 0
? numericFallback
: Date.now();
if (!Number.isSafeInteger(candidate) || candidate <= 0) candidate = 1;
// 사용 중인 ID가 N개라면 서로 다른 N+1개 후보 중 적어도 하나는 비어 있습니다.
const maxAttempts = usedIds.size + 1;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
const key = String(candidate);
if (!usedIds.has(key)) {
usedIds.add(key);
return candidate;
}
candidate = candidate >= Number.MAX_SAFE_INTEGER ? 1 : candidate + 1;
}
throw new Error('고유한 습관 ID를 할당할 수 없습니다.');
};
const app = {
state: {
// --- MODIFIED: 데이터 버전 관리 기능 추가 ---
version: '3.6.1',
habits: [],
currentView: 'calendar',
currentDate: new Date(),
settings: {
theme: 'light',
},
achievements: {},
// --- NEW: 리뷰 기능 상태 추가 ---
reviewPeriod: 'weekly',
// --- NEW: 탐험가 업적 달성을 위한 상태 추가 ---
visitedViews: {},
filters: {
search: '',
showArchived: false,
sortBy: 'order',
},
reportPeriod: 'weekly',
chartInstances: {},
},
elements: {},
_hadDataLoadError: false,
_hasPersistedIntegratedData: false,
_activeConfirmCleanup: null,
init() {
this.cacheElements();
this.loadData();
this.state.currentView = 'calendar';
// --- MODIFIED: 사용자가 데이터를 초기화한 후 새로고침 시 기본 습관이 추가되는 것을 방지 ---
let hasBeenInitialized = false;
if (!this._hadDataLoadError) {
try {
hasBeenInitialized = localStorage.getItem('habitTrackerInitialized') === 'true';
} catch (error) {
// 초기화 플래그를 읽지 못한 상태에서 샘플 데이터를 저장하면 접근할 수 없는
// 기존 사용자 데이터를 덮어쓸 수 있으므로, 보수적으로 오류 상태로 전환합니다.
this._hadDataLoadError = true;
this._hasPersistedIntegratedData = true;
console.error('Failed to read the habit tracker initialization flag. Default data creation was blocked.', error);
}
}
// 통합 키에 정상적인 빈 상태가 있다면 '초기화하지 않음'이 아니라
// 사용자가 의도적으로 모두 지운 저장된 상태일 수 있습니다.
if (this.state.habits.length === 0
&& !hasBeenInitialized
&& !this._hasPersistedIntegratedData
&& !this._hadDataLoadError) {
if (this.setupDefaultHabits()) {
this._hasPersistedIntegratedData = true;
try {
localStorage.setItem('habitTrackerInitialized', 'true');
} catch (error) {
console.error('Failed to persist habit tracker initialization flag.', error);
}
}
}
this.applySettings();
this.addEventListeners();
this.render();
this.showRandomQuote();
if (this._hadDataLoadError) {
this.showToast('습관 데이터를 안전하게 불러오지 못했습니다. 원본 보호를 위해 자동 저장과 기본 데이터 생성을 중단했습니다.', 'error', 6000);
}
},
setupDefaultHabits(saveOptions = {}) {
const now = Date.now();
const defaultHabits = [
{ id: now + 0, name: '⚖️ 매일 아침 체중 측정', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 0, logs: {}, createdAt: now + 0 },
{ id: now + 1, name: '🥗 샐러드 먹기', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 1, logs: {}, createdAt: now + 1 },
{ id: now + 2, name: '💧 물 1리터 마시기', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 2, logs: {}, createdAt: now + 2 },
{ id: now + 3, name: '🕒 4시 이후 금식', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 3, logs: {}, createdAt: now + 3 },
{ id: now + 4, name: '💊 영양제 먹기', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 4, logs: {}, createdAt: now + 4 },
{ id: now + 5, name: '😴 7~8시간 자기', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 5, logs: {}, createdAt: now + 5 },
{ id: now + 6, name: '🚫 쌀/빵/면/과자/과당음료 먹지 않기', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 6, logs: {}, createdAt: now + 6 },
{ id: now + 7, name: '🏋️ 운동', type: 'check', goal: 1, frequency: { type: 'daily', days: [0,1,2,3,4,5,6] }, isArchived: false, order: 7, logs: {}, createdAt: now + 7 }
];
const previousHabits = this.state.habits;
this.state.habits = defaultHabits;
if (this.saveData(saveOptions)) return true;
// 저장에 실패한 샘플을 화면에 남기면 사용자는 영구 저장된 것으로 오인하고
// 기록을 시작할 수 있습니다. 재시작 시 그 기록이 사라지지 않도록 메모리도
// 저장 전 상태로 되돌립니다.
this.state.habits = previousHabits;
return false;
},
cacheElements() {
this.elements = {
appContent: document.getElementById('app-content'),
appFiltersContainer: document.getElementById('app-filters-container'),
addHabitBtn: document.getElementById('add-habit-btn'),
// settingsBtn 제거
achievementsBtn: document.getElementById('achievements-btn'),
viewButtons: document.querySelectorAll('.view-switcher button'),
habitModal: document.getElementById('habit-modal'),
// settingsModal 제거
confirmModal: document.getElementById('confirm-modal'),
achievementsModal: document.getElementById('achievements-modal'),
habitForm: document.getElementById('habit-form'),
modalTitle: document.getElementById('modal-title'),
habitIdInput: document.getElementById('habit-id'),
habitNameInput: document.getElementById('habit-name'),
habitFrequencySelect: document.getElementById('habit-frequency'),
specificDaysGroup: document.getElementById('specific-days-group'),
deleteHabitBtn: document.getElementById('delete-habit-btn'),
archiveHabitBtn: document.getElementById('archive-habit-btn'),
cancelHabitBtn: document.getElementById('cancel-habit-btn'),
// themeToggleBtn, exportDataBtn 등 제거
confirmTitle: document.getElementById('confirm-title'),
confirmMessage: document.getElementById('confirm-message'),
confirmOkBtn: document.getElementById('confirm-ok-btn'),
confirmCancelBtn: document.getElementById('confirm-cancel-btn'),
achievementsGrid: document.getElementById('achievements-grid'),
motivationalQuote: document.getElementById('motivational-quote'),
datePickerInput: document.getElementById('date-picker-input'),
toastContainer: document.getElementById('toast-container'),
};
},
addEventListeners() {
// [기능 추가] 부모 창(MothNote)로부터 테마 변경 메시지 수신
window.addEventListener('message', (event) => {
// 보안을 위해 메시지 출처 확인
if (event.origin !== window.location.origin || event.source !== window.parent) {
return;
}
if (event.data && event.data.type === 'setTheme') {
this.state.settings.theme = event.data.theme;
this.applySettings();
this.saveData();
}
});
this.elements.viewButtons.forEach(btn => {
btn.addEventListener('click', () => {
const viewName = btn.id.split('-')[1];
this.state.currentView = viewName;
// 메뉴 방문 기록은 업적이 해제되기 전에도 영구 저장해야 합니다.
// 이전에는 여섯 번째 메뉴를 같은 세션에서 누른 경우에만 저장되어,
// 중간에 새로고침하면 탐험가 진행도가 매번 사라졌습니다.
if (this.markViewVisited(viewName)) {
this.checkAchievement('explorer');
}
if (this.state.currentView === 'today') {
this.state.currentDate = new Date();
this.state.currentDate.setHours(0,0,0,0);
}
this.render();
});
});
this.elements.addHabitBtn.addEventListener('click', () => this.openHabitModal());
this.elements.achievementsBtn.addEventListener('click', () => this.openAchievementsModal());
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => {
if (e.target === modal || e.target.classList.contains('close-button') || e.target.id === 'cancel-habit-btn') {
this.closeModal(modal);
}
});
});
document.addEventListener('keydown', (e) => {
// 조합 취소 Escape가 작성 중인 습관 창 전체를 닫지 않게 합니다.
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') {
const visibleModal = document.querySelector('.modal.visible');
if (visibleModal) {
this.closeModal(visibleModal);
}
}
});
this.elements.habitForm.addEventListener('submit', (e) => this.handleHabitFormSubmit(e));
this.elements.habitFrequencySelect.addEventListener('change', (e) => {
this.elements.specificDaysGroup.style.display = e.target.value === 'specific_days' ? 'block' : 'none';
});
this.elements.deleteHabitBtn.addEventListener('click', () => this.handleDeleteHabit());
this.elements.archiveHabitBtn.addEventListener('click', () => this.handleArchiveHabit());
this.elements.datePickerInput.addEventListener('change', (e) => this.handleDateJump(e));
this.addDelegatedEventListeners();
},
// ----- DATA & STATE MANAGEMENT -----
saveData({ allowCorruptDataReplacement = false } = {}) {
// 파싱 또는 구조 검증에 실패한 통합 데이터는 사용자가 명시적으로 초기화하기 전까지 보존합니다.
// 테마 메시지나 일반 UI 작업이 빈 안전 상태를 자동 저장해 원본과 복구본을
// 덮어쓰는 일을 막습니다.
if (this._hadDataLoadError && !allowCorruptDataReplacement) {
console.warn('Habit tracker save was blocked to preserve malformed integrated data.');
if (typeof this.showToast === 'function') {
this.showToast('저장된 습관 데이터가 손상되어 원본 보호를 위해 변경사항을 저장하지 않았습니다. 초기화하거나 정상 백업을 가져와 주세요.', 'error');
}
return false;
}
// [수정] 데이터 저장 키를 MothNote와 통합될 키로 변경
try {
localStorage.setItem('habitTrackerDataV2_integrated', JSON.stringify(this.state, (key, value) => key === 'chartInstances' ? undefined : value));
if (allowCorruptDataReplacement) {
this._hadDataLoadError = false;
this._hasPersistedIntegratedData = true;
}
return true;
} catch (error) {
console.error('Habit tracker data save failed.', error);
if (typeof this.showToast === 'function') {
this.showToast('습관 트래커 데이터를 저장하지 못했습니다. 저장 공간 또는 브라우저 권한을 확인해주세요.', 'error');
}
return false;
}
},
createPersistableStateSnapshot() {
return JSON.parse(JSON.stringify({
habits: this.state.habits,
settings: this.state.settings,
achievements: this.state.achievements,
reviewPeriod: this.state.reviewPeriod,
visitedViews: this.state.visitedViews,
filters: this.state.filters,
reportPeriod: this.state.reportPeriod
}));
},
restorePersistableStateSnapshot(snapshot) {
if (!snapshot || typeof snapshot !== 'object') return;
Object.assign(this.state, JSON.parse(JSON.stringify(snapshot)));
},
saveDataOrRollback(snapshot, saveOptions = {}) {
if (this.saveData(saveOptions)) return true;
this.restorePersistableStateSnapshot(snapshot);
return false;
},
markViewVisited(viewName) {
const normalizedViewName = String(viewName ?? '');
if (!normalizedViewName) return false;
if (!this.state.visitedViews || typeof this.state.visitedViews !== 'object' || Array.isArray(this.state.visitedViews)) {
this.state.visitedViews = {};
}
if (this.state.visitedViews[normalizedViewName] === true) return true;
const previousState = this.createPersistableStateSnapshot();
this.state.visitedViews[normalizedViewName] = true;
return this.saveDataOrRollback(previousState);
},
updateFilterPreference(key, value) {
if (!['search', 'showArchived', 'sortBy'].includes(key)) return false;
if (Object.is(this.state.filters[key], value)) return false;
this.state.filters = { ...this.state.filters, [key]: value };
// 필터는 핵심 습관 데이터가 아니므로 저장 실패 시 현재 화면 선택까지
// 되돌리지는 않습니다. saveData()가 실패 원인을 알리고, 원본 저장값은 보존합니다.
this.saveData();
return true;
},
sanitizeLoadedState(rawState = {}, options = {}) {
if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
rawState = {};
}
const reportStructuralCorruption = () => {
if (typeof options?.onStructuralCorruption === 'function') {
options.onStructuralCorruption();
}
};
const now = Date.now();
const usedIds = new Set();
const safeDatePattern = /^\d{4}-\d{2}-\d{2}$/;
const validViews = new Set(['calendar', 'today', 'stats', 'timeline', 'review', 'archive']);
const validSorts = new Set(['order', 'name_asc', 'name_desc', 'created_at', 'streak', 'completion_rate']);
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
const isPlainStateObject = value => Boolean(value)
&& typeof value === 'object'
&& !Array.isArray(value);
const readOptionalStateObject = (propertyName) => {
if (!hasOwn(rawState, propertyName)) return {};
if (!isPlainStateObject(rawState[propertyName])) {
reportStructuralCorruption();
return {};
}
return rawState[propertyName];
};
const parseBooleanScalar = value => {
if (typeof value === 'boolean') return value;
if (value === 1 || value === '1') return true;
if (value === 0 || value === '0') return false;
if (typeof value !== 'string') return null;
const normalized = value.trim().toLowerCase();
if (normalized === 'true') return true;
if (normalized === 'false') return false;
return null;
};
const parseFiniteNumericScalar = value => {
if (typeof value !== 'number' && typeof value !== 'string') return null;
if (typeof value === 'string' && value.trim() === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
const makeId = (value, index) => {
return allocateUniqueHabitId(value, usedIds, now + index + 1);
};
const normalizeFrequency = (frequency) => {
const validTypes = new Set(['daily', 'weekdays', 'weekends', 'specific_days']);
const isFrequencyObject = Boolean(frequency) && typeof frequency === 'object' && !Array.isArray(frequency);
if (frequency !== undefined && !isFrequencyObject) reportStructuralCorruption();
if (isFrequencyObject
&& Object.prototype.hasOwnProperty.call(frequency, 'type')
&& !validTypes.has(frequency.type)) {
reportStructuralCorruption();
}
if (isFrequencyObject
&& Object.prototype.hasOwnProperty.call(frequency, 'days')
&& !Array.isArray(frequency.days)) {
reportStructuralCorruption();
}
// 특정 요일 습관에서 days가 통째로 누락되면 기본 7일로 대체되어
// 사용자가 지정했던 일정과 과거 달성률이 바뀝니다. 원본을 덮어쓰지 않습니다.
if (frequency?.type === 'specific_days'
&& !Object.prototype.hasOwnProperty.call(frequency, 'days')) {
reportStructuralCorruption();
}
const type = validTypes.has(frequency?.type) ? frequency.type : 'daily';
const defaultDays = {
daily: [0,1,2,3,4,5,6],
weekdays: [1,2,3,4,5],
weekends: [0,6],
specific_days: [0,1,2,3,4,5,6]
}[type];
const rawDays = Array.isArray(frequency?.days) ? frequency.days : defaultDays;
const hasInvalidDay = rawDays.some(day => {
const numericDay = parseFiniteNumericScalar(day);
return numericDay === null
|| !Number.isInteger(numericDay)
|| numericDay < 0
|| numericDay > 6;
});
if (Array.isArray(frequency?.days) && (rawDays.length === 0 || hasInvalidDay)) {
reportStructuralCorruption();
}
const days = Array.from(new Set(rawDays
.map(parseFiniteNumericScalar)
.filter(day => Number.isInteger(day) && day >= 0 && day <= 6)));
return { type, days: days.length ? days : defaultDays };
};
const getValidLocalDateTimestamp = (dateStr) => {
if (!safeDatePattern.test(dateStr)) return null;
const [year, month, day] = dateStr.split('-').map(Number);
const localDate = new Date(year, month - 1, day);
if (localDate.getFullYear() !== year || localDate.getMonth() !== month - 1 || localDate.getDate() !== day) {
return null;
}
localDate.setHours(0, 0, 0, 0);
return localDate.getTime();
};
const normalizeLogs = (logs) => {
const safeLogs = {};
// 현재 저장 형식에서 logs는 빈 습관에도 반드시 존재합니다.
// 누락된 필드를 빈 객체로 저장하면 원래의 실천 기록을 복구할 단서가 사라집니다.
if (logs === undefined) {
reportStructuralCorruption();
return safeLogs;
}
if (!logs || typeof logs !== 'object' || Array.isArray(logs)) {
reportStructuralCorruption();
return safeLogs;
}
for (const [date, entry] of Object.entries(logs)) {
// 형식만 맞는 존재하지 않는 날짜(예: 2026-02-31)가 Date에서 다음 달로
// 자동 보정되어 통계·업적 계산에 섞이지 않도록 달력 유효성까지 확인합니다.
if (getValidLocalDateTimestamp(date) === null) {
reportStructuralCorruption();
continue;
}
const valueToCheck = entry && typeof entry === 'object' && !Array.isArray(entry)
? entry.value
: entry;
const value = parseFiniteNumericScalar(valueToCheck);
// 습관 기록은 완료(1)/미완료(0)만 존재합니다. 0.5, 2, -1 등의
// 손상된 원본을 0/1로 강제 변환하면 다음 저장에서 원본 정보가 사라집니다.
// 구버전 호환용 숫자 문자열은 허용하되 이진 값 외에는 보호 모드로 전환합니다.
if (value === null || (value !== 0 && value !== 1)) {
reportStructuralCorruption();
continue;
}
safeLogs[date] = { value };
}
return safeLogs;
};
const habits = Array.isArray(rawState.habits) ? rawState.habits : [];
const sanitizedHabits = habits
.map((habit, index) => {
if (!habit || typeof habit !== 'object' || Array.isArray(habit)) {
reportStructuralCorruption();
return null;
}
const normalizedLogs = normalizeLogs(habit.logs);
const rawCreatedAt = Number(habit.createdAt);
const hasValidCreatedAt = (typeof habit.createdAt === 'number'
|| (typeof habit.createdAt === 'string' && habit.createdAt.trim() !== ''))
&& Number.isFinite(rawCreatedAt)
&& rawCreatedAt > 0
&& !Number.isNaN(new Date(rawCreatedAt).getTime());
// 통합 저장본의 생성일/정렬 순서가 명시적으로 손상됐는데 이를
// 오늘/배열 위치로 바꿔 저장하면 원래 작성일 및 사용자 지정 순서가 소실됩니다.
// 구버전에서 필드가 없는 경우에만 기존 호환 기본값을 사용합니다.
if (hasOwn(habit, 'createdAt') && !hasValidCreatedAt) {
reportStructuralCorruption();
}
const rawOrder = habit.order;
const hasValidOrder = (typeof rawOrder === 'number'
|| (typeof rawOrder === 'string' && rawOrder.trim() !== ''))
&& Number.isFinite(Number(rawOrder));
if (hasOwn(habit, 'order') && !hasValidOrder) {
reportStructuralCorruption();
}
if (Object.prototype.hasOwnProperty.call(habit, 'name')
&& (habit.name === null || typeof habit.name === 'object')) {
// 객체/배열/null 습관명을 문자열로 강제 변환해 원본을 조용히
// 훼손하지 않고, 손상 데이터 보호 모드로 전환합니다.
reportStructuralCorruption();
}
const isArchived = hasOwn(habit, 'isArchived')
? parseBooleanScalar(habit.isArchived)
: false;
if (isArchived === null) {
// Boolean("false")가 true가 되어 활성 습관을 보관함으로 숨기는
// 조용한 의미 반전을 막고, 해석 불가능한 원본은 보호합니다.
reportStructuralCorruption();
}
const earliestLogTimestamp = Object.keys(normalizedLogs)
.sort()
.map(getValidLocalDateTimestamp)
.find(timestamp => timestamp !== null);
return {
id: makeId(habit.id, index),
// 입력 단계에 없는 길이 제한을 로드 단계에서만 적용하면
// 재시작 후 사용자가 작성한 접미부가 조용히 손실됩니다.
name: String(habit.name ?? 'Untitled').trim() || 'Untitled',
type: 'check',
goal: 1,
frequency: normalizeFrequency(habit.frequency),
isArchived: isArchived ?? false,
order: hasValidOrder ? Number(rawOrder) : index,
logs: normalizedLogs,
createdAt: hasValidCreatedAt ? rawCreatedAt : (earliestLogTimestamp ?? now + index)
};
})
.filter(Boolean)
.sort((a, b) => a.order - b.order);
// 보조 컨테이너가 배열/null/문자열인데도 빈 객체로 조용히 바꾸면, 다음
// 일반 저장이 원본 업적·방문 기록·필터를 영구적으로 덮어쓸 수 있습니다.
const rawFilters = readOptionalStateObject('filters');
const rawSettings = readOptionalStateObject('settings');
const rawAchievements = readOptionalStateObject('achievements');
const rawVisited = readOptionalStateObject('visitedViews');
const currentDate = rawState.currentDate instanceof Date ? rawState.currentDate : new Date();
currentDate.setHours(0, 0, 0, 0);
// 손상된 검색 조건을 String()으로 강제 변환한 뒤 재저장하면
// 백업에서 복원할 수 있던 원래 값이 조용히 훼손될 수 있습니다.
if (hasOwn(rawFilters, 'search') && typeof rawFilters.search !== 'string') {
reportStructuralCorruption();
}
const showArchived = hasOwn(rawFilters, 'showArchived')
? parseBooleanScalar(rawFilters.showArchived)
: false;
if (showArchived === null) reportStructuralCorruption();
const normalizedVisitedViews = {};
Object.entries(rawVisited).forEach(([key, value]) => {
if (!validViews.has(key)) return;
const visited = parseBooleanScalar(value);
if (visited === null) {
reportStructuralCorruption();
return;
}
if (visited) normalizedVisitedViews[key] = true;
});
// [MAJOR BUG FIX] 업적 컨테이너만 객체인지 확인하고 개별 항목은 조용히
// 버리거나 String()으로 강제 변환하면, 다음 일반 저장에서 손상 원본의
// 업적 정보가 영구적으로 덮어써질 수 있습니다. 가져오기 검증과 동일하게
// 알려진 업적 항목의 구조까지 확인하고, 해석 불가능하면 보호 모드로 전환합니다.
const normalizedAchievements = {};
Object.entries(rawAchievements).forEach(([key, value]) => {
if (!achievementList[key]) return;
if (!isPlainStateObject(value)
|| (hasOwn(value, 'unlockedAt') && typeof value.unlockedAt !== 'string')) {
reportStructuralCorruption();
return;
}
normalizedAchievements[key] = {
unlockedAt: typeof value.unlockedAt === 'string' ? value.unlockedAt : ''
};
});
return {
habits: sanitizedHabits,
currentView: validViews.has(rawState.currentView) ? rawState.currentView : 'calendar',
currentDate,
settings: { theme: rawSettings.theme === 'dark' ? 'dark' : 'light' },
achievements: normalizedAchievements,
reviewPeriod: rawState.reviewPeriod === 'monthly' ? 'monthly' : 'weekly',
visitedViews: normalizedVisitedViews,
filters: {
search: String(rawFilters.search ?? '').slice(0, 120),
showArchived: showArchived ?? false,
sortBy: validSorts.has(rawFilters.sortBy) ? rawFilters.sortBy : 'order'
},
reportPeriod: ['weekly', 'monthly', 'yearly', 'this_week', 'this_month'].includes(rawState.reportPeriod) ? rawState.reportPeriod : 'weekly',
chartInstances: {}
};
},
loadData() {
this._hadDataLoadError = false;
// [수정] MothNote와 통합된 키에서 데이터를 로드
let data = null;
let oldData = null;
let veryOldData = null;
try {
data = localStorage.getItem('habitTrackerDataV2_integrated');
oldData = localStorage.getItem('habitTrackerDataV2'); // 이전 버전 키
veryOldData = localStorage.getItem('habitTrackerData'); // 아주 오래된 버전 키
} catch (error) {
// 저장소 접근 자체가 실패한 경우 데이터의 존재 여부를 알 수 없습니다.
// 빈 상태를 표시하되 저장 및 기본 데이터 생성을 막아, 보이지 않는 원본을 보호합니다.
this._hadDataLoadError = true;
this._hasPersistedIntegratedData = true;
console.error('Habit tracker storage could not be read. Starting in a protected safe state.', error);
const safeState = this.sanitizeLoadedState({});
const initialTheme = new URLSearchParams(window.location.search).get('theme') || 'light';
safeState.settings.theme = initialTheme;
this.state = { ...this.state, ...safeState, chartInstances: {} };
return;
}
this._hasPersistedIntegratedData = data !== null;
if (data !== null) {
try {
if (typeof data !== 'string' || data.trim() === '') {
throw new Error('Integrated habit data is empty.');
}
const parsedData = JSON.parse(data);
if (!parsedData || typeof parsedData !== 'object' || Array.isArray(parsedData) || !Array.isArray(parsedData.habits)) {
throw new Error('Integrated habit data has an invalid top-level structure.');
}
// [수정] 저장된 날짜(과거)를 무시하고 항상 '오늘' 날짜로 초기화합니다.
const today = new Date();
today.setHours(0, 0, 0, 0);
parsedData.currentDate = today;
// 기존 state에 덮어씌우되, 손상/조작된 로컬 데이터는 먼저 정규화합니다.
// 사용자 습관/로그 레코드가 유실되는 정규화는 실패로 처리해 원본 키를 보존합니다.
let hasStructuralCorruption = false;
const sanitizedState = this.sanitizeLoadedState(parsedData, {
onStructuralCorruption: () => { hasStructuralCorruption = true; }
});
if (hasStructuralCorruption) {
throw new Error('Integrated habit data contains malformed habit, frequency, or log records.');
}
this.state = { ...this.state, ...sanitizedState, chartInstances: {} };
} catch (error) {
this._hadDataLoadError = true;
console.error('Habit tracker data load failed. Starting with a safe empty state without deleting the original data.', error);
try {
localStorage.setItem('habitTrackerDataV2_integrated_corrupt_backup', JSON.stringify({
timestamp: Date.now(),
data
}));
} catch (backupError) {
console.warn('Failed to preserve corrupt habit tracker data backup.', backupError);
}
// 원본 키를 삭제하지 않습니다. 기본 습관 자동 생성도 막아 손상 원본을 샘플 데이터로 덮어쓰지 않습니다.
this.state = { ...this.state, ...this.sanitizeLoadedState({}), chartInstances: {} };
}
// [수정] URL 파라미터에서 초기 테마를 가져옵니다.
const urlParams = new URLSearchParams(window.location.search);
const initialTheme = urlParams.get('theme') || 'light';
this.state.settings.theme = initialTheme;
} else {
const urlParams = new URLSearchParams(window.location.search);
const initialTheme = urlParams.get('theme') || 'light';
this.state.settings = { theme: initialTheme };
const today = new Date();
today.setHours(0,0,0,0);
this.state.currentDate = today;
}
// 레거시 마이그레이션은 현재 통합 데이터가 '없을 때'만 합니다.
// 통합 키의 habits: []는 유효한 사용자 상태이며, 오래된 키로 덮어쓰면 안 됩니다.
if (!this._hadDataLoadError && !this._hasPersistedIntegratedData && (oldData || veryOldData)) {
console.log("Old data found and no new data exists. Migrating...");
this.migrateData(oldData || veryOldData, oldData ? 'habitTrackerDataV2' : 'habitTrackerData');
}
},
migrateData(oldDataString, legacyKey = null) {
const previousState = this.state;
try {
const oldState = JSON.parse(oldDataString);
if (!oldState || typeof oldState !== 'object' || Array.isArray(oldState) || !Array.isArray(oldState.habits)) {
throw new Error('Legacy habit data has an invalid top-level structure.');
}
// 변환 후에만 검사하면 `logs || {}`와 비교 연산이 손상 원본을
// 빈 기록/미완료로 바꿔 버립니다. 원본을 삭제하기 전에 변환 전
// 컨테이너와 V1 기록 값을 확인하여 손실이 있는 변환은 중단합니다.
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
for (const key of ['settings', 'achievements', 'visitedViews', 'filters']) {
if (hasOwn(oldState, key) && !isRecord(oldState[key])) {
throw new Error(`Legacy habit ${key} data has an invalid structure.`);
}
}
const readLegacyLogNumber = value => {
// 구버전 체크 기록의 true/false와 숫자 문자열은 기존 의미를 유지합니다.
if (typeof value === 'boolean') return Number(value);
if ((typeof value !== 'number' && typeof value !== 'string')
|| (typeof value === 'string' && value.trim() === '')) {
throw new Error('Legacy habit log value is not numeric.');
}
const number = Number(value);
if (!Number.isFinite(number)) throw new Error('Legacy habit log value is not finite.');
return number;
};
// 구버전 ID는 단순 순번일 수도 있으므로 생성 시각으로 무조건 사용하지 않습니다.
// 실제 생성 시각이 있으면 보존하고, 없으면 시간 기반 ID와 가장 오래된
// 유효 로그를 이용합니다. 어느 쪽도 알 수 없으면 로더의 기본값에 맡깁니다.
const getLegacyCreatedAt = habit => {
if (hasOwn(habit, 'createdAt')) {
const value = habit.createdAt;
const timestamp = (typeof value === 'number' || (typeof value === 'string' && value.trim()))
? Number(value) : NaN;
if (!Number.isFinite(timestamp) || timestamp <= 0 || Number.isNaN(new Date(timestamp).getTime())) {
throw new Error('Legacy habit creation time is invalid.');
}
return timestamp;
}
let firstLogTime = null;
for (const dateText of Object.keys(habit.logs || {})) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateText);
if (!match) continue;
const year = Number(match[1]), month = Number(match[2]) - 1, day = Number(match[3]);
const date = new Date(year, month, day);
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) continue;
const timestamp = date.getTime();
if (firstLogTime === null || timestamp < firstLogTime) firstLogTime = timestamp;
}
const idTimestamp = Number(habit.id);
const looksLikeTimestamp = Number.isFinite(idTimestamp)
&& idTimestamp >= 946684800000 && idTimestamp <= Date.now();
if (looksLikeTimestamp) return firstLogTime === null ? idTimestamp : Math.min(idTimestamp, firstLogTime);
return firstLogTime === null ? undefined : firstLogTime;
};
// 아주 오래된 데이터 형식(V1)인지 확인
const isVeryOld = !oldState.version;
let migrationCandidate;
if (isVeryOld) {
migrationCandidate = {
...this.state,
habits: oldState.habits.map((habit, index) => {
if (!isRecord(habit)
|| (hasOwn(habit, 'name') && (habit.name === null || typeof habit.name === 'object'))
|| (hasOwn(habit, 'logs') && !isRecord(habit.logs))) {
throw new Error('Legacy habit or log data has an invalid structure.');
}
const goal = habit.type === 'count' && hasOwn(habit, 'goal')
? readLegacyLogNumber(habit.goal)
: 1;
if (goal <= 0) throw new Error('Legacy habit count goal must be positive.');
const createdAt = getLegacyCreatedAt(habit);
return {
id: habit.id || Date.now() + index,
name: habit.name || 'Untitled',
type: 'check',
goal: 1,
frequency: hasOwn(habit, 'frequency')
? habit.frequency
: { type: 'daily', days: [0, 1, 2, 3, 4, 5, 6] },
isArchived: hasOwn(habit, 'isArchived') ? habit.isArchived : false,
order: hasOwn(habit, 'order') ? habit.order : index,
...(createdAt === undefined ? {} : { createdAt }),
logs: Object.entries(habit.logs || {}).reduce((acc, [date, value]) => {
const numericValue = readLegacyLogNumber(value);
const wasCompleted = habit.type === 'count' ? numericValue >= goal : numericValue > 0;
acc[date] = { value: wasCompleted ? 1 : 0 };
return acc;
}, {}),
};
}),
settings: { ...this.state.settings, theme: oldState.settings?.theme || 'light' },
achievements: oldState.achievements || {},
visitedViews: oldState.visitedViews || {},
filters: oldState.filters || { search: '', showArchived: false, sortBy: 'order' },
reviewPeriod: oldState.reviewPeriod || this.state.reviewPeriod,
reportPeriod: oldState.reportPeriod || this.state.reportPeriod
};
} else {
// V2 데이터 마이그레이션 (기존 로직 유지)
migrationCandidate = {
...this.state,
habits: oldState.habits,
achievements: oldState.achievements || {},
visitedViews: oldState.visitedViews || {},
filters: oldState.filters || { search: '', showArchived: false, sortBy: 'order' },
settings: { ...this.state.settings, theme: oldState.settings?.theme || 'light' }
};
}
// [CRITICAL BUG FIX] 레거시 구조가 손상된 경우 빈 정제본을 새 통합 키에 저장한 뒤
// 유일한 구버전 원본까지 삭제하면 복구할 수 없는 데이터 유실이 발생합니다.
// 후보 상태를 메모리 밖에서 검증하고, 모든 레코드가 구조 검사를 통과한 경우에만
// 현재 상태 교체와 신규 키 저장을 수행하고 레거시 원본은 보존합니다.
let hasStructuralCorruption = false;
const sanitizedCandidate = this.sanitizeLoadedState(migrationCandidate, {
onStructuralCorruption: () => { hasStructuralCorruption = true; }
});
if (hasStructuralCorruption) {
throw new Error('Legacy habit data contains malformed habit, frequency, or log records.');
}
this.state = { ...this.state, ...sanitizedCandidate, chartInstances: {} };
if (this.saveData()) {
this._hasPersistedIntegratedData = true;
// V1의 횟수형 기록은 현재 체크형으로 변환되며, 다른 레거시 키가
// 서로 다른 기록을 담을 수도 있습니다. 어느 원본도 삭제하지 않습니다.
// 통합 키가 존재하는 동안에는 레거시 데이터가 다시 적용되지 않습니다.
this.showToast("데이터 구조가 최신 버전으로 업데이트되었습니다!", 'info');
} else {
this.state = previousState;
this._hadDataLoadError = true;
this.showToast("데이터 구조 업데이트 중 저장에 실패했습니다. 기존 데이터를 유지했습니다.", 'error');
}
} catch (e) {
// 마이그레이션이 실패한 세션에서 기본 샘플이나 후속 UI 저장이 신규 통합 키를
// 만들어 레거시 원본을 가리는 일을 막습니다. 사용자가 명시적으로 초기화하기
// 전까지 기존 키를 유일한 복구 원본으로 보존합니다.
this.state = previousState;
this._hadDataLoadError = true;
console.error("Failed to migrate old data:", e);
this.showToast("구버전 습관 데이터 구조를 확인할 수 없어 원본을 보존했습니다. 정상 백업을 복원하거나 명시적으로 초기화해주세요.", 'error');
}
},
applySettings() {
// [수정] body의 클래스를 직접 조작하는 대신 data-theme 속성을 사용
if (this.state.settings.theme === 'dark') {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
// 차트 색상 업데이트
this.destroyCharts();
this.render();
},
toggleTheme() {
// 이 함수는 이제 postMessage를 통해서만 호출되므로 내부 로직은 불필요
},
// ----- RENDERING -----
render() {
this.updateActiveViewButton();
this.renderFilters();
this.destroyCharts();
const viewRenderers = {
calendar: this.renderCalendar,
today: this.renderToday,
stats: this.renderStats,
timeline: this.renderTimeline,
review: this.renderReview,
archive: this.renderArchive,
};
const renderFunction = viewRenderers[this.state.currentView];
if (renderFunction) {
renderFunction.call(this);
}
},
updateActiveViewButton() {
this.elements.viewButtons.forEach(btn => {
btn.classList.toggle('active', btn.id === `view-${this.state.currentView}`);
});
},
renderFilters() {
const showSort = ['today', 'stats'].includes(this.state.currentView);
const sortOptions = `
<label for="sort-by">정렬:</label>
<select id="sort-by">
<option value="order" ${this.state.filters.sortBy === 'order' ? 'selected' : ''}>기본</option>
<option value="name_asc" ${this.state.filters.sortBy === 'name_asc' ? 'selected' : ''}>이름 (오름차순)</option>
<option value="name_desc" ${this.state.filters.sortBy === 'name_desc' ? 'selected' : ''}>이름 (내림차순)</option>
<option value="created_at" ${this.state.filters.sortBy === 'created_at' ? 'selected' : ''}>최신순</option>
<option value="streak" ${this.state.filters.sortBy === 'streak' ? 'selected' : ''}>현재 연속일순</option>
<option value="completion_rate" ${this.state.filters.sortBy === 'completion_rate' ? 'selected' : ''}>달성률순</option>
</select>
`;
const html = `
<div class="filters">
<input type="search" id="search-filter" placeholder="습관 검색 후 Enter..." value="${this.escapeHTML(this.state.filters.search)}">
<label>
<input type="checkbox" id="archived-filter" ${this.state.filters.showArchived ? 'checked' : ''}>
보관된 습관 보기
</label>
${showSort ? sortOptions : ''}
</div>`;
this.elements.appFiltersContainer.innerHTML = (this.state.currentView !== 'archive' && this.state.currentView !== 'review') ? html : '';
if (this.state.currentView !== 'archive' && this.state.currentView !== 'review') {
const searchInput = document.getElementById('search-filter');
searchInput.addEventListener('keydown', (e) => {
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter') {
const search = String(e.target.value ?? '').slice(0, 120);
if (this.updateFilterPreference('search', search)) this.render();
}
});
searchInput.addEventListener('blur', (e) => {
const search = String(e.target.value ?? '').slice(0, 120);
if (this.updateFilterPreference('search', search)) this.render();
});
document.getElementById('archived-filter').addEventListener('change', (e) => {
if (this.updateFilterPreference('showArchived', Boolean(e.target.checked))) this.render();
});
if(showSort) {
document.getElementById('sort-by').addEventListener('change', (e) => {
if (this.updateFilterPreference('sortBy', e.target.value)) this.render();
});
}
}
},
getFilteredHabits() {
const { sortBy, showArchived, search } = this.state.filters;
const searchLower = search.toLowerCase();
let filteredHabits = this.state.habits
.filter(h => h.isArchived === showArchived)
.filter(h => h.name.toLowerCase().includes(searchLower));
if (['streak', 'completion_rate'].includes(sortBy)) {
filteredHabits = filteredHabits.map(h => ({
...h,
stats: this.calculateHabitStats(h)
}));
}
return filteredHabits.sort((a, b) => {
switch (sortBy) {
case 'name_asc': return a.name.localeCompare(b.name);
case 'name_desc': return b.name.localeCompare(a.name);
case 'created_at': return (b.createdAt || b.id) - (a.createdAt || a.id);
case 'streak': return (b.stats?.currentStreak || 0) - (a.stats?.currentStreak || 0);
case 'completion_rate': return (b.stats?.completionRate || 0) - (a.stats?.completionRate || 0);
case 'order':
default:
return (a.order || 0) - (b.order || 0);
}
});
},
renderEmptyState(view) {
let message = {};
const hasSearchTerm = this.state.filters.search.trim() !== '';
if (this.state.habits.length === 0) {
message = { title: "첫 습관을 만들어볼까요? 🌱", body: "'새 습관 추가' 버튼을 눌러 추적하고 싶은 첫 습관을 만들어보세요!", showAddButton: true };
} else if (hasSearchTerm && this.getFilteredHabits().length === 0) {
message = { title: "검색 결과 없음 🧐", body: `"${this.escapeHTML(this.state.filters.search)}"에 대한 검색 결과가 없습니다.`, showAddButton: false };
} else if (view === 'today' || view === 'calendar') {
message = { title: "표시할 습관이 없어요 🤷", body: "이 날짜에는 예정된 습관이 없거나 필터와 일치하는 습관이 없습니다.", showAddButton: false };
} else {
message = { title: "표시할 습관이 없어요 🤷", body: "필터 설정을 확인하거나 새로운 습관을 추가해보세요.", showAddButton: false };
}
this.elements.appContent.innerHTML = `
<div class="empty-state">
<h3>${message.title}</h3>
<p>${message.body}</p>
${message.showAddButton ? '<button id="empty-add-habit-btn">💪 첫 습관 추가하기</button>' : ''}
</div>