-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.v2.js
More file actions
2424 lines (2108 loc) · 72.9 KB
/
Copy pathapp.v2.js
File metadata and controls
2424 lines (2108 loc) · 72.9 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
// v20260502c - soft delete sync fix
const CLOUD_ENV = "YOUR_CLOUD_ENV_ID";
let app = null;
let auth = null;
let db = null;
let currentUser = null;
let pendingVerifyOtp = null;
let pendingPhone = null;
let syncTimer = null;
try {
if (typeof cloudbase !== "undefined") {
app = cloudbase.init({ env: CLOUD_ENV, region: "ap-shanghai" });
auth = app.auth();
db = app.database();
}
} catch (e) {
console.warn("CloudBase 初始化失败,离线模式:", e);
}
const STORAGE_KEY = "todo-list-app-v2";
const COLLAPSED_STORAGE_KEY = `${STORAGE_KEY}-collapsed`;
const THEME_STORAGE_KEY = `${STORAGE_KEY}-theme`;
const SORT_MODE_STORAGE_KEY = `${STORAGE_KEY}-sort-mode`;
const ORDER_STORAGE_KEY = `${STORAGE_KEY}-order`;
const THEME_MEDIA_QUERY = "(prefers-color-scheme: dark)";
const TASK_TYPES = ["阅读", "输出", "实践", "事务", "其他"];
const SORT_MODES = ["default", "date-asc", "date-desc", "priority"];
const WEEKDAY_MAP = {
一: 1,
二: 2,
三: 3,
四: 4,
五: 5,
六: 6,
日: 7,
天: 7,
};
const DEFAULT_TASK_ORDER = {
today: {},
deadline: {},
archive: {},
};
const DEFAULT_COLLAPSED_SECTIONS = {
today: false,
deadline: false,
archive: false,
};
const form = document.querySelector("#task-form");
const formTitle = document.querySelector("#form-title");
const formSubtitle = document.querySelector("#form-subtitle");
const submitButton = document.querySelector("#submit-btn");
const cancelEditButton = document.querySelector("#cancel-edit-btn");
const titleInput = document.querySelector("#task-title");
const typeInput = document.querySelector("#task-type");
const scopeInput = document.querySelector("#task-scope");
const taskDateInput = document.querySelector("#task-date");
const dueDateInput = document.querySelector("#task-due-date");
const taskDateField = document.querySelector("#task-date-field");
const dueDateField = document.querySelector("#task-due-date-field");
const dateHelper = document.querySelector("#date-helper");
const urgentInput = document.querySelector("#task-urgent");
const importantInput = document.querySelector("#task-important");
const quadrantPreview = document.querySelector("#quadrant-preview");
const searchFilter = document.querySelector("#filter-search");
const statusFilter = document.querySelector("#filter-status");
const typeFilter = document.querySelector("#filter-type");
const quadrantFilter = document.querySelector("#filter-quadrant");
const sortModeInput = document.querySelector("#sort-mode");
const exportButton = document.querySelector("#export-btn");
const importFileInput = document.querySelector("#import-file");
const quickAddForm = document.querySelector("#quick-add-form");
const quickAddInput = document.querySelector("#quick-add-input");
const totalCount = document.querySelector("#total-count");
const todayCount = document.querySelector("#today-count");
const completedCount = document.querySelector("#completed-count");
const overdueCount = document.querySelector("#overdue-count");
const todayLabel = document.querySelector("#today-label");
const themeToggleButton = document.querySelector("#theme-toggle");
const todayTaskList = document.querySelector("#today-task-list");
const deadlineTaskList = document.querySelector("#deadline-task-list");
const archiveTaskList = document.querySelector("#archive-task-list");
const todaySectionCount = document.querySelector("#today-section-count");
const deadlineSectionCount = document.querySelector("#deadline-section-count");
const archiveSectionCount = document.querySelector("#archive-section-count");
const noResultsState = document.querySelector("#no-results-state");
const emptyState = document.querySelector("#empty-state");
const taskSections = document.querySelector(".task-sections");
const undoToast = document.querySelector("#undo-toast");
const undoToastMessage = document.querySelector("#undo-toast-message");
const undoToastAction = document.querySelector("#undo-toast-action");
const overdueStatCard = document.querySelector("#overdue-stat-card");
const loginToggle = document.querySelector("#login-toggle");
const loginModal = document.querySelector("#login-modal");
const loginPhone = document.querySelector("#login-phone");
const loginCode = document.querySelector("#login-code");
const sendCodeBtn = document.querySelector("#send-code-btn");
const loginSubmitBtn = document.querySelector("#login-submit-btn");
const loginCancelBtn = document.querySelector("#login-cancel-btn");
const loginError = document.querySelector("#login-error");
const state = {
tasks: loadTasks(),
editingTaskId: null,
editingOriginalTask: null,
filters: {
search: "",
status: "all",
type: "all",
quadrant: "all",
tag: "all",
overdueOnly: false,
},
sortMode: loadSortMode(),
themePreference: loadThemePreference(),
collapsedSections: loadCollapsedSections(),
taskOrder: loadTaskOrder(),
undo: {
entry: null,
timeoutId: null,
},
pendingDelete: {
taskId: null,
timeoutId: null,
},
searchDebounceId: null,
login: {
isLoggedIn: false,
phone: "",
userId: "",
},
drag: {
taskId: null,
sourceSectionKey: null,
targetSectionKey: null,
targetTaskId: null,
position: null,
},
editingSubtasks: [],
};
function loadThemePreference() {
try {
const raw = localStorage.getItem(THEME_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
return parsed === "light" || parsed === "dark" ? parsed : null;
} catch {
return null;
}
}
function loadSortMode() {
try {
const raw = localStorage.getItem(SORT_MODE_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
return SORT_MODES.includes(parsed) ? parsed : "default";
} catch {
return "default";
}
}
function loadTaskOrder() {
try {
const raw = localStorage.getItem(ORDER_STORAGE_KEY);
if (!raw) {
return {
today: {},
deadline: {},
archive: {},
};
}
const parsed = JSON.parse(raw);
return {
today: normalizeOrderSection(parsed?.today),
deadline: normalizeOrderSection(parsed?.deadline),
archive: normalizeOrderSection(parsed?.archive),
};
} catch {
return {
today: {},
deadline: {},
archive: {},
};
}
}
function normalizeOrderSection(section) {
if (!section || typeof section !== "object" || Array.isArray(section)) {
return {};
}
return Object.fromEntries(
Object.entries(section).filter(
([taskId, value]) => typeof taskId === "string" && Number.isFinite(value)
)
);
}
function getSystemThemePreference() {
return window.matchMedia(THEME_MEDIA_QUERY).matches ? "dark" : "light";
}
function getResolvedTheme() {
return state.themePreference || getSystemThemePreference();
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
if (!themeToggleButton) {
return;
}
const isDark = theme === "dark";
themeToggleButton.textContent = isDark ? "浅色模式" : "深色模式";
themeToggleButton.setAttribute("aria-pressed", String(isDark));
themeToggleButton.setAttribute("aria-label", isDark ? "切换到浅色模式" : "切换到深色模式");
}
function saveThemePreference(theme) {
if (theme !== "light" && theme !== "dark") {
return false;
}
return saveToLocalStorage(THEME_STORAGE_KEY, theme);
}
function saveSortMode(sortMode) {
if (!SORT_MODES.includes(sortMode)) {
return false;
}
return saveToLocalStorage(SORT_MODE_STORAGE_KEY, sortMode);
}
function handleThemeToggle() {
const nextTheme = getResolvedTheme() === "dark" ? "light" : "dark";
if (!saveThemePreference(nextTheme)) {
applyTheme(getResolvedTheme());
return;
}
state.themePreference = nextTheme;
applyTheme(nextTheme);
}
function syncThemeWithSystem(event) {
if (state.themePreference) {
return;
}
applyTheme(event.matches ? "dark" : "light");
}
function createHighlightedTextFragment(text, keyword) {
const fragment = document.createDocumentFragment();
const normalizedKeyword = keyword.trim().toLowerCase();
if (!normalizedKeyword) {
fragment.append(text);
return fragment;
}
const lowerText = text.toLowerCase();
let searchStartIndex = 0;
let matchIndex = lowerText.indexOf(normalizedKeyword, searchStartIndex);
if (matchIndex === -1) {
fragment.append(text);
return fragment;
}
while (matchIndex !== -1) {
if (matchIndex > searchStartIndex) {
fragment.append(text.slice(searchStartIndex, matchIndex));
}
const mark = document.createElement("mark");
mark.textContent = text.slice(matchIndex, matchIndex + normalizedKeyword.length);
fragment.append(mark);
searchStartIndex = matchIndex + normalizedKeyword.length;
matchIndex = lowerText.indexOf(normalizedKeyword, searchStartIndex);
}
if (searchStartIndex < text.length) {
fragment.append(text.slice(searchStartIndex));
}
return fragment;
}
function setElementTextWithHighlight(element, text) {
element.textContent = "";
element.append(createHighlightedTextFragment(text, state.filters.search));
}
function getTaskDateValue(task) {
return task.scope === "deadline" ? task.dueDate || "9999-12-31" : task.taskDate || "9999-12-31";
}
function getPriorityWeight(task) {
if (task.urgent && task.important) return 0;
if (!task.urgent && task.important) return 1;
if (task.urgent && !task.important) return 2;
return 3;
}
function compareByCreatedAtDesc(a, b) {
return new Date(b.createdAt) - new Date(a.createdAt);
}
function compareByDate(a, b, direction = "asc") {
const comparison = getTaskDateValue(a).localeCompare(getTaskDateValue(b));
if (comparison !== 0) {
return direction === "desc" ? -comparison : comparison;
}
return compareByCreatedAtDesc(a, b);
}
function compareByPriority(a, b) {
const priorityComparison = getPriorityWeight(a) - getPriorityWeight(b);
if (priorityComparison !== 0) {
return priorityComparison;
}
if (a.completed !== b.completed) return Number(a.completed) - Number(b.completed);
return compareByCreatedAtDesc(a, b);
}
function sortTasks(tasks, sectionKey) {
if (state.sortMode === "date-asc") {
tasks.sort((a, b) => compareByDate(a, b, "asc"));
return;
}
if (state.sortMode === "date-desc") {
tasks.sort((a, b) => compareByDate(a, b, "desc"));
return;
}
if (state.sortMode === "priority") {
tasks.sort(compareByPriority);
return;
}
const orderMap = state.taskOrder[sectionKey] || {};
if (Object.keys(orderMap).length > 0) {
tasks.sort((a, b) => {
const aInMap = a.id in orderMap;
const bInMap = b.id in orderMap;
if (aInMap && bInMap) return orderMap[a.id] - orderMap[b.id];
if (!aInMap && !bInMap) return compareByCreatedAtDesc(a, b);
return aInMap ? -1 : 1;
});
return;
}
if (sectionKey === "deadline") {
tasks.sort(compareDeadlineTasks);
return;
}
if (sectionKey === "archive") {
tasks.sort((a, b) => b.taskDate.localeCompare(a.taskDate) || compareDailyTasks(a, b));
return;
}
tasks.sort(compareDailyTasks);
}
function getFocusableTaskItems() {
return Array.from(taskSections.querySelectorAll(".task-item"));
}
function focusAdjacentTaskItem(currentItem, direction) {
const items = getFocusableTaskItems();
const currentIndex = items.indexOf(currentItem);
if (currentIndex === -1) {
return;
}
const nextItem = items[currentIndex + direction];
if (nextItem) {
nextItem.focus();
}
}
function createTaskId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `task-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
function getTodayDateString() {
return new Date().toLocaleDateString("sv-SE");
}
function formatDate(dateString) {
if (!dateString) return "未设置";
const date = new Date(`${dateString}T00:00:00`);
return new Intl.DateTimeFormat("zh-CN", {
year: "numeric",
month: "long",
day: "numeric",
}).format(date);
}
function formatShortDate(dateString) {
if (!dateString) return "无日期";
const date = new Date(`${dateString}T00:00:00`);
return new Intl.DateTimeFormat("zh-CN", {
month: "numeric",
day: "numeric",
weekday: "short",
}).format(date);
}
function getQuadrant(urgent, important) {
if (urgent && important) return "紧急且重要";
if (urgent && !important) return "紧急不重要";
if (!urgent && important) return "重要不紧急";
return "不紧急不重要";
}
function getQuadrantClass(label) {
if (label === "紧急且重要") return "q1";
if (label === "紧急不重要") return "q2";
if (label === "重要不紧急") return "q3";
return "q4";
}
function getQuadrantVisual(label) {
if (label === "紧急且重要") return { icon: "●", shortLabel: "第一象限" };
if (label === "紧急不重要") return { icon: "▲", shortLabel: "第二象限" };
if (label === "重要不紧急") return { icon: "■", shortLabel: "第三象限" };
return { icon: "◆", shortLabel: "第四象限" };
}
function normalizeTask(task) {
const urgent = Boolean(task.urgent);
const important = Boolean(task.important);
const createdAt = task.createdAt || new Date().toISOString();
const createdDate = task.createdDate || createdAt.slice(0, 10);
const scope = task.scope === "deadline" ? "deadline" : "daily";
const taskDate = scope === "daily" ? task.taskDate || createdDate : "";
const dueDate = scope === "deadline" ? task.dueDate || "" : "";
return {
id: task.id || createTaskId(),
title: typeof task.title === "string" ? task.title : "",
type: TASK_TYPES.includes(task.type) ? task.type : "其他",
urgent,
important,
quadrant: getQuadrant(urgent, important),
completed: Boolean(task.completed),
createdAt,
createdDate,
scope,
taskDate,
dueDate,
subtasks: Array.isArray(task.subtasks)
? task.subtasks
.filter((s) => s && typeof s.title === "string" && s.title.trim())
.map((s) => ({
id: s.id || createTaskId(),
title: s.title.trim(),
completed: Boolean(s.completed),
}))
: [],
reminderAt: typeof task.reminderAt === "string" ? task.reminderAt : "",
recurrence:
task.recurrence && typeof task.recurrence === "object"
? {
type: ["daily", "weekly", "monthly"].includes(task.recurrence.type) ? task.recurrence.type : "",
interval: Number.isFinite(task.recurrence.interval) ? task.recurrence.interval : 1,
weekdays: Array.isArray(task.recurrence.weekdays) ? task.recurrence.weekdays : [],
endDate: typeof task.recurrence.endDate === "string" ? task.recurrence.endDate : "",
}
: { type: "", interval: 1, weekdays: [], endDate: "" },
tags: Array.isArray(task.tags)
? [...new Set(task.tags.filter((t) => typeof t === "string" && t.trim()).map((t) => t.trim()))]
: [],
deleted: Boolean(task.deleted),
deletedAt: typeof task.deletedAt === "string" ? task.deletedAt : "",
};
}
function scheduleSync() {
if (!state.login.isLoggedIn) return;
if (syncTimer) clearTimeout(syncTimer);
syncTimer = setTimeout(() => {
pushToCloud();
}, 1000);
}
async function pushToCloud() {
if (!db || !currentUser) return;
try {
const userId = currentUser.id;
const collection = db.collection("tasks");
// 循环删除直到清空,避免 limit(1000) 导致残留
let hasMore = true;
while (hasMore) {
const existing = await collection.where({ userId }).limit(1000).get();
const docs = existing.data || [];
if (docs.length === 0) {
hasMore = false;
} else {
await Promise.all(docs.map((doc) => collection.doc(doc._id).remove()));
if (docs.length < 1000) hasMore = false;
}
}
// 只推送未删除的任务,已删除的不再上传
var activeTasks = state.tasks.filter(function (t) { return !t.deleted; });
await Promise.all(
activeTasks.map((task) => collection.add({ ...task, userId }))
);
localStorage.setItem(STORAGE_KEY + '-cloud-synced', '1');
} catch (e) {
console.warn("推送到云端失败:", e);
}
}
async function syncFromCloud() {
if (!db || !currentUser) return;
try {
const userId = currentUser.id;
const result = await db.collection("tasks").where({ userId }).limit(1000).get();
const cloudTasks = (result.data || [])
.map(({ _id, userId, ...task }) => normalizeTask(task))
.filter((t) => t.title.trim() && !t.deleted);
const hasEverSynced = localStorage.getItem(STORAGE_KEY + '-cloud-synced');
if (cloudTasks.length === 0) {
if (hasEverSynced) {
// 云端曾有数据但现在为空 = 所有任务已被删除,清空本地
if (state.tasks.length > 0) {
commitTasks([]);
render();
}
} else {
// 从未同步过 = 首次使用,把本地数据推上去
if (state.tasks.filter((t) => !t.deleted).length > 0) {
await pushToCloud();
localStorage.setItem(STORAGE_KEY + '-cloud-synced', '1');
}
}
return;
}
// 云端有数据:直接用云端覆盖本地
localStorage.setItem(STORAGE_KEY + '-cloud-synced', '1');
if (!commitTasks(cloudTasks)) return;
render();
} catch (e) {
console.warn("从云端同步失败:", e);
}
}
function showLoginError(msg) {
loginError.textContent = msg;
loginError.hidden = false;
}
function clearLoginError() {
loginError.hidden = true;
loginError.textContent = "";
}
function openLoginModal() {
clearLoginError();
loginPhone.value = "";
loginCode.value = "";
loginModal.hidden = false;
loginPhone.focus();
}
function closeLoginModal() {
loginModal.hidden = true;
clearLoginError();
}
function updateLoginUI() {
if (state.login.isLoggedIn) {
const maskedPhone = state.login.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
loginToggle.textContent = maskedPhone + " 退出";
loginToggle.setAttribute("aria-label", "点击退出登录");
} else {
loginToggle.textContent = "登录同步";
loginToggle.setAttribute("aria-label", "点击登录以同步数据");
}
}
async function handleLogout() {
if (!window.confirm("确定要退出登录吗?退出后数据仅保存在本地。")) return;
try {
if (auth) await auth.signOut();
} catch (e) {
console.warn("CloudBase 退出失败:", e);
}
if (syncTimer) {
clearTimeout(syncTimer);
syncTimer = null;
}
currentUser = null;
pendingVerifyOtp = null;
pendingPhone = null;
state.login.isLoggedIn = false;
state.login.phone = "";
state.login.userId = "";
updateLoginUI();
}
async function sendVerificationCode() {
const phone = loginPhone.value.trim();
if (!/^1\d{10}$/.test(phone)) {
showLoginError("请输入正确的11位手机号");
return;
}
if (!auth) {
showLoginError("CloudBase 未初始化,请检查网络后刷新");
return;
}
try {
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = "发送中...";
const { data, error } = await auth.signInWithOtp({ phone });
if (error) {
throw new Error(error.message || "验证码发送失败");
}
// 保存 verifyOtp 回调和手机号,登录时使用
pendingVerifyOtp = data.verifyOtp;
pendingPhone = phone;
let seconds = 60;
const tick = () => {
seconds--;
sendCodeBtn.textContent = seconds > 0 ? `${seconds}s` : "发送验证码";
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
sendCodeBtn.disabled = false;
}
};
setTimeout(tick, 1000);
} catch (e) {
sendCodeBtn.textContent = "发送验证码";
sendCodeBtn.disabled = false;
showLoginError("发送失败:" + (e.message || "请重试"));
}
}
async function handleLogin() {
const phone = loginPhone.value.trim();
const code = loginCode.value.trim();
if (!/^1\d{10}$/.test(phone)) {
showLoginError("请输入正确的11位手机号");
return;
}
if (!/^\d{4,6}$/.test(code)) {
showLoginError("请输入4-6位验证码");
return;
}
if (!auth) {
showLoginError("CloudBase 未初始化,请检查网络后刷新");
return;
}
if (!pendingVerifyOtp) {
showLoginError("请先发送验证码");
return;
}
try {
loginSubmitBtn.disabled = true;
loginSubmitBtn.textContent = "登录中...";
let loginData = null;
let loginError = null;
let debugInfo = [];
// 方式1:使用 signInWithOtp 返回的 verifyOtp 闭包(主流浏览器兼容)
if (pendingVerifyOtp) {
debugInfo.push("闭包存在");
try {
const result = await pendingVerifyOtp({ token: code });
loginData = result.data;
loginError = result.error;
debugInfo.push("闭包结果: data=" + !!loginData + " error=" + JSON.stringify(loginError));
} catch (closureErr) {
console.warn("verifyOtp 闭包调用失败,尝试 fallback:", closureErr);
loginError = closureErr;
debugInfo.push("闭包异常: " + (closureErr.message || String(closureErr)));
}
} else {
debugInfo.push("闭包不存在");
}
// 方式2:fallback - 通过 resend 获取 messageId,再用 auth.verifyOtp 独立方法验证
if ((!loginData || loginError) && auth.verifyOtp && pendingPhone) {
debugInfo.push("尝试fallback");
try {
const { data: resendData, error: resendErr } = await auth.resend({
phone: pendingPhone,
type: "sms",
});
debugInfo.push("resend: err=" + JSON.stringify(resendErr) + " data=" + JSON.stringify(resendData));
if (!resendErr && resendData && resendData.messageId) {
const result = await auth.verifyOtp({
phone: pendingPhone,
token: code,
messageId: resendData.messageId,
});
loginData = result.data;
loginError = result.error;
debugInfo.push("fallback结果: data=" + !!loginData + " error=" + JSON.stringify(loginError));
}
} catch (fallbackErr) {
console.warn("verifyOtp fallback 也失败:", fallbackErr);
debugInfo.push("fallback异常: " + (fallbackErr.message || String(fallbackErr)));
if (!loginError) loginError = fallbackErr;
}
} else if (!loginData || loginError) {
debugInfo.push("无法fallback: verifyOtp=" + !!auth.verifyOtp + " phone=" + !!pendingPhone);
}
if (loginError || !loginData) {
throw new Error((loginError?.message || "登录失败") + " [" + debugInfo.join(" | ") + "]");
}
currentUser = loginData.user || null;
state.login.isLoggedIn = true;
state.login.phone = phone;
state.login.userId = currentUser ? currentUser.id : "";
pendingVerifyOtp = null;
pendingPhone = null;
updateLoginUI();
closeLoginModal();
await syncFromCloud();
} catch (e) {
showLoginError("登录失败:" + (e.message || JSON.stringify(e) || "请重试") + " [" + typeof e + "]");
} finally {
loginSubmitBtn.disabled = false;
loginSubmitBtn.textContent = "登录";
}
}
async function checkLoginState() {
if (!auth) return;
try {
const { data, error } = await auth.getSession();
if (error || !data || !data.user) return;
currentUser = data.user;
state.login.isLoggedIn = true;
state.login.userId = currentUser.id;
const rawPhone = currentUser.phone || "";
state.login.phone = rawPhone.replace(/^\+86\s*/, "");
updateLoginUI();
await syncFromCloud();
} catch (e) {
// not logged in, normal
}
}
function loadTasks() {
try {
const raw = localStorage.getItem(STORAGE_KEY) || localStorage.getItem("todo-list-app-v1");
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.map(normalizeTask).filter((task) => task.title.trim());
} catch {
return [];
}
}
function loadCollapsedSections() {
try {
const raw = localStorage.getItem(COLLAPSED_STORAGE_KEY);
if (!raw) return { ...DEFAULT_COLLAPSED_SECTIONS };
const parsed = JSON.parse(raw);
return {
today: Boolean(parsed?.today),
deadline: Boolean(parsed?.deadline),
archive: Boolean(parsed?.archive),
};
} catch {
return { ...DEFAULT_COLLAPSED_SECTIONS };
}
}
function saveToLocalStorage(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch {
window.alert("保存失败,请清理浏览器存储空间后重试。");
return false;
}
}
function saveTasks() {
return saveToLocalStorage(STORAGE_KEY, state.tasks);
}
function saveCollapsedSections() {
return saveToLocalStorage(COLLAPSED_STORAGE_KEY, state.collapsedSections);
}
function commitTasks(nextTasks) {
const previousTasks = state.tasks;
state.tasks = nextTasks;
if (saveTasks()) {
scheduleSync();
return true;
}
state.tasks = previousTasks;
return false;
}
function isTaskOverdue(task) {
const today = getTodayDateString();
return task.scope === "deadline" && Boolean(task.dueDate) && task.dueDate < today && !task.completed;
}
function buildSearchText(task) {
return [
task.title,
task.type,
task.quadrant,
task.scope === "daily" ? "当日任务" : "截止任务",
task.taskDate,
task.dueDate,
formatDate(task.taskDate),
formatDate(task.dueDate),
formatShortDate(task.taskDate),
formatShortDate(task.dueDate),
...task.tags,
]
.filter(Boolean)
.join(" ")
.toLowerCase();
}
function matchesFilters(task) {
if (task.deleted) return false;
const searchKeyword = state.filters.search.trim().toLowerCase();
if (searchKeyword && !buildSearchText(task).includes(searchKeyword)) {
return false;
}
if (state.filters.status === "completed" && !task.completed) {
return false;
}
if (state.filters.status === "active" && task.completed) {
return false;
}
if (state.filters.type !== "all" && task.type !== state.filters.type) {
return false;
}
if (state.filters.quadrant !== "all" && task.quadrant !== state.filters.quadrant) {
return false;
}
if (state.filters.tag !== "all" && !task.tags.includes(state.filters.tag)) {
return false;
}
if (state.filters.overdueOnly && !isTaskOverdue(task)) {
return false;
}
return true;
}
function compareDailyTasks(a, b) {
if (a.completed !== b.completed) return Number(a.completed) - Number(b.completed);
return new Date(b.createdAt) - new Date(a.createdAt);
}
function compareDeadlineTasks(a, b) {
if (a.completed !== b.completed) return Number(a.completed) - Number(b.completed);
if (a.dueDate && b.dueDate && a.dueDate !== b.dueDate) return a.dueDate.localeCompare(b.dueDate);
if (a.dueDate && !b.dueDate) return -1;
if (!a.dueDate && b.dueDate) return 1;
return new Date(b.createdAt) - new Date(a.createdAt);
}
function getVisibleTaskGroups() {
const today = getTodayDateString();
const groups = {
todayTasks: [],
deadlineTasks: [],
archiveTasks: [],
};
state.tasks.forEach((task) => {
if (!matchesFilters(task)) {
return;
}
if (task.scope === "deadline") {
groups.deadlineTasks.push(task);
return;
}
if (task.taskDate === today) {
groups.todayTasks.push(task);
return;
}
groups.archiveTasks.push(task);
});
sortTasks(groups.todayTasks, "today");
sortTasks(groups.deadlineTasks, "deadline");
sortTasks(groups.archiveTasks, "archive");
return groups;
}
function updateStats() {
const today = getTodayDateString();
const activeTasks = state.tasks.filter((task) => !task.deleted);
const completed = activeTasks.filter((task) => task.completed).length;
const todayPending = activeTasks.filter(
(task) => task.scope === "daily" && task.taskDate === today && !task.completed
).length;
const overdue = activeTasks.filter(isTaskOverdue).length;
totalCount.textContent = String(activeTasks.length);
todayCount.textContent = String(todayPending);
completedCount.textContent = String(completed);
overdueCount.textContent = String(overdue);
overdueStatCard?.setAttribute("aria-pressed", String(state.filters.overdueOnly));
todayLabel.textContent = `今天是 ${formatDate(today)}`;
}
function createBadge(text, className) {
const badge = document.createElement("span");
badge.className = className;
badge.textContent = text;
return badge;
}
function createQuadrantBadge(label) {
const visual = getQuadrantVisual(label);
const badge = document.createElement("span");
badge.className = `badge quadrant ${getQuadrantClass(label)}`;
const icon = document.createElement("span");
icon.className = "badge-icon";
icon.textContent = visual.icon;
const text = document.createElement("span");
text.textContent = `${visual.shortLabel} · ${label}`;
badge.append(icon, text);
return badge;
}
function createTaskItem(task) {
const item = document.createElement("li");
item.className = `task-item ${getQuadrantClass(task.quadrant)}${task.completed ? " completed" : ""}`;
item.dataset.id = task.id;
item.tabIndex = 0;
if (isTaskOverdue(task)) {
item.classList.add("overdue");
}
const checkbox = document.createElement("input");
checkbox.className = "task-toggle";
checkbox.type = "checkbox";
checkbox.checked = task.completed;
checkbox.setAttribute("aria-label", `完成任务:${task.title}`);
const main = document.createElement("div");
main.className = "task-main";
const topRow = document.createElement("div");
topRow.className = "task-top-row";