-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2026 lines (1762 loc) · 74 KB
/
script.js
File metadata and controls
2026 lines (1762 loc) · 74 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
class TODOStack {
constructor() {
this.stack = [];
this.completedTasks = [];
this.todayTaskCount = 0;
this.selectedTaskId = null; // 当前选中的任务ID
this.init();
this.loadFromStorage();
this.updateUI();
this.handleUrlParameters();
}
init() {
// 获取 DOM 元素
this.taskInput = document.getElementById('taskInput');
this.pushBtn = document.getElementById('pushBtn');
this.popBtn = document.getElementById('popBtn');
this.peekBtn = document.getElementById('peekBtn');
this.pinSelectedBtn = document.getElementById('pinSelectedBtn');
this.clearBtn = document.getElementById('clearBtn');
this.taskStack = document.getElementById('taskStack');
this.stackSize = document.getElementById('stackSize');
this.totalTasks = document.getElementById('totalTasks');
this.completedTasksEl = document.getElementById('completedTasks');
this.todayTasksEl = document.getElementById('todayTasks');
this.helpBtn = document.getElementById('helpBtn');
this.helpModal = document.getElementById('helpModal');
this.closeModal = document.getElementById('closeModal');
this.toggleHistoryBtn = document.getElementById('toggleHistory');
this.clearHistoryBtn = document.getElementById('clearHistory');
this.historyContainer = document.getElementById('historyContainer');
this.historyList = document.getElementById('historyList');
// 任务详情相关元素
this.toggleDetailsBtn = document.getElementById('toggleDetailsBtn');
this.collapseDetailsBtn = document.getElementById('collapseDetailsBtn');
this.taskDetailsSection = document.getElementById('taskDetailsSection');
this.taskDeadline = document.getElementById('taskDeadline');
this.taskPriority = document.getElementById('taskPriority');
this.taskDescription = document.getElementById('taskDescription');
this.taskUrl = document.getElementById('taskUrl');
this.taskFile = document.getElementById('taskFile');
this.taskTags = document.getElementById('taskTags');
this.attachmentsList = document.getElementById('attachmentsList');
this.tagsList = document.getElementById('tagsList');
this.previewBtn = document.getElementById('previewBtn');
this.editBtn = document.getElementById('editBtn');
this.markdownPreview = document.getElementById('markdownPreview');
// 拖拽相关属性
this.draggedElement = null;
this.draggedIndex = null;
this.historyVisible = false;
this.detailsVisible = false;
this.attachments = [];
// 绑定事件
this.bindEvents();
// 检查今日任务计数
this.checkDailyReset();
}
bindEvents() {
// 入栈事件
this.pushBtn.addEventListener('click', () => this.push());
this.taskInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !this.detailsVisible) {
this.push();
}
});
// 栈操作事件
this.popBtn.addEventListener('click', () => this.pop());
this.peekBtn.addEventListener('click', () => this.peek());
this.pinSelectedBtn.addEventListener('click', () => this.pinSelectedTask());
this.clearBtn.addEventListener('click', () => this.clear());
// 历史记录事件
this.toggleHistoryBtn.addEventListener('click', () => this.toggleHistory());
this.clearHistoryBtn.addEventListener('click', () => this.clearHistory());
// 任务详情事件
this.toggleDetailsBtn.addEventListener('click', () => this.toggleDetails());
this.collapseDetailsBtn.addEventListener('click', () => this.toggleDetails());
// Markdown 预览事件
this.previewBtn.addEventListener('click', () => this.showMarkdownPreview());
this.editBtn.addEventListener('click', () => this.hideMarkdownPreview());
// 文件上传事件
this.taskFile.addEventListener('change', (e) => this.handleFileUpload(e));
// 标签输入事件
this.taskTags.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
this.addTag();
}
});
this.taskTags.addEventListener('input', () => this.updateTagsList());
// 模态框事件
this.helpBtn.addEventListener('click', () => this.showHelp());
this.closeModal.addEventListener('click', () => this.hideHelp());
this.helpModal.addEventListener('click', (e) => {
if (e.target === this.helpModal) {
this.hideHelp();
}
});
// 键盘快捷键
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
switch(e.key) {
case 'Enter':
e.preventDefault();
this.push();
break;
case 'Backspace':
e.preventDefault();
this.pop();
break;
case 'd':
e.preventDefault();
this.toggleDetails();
break;
}
}
});
// 事件委托 - 处理动态生成的按钮
document.addEventListener('click', (e) => {
const target = e.target.closest('[data-action]');
if (!target) return;
const action = target.dataset.action;
const taskId = target.dataset.taskId;
switch(action) {
case 'toggle-details':
this.toggleTaskDetails(parseInt(taskId));
break;
case 'undo-complete':
this.undoComplete(taskId);
break;
case 'remove-attachment':
const attachmentId = target.dataset.attachmentId;
this.removeAttachment(parseInt(attachmentId));
break;
case 'remove-tag':
const tagToRemove = target.dataset.tag;
this.removeTagFromDisplay(tagToRemove);
break;
}
});
// 事件委托 - 处理描述编辑相关按钮
document.addEventListener('click', (e) => {
// 处理编辑按钮
if (e.target.closest('.edit-description-btn')) {
e.stopPropagation();
const btn = e.target.closest('.edit-description-btn');
const taskId = parseInt(btn.dataset.taskId);
this.showDescriptionEdit(taskId);
return;
}
// 处理保存按钮
if (e.target.closest('.save-description-btn')) {
e.stopPropagation();
const btn = e.target.closest('.save-description-btn');
const taskId = parseInt(btn.dataset.taskId);
this.saveDescriptionEdit(taskId);
return;
}
// 处理取消按钮
if (e.target.closest('.cancel-description-btn')) {
e.stopPropagation();
const btn = e.target.closest('.cancel-description-btn');
const taskId = parseInt(btn.dataset.taskId);
this.cancelDescriptionEdit(taskId);
return;
}
// 处理文本框点击
if (e.target.closest('.description-textarea')) {
e.stopPropagation();
return;
}
});
// 任务选择事件
document.addEventListener('click', (e) => {
const taskItem = e.target.closest('.task-item');
if (taskItem &&
!e.target.closest('[data-action]') &&
!e.target.closest('.expand-toggle') &&
!e.target.closest('.edit-description-btn') &&
!e.target.closest('.save-description-btn') &&
!e.target.closest('.cancel-description-btn') &&
!e.target.closest('.description-textarea')) {
const taskId = parseInt(taskItem.dataset.taskId);
this.selectTask(taskId);
}
});
}
// 入栈操作
push() {
const taskText = this.taskInput.value.trim();
if (!taskText) {
this.taskInput.focus();
this.showNotification('请输入任务标题', 'warning');
return;
}
if (taskText.length > 100) {
this.showNotification('任务标题不能超过100个字符', 'error');
return;
}
// 收集任务详情
const task = {
id: Date.now(),
title: taskText,
description: this.taskDescription.value.trim(),
deadline: this.taskDeadline.value || null,
priority: this.taskPriority.value,
url: this.taskUrl.value.trim() || null,
tags: this.getTagsFromInput(),
attachments: [...this.attachments],
progress: 0,
progressHistory: [],
timestamp: new Date(),
index: this.stack.length
};
this.stack.push(task);
this.todayTaskCount++;
// 清空输入
this.clearTaskInputs();
this.taskInput.focus();
this.updateUI();
this.saveToStorage();
this.showNotification(`任务 "${taskText}" 已入栈`, 'success');
}
// 出栈操作
pop() {
if (this.stack.length === 0) {
this.showNotification('栈为空,无法执行出栈操作', 'warning');
return;
}
const task = this.stack.pop();
this.completedTasks.push({
...task,
completedAt: new Date()
});
this.updateUI();
this.saveToStorage();
this.showNotification(`任务 "${task.title}" 已完成并出栈`, 'success');
// 添加完成动画
this.animateCompletion();
}
// 查看栈顶
peek() {
if (this.stack.length === 0) {
this.showNotification('栈为空,无栈顶元素', 'warning');
return;
}
const topTask = this.stack[this.stack.length - 1];
// 高亮栈顶任务
this.highlightTopTask();
// 自动展开栈顶任务的详情
const topTaskElement = this.taskStack.querySelector('.task-item:first-child');
if (topTaskElement) {
const taskId = topTask.id;
const detailsElement = document.getElementById(`details-${taskId}`);
const toggleButton = topTaskElement.querySelector('.expand-toggle');
if (detailsElement && !detailsElement.classList.contains('show')) {
// 展开详情
detailsElement.classList.add('show');
toggleButton.classList.add('expanded');
topTaskElement.classList.add('expanded');
// 滚动到栈顶任务
topTaskElement.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
this.showNotification(`已展开栈顶任务详情: "${topTask.title}"`, 'success');
} else if (detailsElement && detailsElement.classList.contains('show')) {
// 如果已经展开,则收起
detailsElement.classList.remove('show');
toggleButton.classList.remove('expanded');
topTaskElement.classList.remove('expanded');
this.showNotification(`已收起栈顶任务详情: "${topTask.title}"`, 'info');
}
}
}
// 清空栈
clear() {
if (this.stack.length === 0) {
this.showNotification('栈已经为空', 'warning');
return;
}
if (confirm(`确定要清空所有 ${this.stack.length} 个任务吗?此操作不可撤销。`)) {
this.stack = [];
this.updateUI();
this.saveToStorage();
this.showNotification('栈已清空', 'success');
}
}
// 更新 UI
updateUI() {
this.updateStackDisplay();
this.updateButtons();
this.updateStats();
this.updateHistoryDisplay();
}
// 更新栈显示
updateStackDisplay() {
this.taskStack.innerHTML = '';
if (this.stack.length === 0) {
this.taskStack.innerHTML = `
<div class="empty-stack">
<i class="fas fa-inbox"></i>
<p>栈为空</p>
<p class="hint">添加你的第一个任务开始使用!</p>
</div>
`;
return;
}
// 从栈顶到栈底显示任务
for (let i = this.stack.length - 1; i >= 0; i--) {
const task = this.stack[i];
// 传递显示位置索引(从0开始,0是栈顶)
const displayIndex = this.stack.length - 1 - i;
const taskElement = this.createTaskElement(task, displayIndex);
this.taskStack.appendChild(taskElement);
}
}
// 创建任务元素
createTaskElement(task, stackIndex) {
const taskDiv = document.createElement('div');
taskDiv.className = 'task-item';
taskDiv.dataset.taskId = task.id;
taskDiv.dataset.stackIndex = stackIndex;
const timeString = this.formatTime(task.timestamp);
// 处理旧版本任务数据兼容性
const title = task.title || task.content || '未命名任务';
const priority = task.priority || 'medium';
const tags = task.tags || [];
const deadline = task.deadline;
// 计算截止日期状态
const deadlineStatus = this.getDeadlineStatus(deadline);
const deadlineClass = deadlineStatus.class;
const deadlineText = deadlineStatus.text;
// 生成标签HTML
const tagsHtml = tags.length > 0
? `<div class="task-tags">
${tags.map(tag => `<span class="task-tag">${this.escapeHtml(tag)}</span>`).join('')}
</div>`
: '';
// 生成截止日期HTML
const deadlineHtml = deadline
? `<div class="task-deadline ${deadlineClass}">
<i class="fas fa-calendar-alt"></i>
${deadlineText}
</div>`
: '';
// 生成图片预览HTML
const imageAttachments = (task.attachments || []).filter(att => att.isImage && att.data);
const imagePreviewHtml = imageAttachments.length > 0
? `<div class="task-image-preview-container">
<div class="task-image-preview-grid">
${imageAttachments.slice(0, 3).map((attachment, index) => `
<div class="task-image-thumb" data-task-id="${task.id}" data-attachment-index="${index}" data-attachment-type="thumb">
<img src="${attachment.data}" alt="${this.escapeHtml(attachment.name)}" />
<div class="thumb-overlay">
<i class="fas fa-search-plus"></i>
</div>
</div>
`).join('')}
${imageAttachments.length > 3 ? `
<div class="task-image-more" data-action="toggle-details" data-task-id="${task.id}">
<span>+${imageAttachments.length - 3}</span>
<div class="more-text">更多</div>
</div>
` : ''}
</div>
</div>`
: '';
// 生成进度条HTML
const progressHtml = task.progress && task.progress > 0
? `<div class="task-progress-mini-container">
<div class="task-progress-mini">
<div class="task-progress-mini-fill" style="width: ${task.progress}%"></div>
<div class="task-progress-mini-text">${task.progress}%</div>
</div>
</div>`
: '';
// 生成状态指示器
const statusIndicators = this.generateStatusIndicators(task);
taskDiv.innerHTML = `
<div class="task-header">
<div class="task-title">
${this.escapeHtml(title)}
${statusIndicators}
</div>
<div class="task-priority ${priority}">
${this.getPriorityIcon(priority)} ${this.getPriorityText(priority)}
</div>
</div>
${deadlineHtml}
${tagsHtml}
${progressHtml}
${imagePreviewHtml}
<div class="task-meta">
<div class="task-meta-left">
<span class="task-index">#${this.stack.length - stackIndex}</span>
<span class="task-time">${timeString}</span>
</div>
<div class="task-meta-right">
${this.generateTaskStats(task)}
</div>
</div>
<button class="expand-toggle" data-task-id="${task.id}" data-action="toggle-details">
<i class="fas fa-chevron-down"></i>
</button>
<div class="task-details" id="details-${task.id}">
${this.generateTaskDetailsHtml(task)}
</div>
`;
// 添加拖拽事件
this.addDragEvents(taskDiv, stackIndex);
// 添加图片点击事件
this.addImageClickEvents(taskDiv, task);
return taskDiv;
}
// 更新按钮状态
updateButtons() {
const hasItems = this.stack.length > 0;
this.popBtn.disabled = !hasItems;
this.peekBtn.disabled = !hasItems;
this.clearBtn.disabled = !hasItems;
// 更新置顶按钮状态
const hasSelectedTask = this.selectedTaskId !== null;
const selectedTaskNotOnTop = hasSelectedTask && this.getSelectedTaskIndex() > 0;
this.pinSelectedBtn.disabled = !selectedTaskNotOnTop;
// 更新历史记录按钮状态
this.clearHistoryBtn.disabled = this.completedTasks.length === 0;
}
// 更新统计信息
updateStats() {
this.stackSize.textContent = this.stack.length;
this.totalTasks.textContent = this.stack.length;
this.completedTasksEl.textContent = this.completedTasks.length;
this.todayTasksEl.textContent = this.todayTaskCount;
}
// 高亮栈顶任务
highlightTopTask() {
const topTask = this.taskStack.querySelector('.task-item:first-child');
if (topTask) {
topTask.classList.add('peek-highlight');
setTimeout(() => {
topTask.classList.remove('peek-highlight');
}, 1000);
}
}
// 完成动画
animateCompletion() {
const topTask = this.taskStack.querySelector('.task-item:first-child');
if (topTask) {
topTask.style.animation = 'slideOutUp 0.5s ease';
setTimeout(() => {
this.updateStackDisplay();
}, 500);
}
}
// 显示通知
showNotification(message, type = 'info') {
// 移除已存在的通知
const existingNotification = document.querySelector('.notification');
if (existingNotification) {
existingNotification.remove();
}
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.innerHTML = `
<i class="fas fa-${this.getNotificationIcon(type)}"></i>
<span>${message}</span>
`;
// 添加样式
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: ${this.getNotificationColor(type)};
color: white;
padding: 15px 20px;
border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1001;
display: flex;
align-items: center;
gap: 10px;
animation: slideInRight 0.3s ease;
max-width: 300px;
font-weight: 500;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => {
notification.remove();
}, 300);
}, 3000);
}
getNotificationIcon(type) {
const icons = {
success: 'check-circle',
error: 'exclamation-circle',
warning: 'exclamation-triangle',
info: 'info-circle'
};
return icons[type] || 'info-circle';
}
getNotificationColor(type) {
const colors = {
success: '#28a745',
error: '#dc3545',
warning: '#ffc107',
info: '#17a2b8'
};
return colors[type] || '#17a2b8';
}
// 显示帮助
showHelp() {
this.helpModal.style.display = 'block';
document.body.style.overflow = 'hidden';
}
// 隐藏帮助
hideHelp() {
this.helpModal.style.display = 'none';
document.body.style.overflow = 'auto';
}
// 格式化时间
formatTime(date) {
// 确保 date 是一个有效的 Date 对象
let dateObj;
if (date instanceof Date) {
dateObj = date;
} else if (typeof date === 'string' || typeof date === 'number') {
dateObj = new Date(date);
} else {
// 如果无法转换,返回默认值
return '未知时间';
}
// 检查日期是否有效
if (isNaN(dateObj.getTime())) {
return '无效时间';
}
const now = new Date();
const diff = now - dateObj;
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes}分钟前`;
if (hours < 24) return `${hours}小时前`;
if (days < 7) return `${days}天前`;
return dateObj.toLocaleDateString('zh-CN', {
month: 'short',
day: 'numeric'
});
}
// HTML 转义
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 检查每日重置
checkDailyReset() {
const today = new Date().toDateString();
const lastDate = localStorage.getItem('todostack_last_date');
if (lastDate !== today) {
this.todayTaskCount = 0;
localStorage.setItem('todostack_last_date', today);
}
}
// 保存到本地存储
saveToStorage() {
const data = {
stack: this.stack,
completedTasks: this.completedTasks,
todayTaskCount: this.todayTaskCount,
lastUpdated: new Date().toISOString()
};
localStorage.setItem('todostack_data', JSON.stringify(data));
}
// 从本地存储加载
loadFromStorage() {
try {
const data = localStorage.getItem('todostack_data');
if (data) {
const parsed = JSON.parse(data);
this.stack = parsed.stack || [];
this.completedTasks = parsed.completedTasks || [];
this.todayTaskCount = parsed.todayTaskCount || 0;
// 转换时间戳为 Date 对象
this.stack.forEach(task => {
task.timestamp = new Date(task.timestamp);
// 转换进展记录的时间戳
if (task.progressHistory && Array.isArray(task.progressHistory)) {
task.progressHistory.forEach(entry => {
if (entry.timestamp) {
entry.timestamp = new Date(entry.timestamp);
}
});
}
});
this.completedTasks.forEach(task => {
task.timestamp = new Date(task.timestamp);
if (task.completedAt) {
task.completedAt = new Date(task.completedAt);
}
// 转换进展记录的时间戳
if (task.progressHistory && Array.isArray(task.progressHistory)) {
task.progressHistory.forEach(entry => {
if (entry.timestamp) {
entry.timestamp = new Date(entry.timestamp);
}
});
}
});
}
} catch (error) {
console.error('加载数据失败:', error);
this.showNotification('数据加载失败,使用默认设置', 'error');
}
}
// 导出数据
exportData() {
const data = {
stack: this.stack,
completedTasks: this.completedTasks,
exportDate: new Date().toISOString(),
version: '1.0'
};
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: 'application/json'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `todostack_backup_${new Date().toISOString().split('T')[0]}.json`;
a.click();
URL.revokeObjectURL(url);
this.showNotification('数据已导出', 'success');
}
// 导入数据
importData(file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = JSON.parse(e.target.result);
if (data.stack && Array.isArray(data.stack)) {
this.stack = data.stack;
this.completedTasks = data.completedTasks || [];
// 转换时间戳
this.stack.forEach(task => {
task.timestamp = new Date(task.timestamp);
// 转换进展记录的时间戳
if (task.progressHistory && Array.isArray(task.progressHistory)) {
task.progressHistory.forEach(entry => {
if (entry.timestamp) {
entry.timestamp = new Date(entry.timestamp);
}
});
}
});
this.completedTasks.forEach(task => {
task.timestamp = new Date(task.timestamp);
if (task.completedAt) {
task.completedAt = new Date(task.completedAt);
}
// 转换进展记录的时间戳
if (task.progressHistory && Array.isArray(task.progressHistory)) {
task.progressHistory.forEach(entry => {
if (entry.timestamp) {
entry.timestamp = new Date(entry.timestamp);
}
});
}
});
this.updateUI();
this.saveToStorage();
this.showNotification('数据导入成功', 'success');
} else {
throw new Error('数据格式错误');
}
} catch (error) {
console.error('导入失败:', error);
this.showNotification('数据导入失败,请检查文件格式', 'error');
}
};
reader.readAsText(file);
}
// 添加拖拽事件
addDragEvents(element, stackIndex) {
element.draggable = true;
element.addEventListener('dragstart', (e) => {
this.draggedElement = element;
this.draggedIndex = stackIndex;
element.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
});
element.addEventListener('dragend', (e) => {
element.classList.remove('dragging');
this.draggedElement = null;
this.draggedIndex = null;
// 移除所有拖拽高亮
document.querySelectorAll('.task-item').forEach(item => {
item.classList.remove('drag-over');
});
});
element.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (this.draggedElement && this.draggedElement !== element) {
element.classList.add('drag-over');
}
});
element.addEventListener('dragleave', (e) => {
element.classList.remove('drag-over');
});
element.addEventListener('drop', (e) => {
e.preventDefault();
element.classList.remove('drag-over');
if (this.draggedElement && this.draggedElement !== element) {
const targetIndex = parseInt(element.dataset.stackIndex);
this.reorderStack(this.draggedIndex, targetIndex);
}
});
}
// 重新排序栈
reorderStack(fromIndex, toIndex) {
if (fromIndex === toIndex) return;
console.log('拖拽排序 - 从位置:', fromIndex, '到位置:', toIndex);
console.log('栈长度:', this.stack.length);
// fromIndex和toIndex是显示位置索引(0是栈顶)
// 需要转换为数组中的实际索引
const actualFromIndex = this.stack.length - 1 - fromIndex;
const actualToIndex = this.stack.length - 1 - toIndex;
console.log('实际数组索引 - 从:', actualFromIndex, '到:', actualToIndex);
// 移动任务
const movedTask = this.stack.splice(actualFromIndex, 1)[0];
this.stack.splice(actualToIndex, 0, movedTask);
console.log('移动后的栈:', this.stack.map(t => t.title));
this.updateUI();
this.saveToStorage();
this.showNotification('任务顺序已调整', 'success');
}
// 切换历史记录显示
toggleHistory() {
this.historyVisible = !this.historyVisible;
if (this.historyVisible) {
this.historyContainer.style.display = 'block';
this.historyContainer.style.animation = 'historySlideDown 0.3s ease forwards';
this.toggleHistoryBtn.innerHTML = '<i class="fas fa-eye-slash"></i> 隐藏历史';
// 当显示历史记录时,立即更新显示
this.updateHistoryDisplay();
} else {
this.historyContainer.style.animation = 'historySlideUp 0.3s ease forwards';
setTimeout(() => {
this.historyContainer.style.display = 'none';
}, 300);
this.toggleHistoryBtn.innerHTML = '<i class="fas fa-eye"></i> 显示历史';
}
}
// 更新历史记录显示
updateHistoryDisplay() {
// 只有当历史记录容器存在时才更新
if (!this.historyList) return;
this.historyList.innerHTML = '';
if (this.completedTasks.length === 0) {
this.historyList.innerHTML = `
<div class="empty-history">
<i class="fas fa-clipboard-check"></i>
<p>暂无已完成任务</p>
<p class="hint">完成的任务会出现在这里</p>
</div>
`;
return;
}
// 按完成时间倒序显示
const sortedTasks = [...this.completedTasks].sort((a, b) =>
new Date(b.completedAt) - new Date(a.completedAt)
);
sortedTasks.forEach(task => {
const historyItem = this.createHistoryElement(task);
this.historyList.appendChild(historyItem);
});
}
// 创建历史记录元素
createHistoryElement(task) {
const historyDiv = document.createElement('div');
historyDiv.className = 'history-item';
const completedTime = this.formatTime(task.completedAt);
const originalTime = this.formatTime(task.timestamp);
// 处理旧版本任务数据兼容性
const title = task.title || task.content || '未命名任务';
const priority = task.priority || 'medium';
historyDiv.innerHTML = `
<div class="history-content">
<i class="fas fa-check-circle check-icon"></i>
<div class="history-task-info">
<span class="history-text">${this.escapeHtml(title)}</span>
<span class="history-priority ${priority}">
${this.getPriorityIcon(priority)} ${this.getPriorityText(priority)}
</span>
</div>
</div>
<div class="history-actions">
<button class="history-undo-btn" data-task-id="${task.id}" data-action="undo-complete" title="撤销完成">
<i class="fas fa-undo"></i>
</button>
</div>
<div class="history-meta">
<span class="history-completed-time">完成于 ${completedTime}</span>
<span class="history-original-time">创建于 ${originalTime}</span>
</div>
`;
return historyDiv;
}
// 撤销完成任务
undoComplete(taskId) {
// 确保taskId是数字类型
const numericTaskId = parseInt(taskId);
const taskIndex = this.completedTasks.findIndex(task => task.id === numericTaskId);
if (taskIndex === -1) {
this.showNotification('任务未找到', 'error');
console.error('撤销失败 - 任务ID:', taskId, '已完成任务列表:', this.completedTasks);
return;
}
const task = this.completedTasks[taskIndex];
// 从已完成任务中移除
this.completedTasks.splice(taskIndex, 1);
// 移除完成时间戳,恢复为未完成状态
delete task.completedAt;
// 重新添加到栈顶(最后一个位置,因为栈是LIFO)
this.stack.push(task);
this.updateUI();
this.saveToStorage();
this.showNotification(`任务"${task.title || task.content || '未命名任务'}"已恢复到待完成状态`, 'success');
}
// 清空历史记录
clearHistory() {
if (this.completedTasks.length === 0) {
this.showNotification('历史记录已经为空', 'warning');
return;
}
if (confirm(`确定要清空所有 ${this.completedTasks.length} 条历史记录吗?此操作不可撤销。`)) {
this.completedTasks = [];
this.updateUI();
this.saveToStorage();
this.showNotification('历史记录已清空', 'success');
}
}
// ===== 进展管理功能方法 =====
// 添加任务进展记录
addTaskProgress(taskId) {
const task = this.stack.find(t => t.id === taskId);
if (!task) {
this.showNotification('任务未找到', 'error');
return;
}
const inputElement = document.querySelector(`.task-progress-input[data-task-id="${taskId}"]`);
const progressText = inputElement ? inputElement.value.trim() : '';
if (!progressText) {
this.showNotification('请输入进展内容', 'warning');
if (inputElement) inputElement.focus();
return;
}
// 添加进展记录
if (!task.progressHistory) {
task.progressHistory = [];
}
const progressEntry = {
id: Date.now(),
text: progressText,