-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
730 lines (601 loc) · 26 KB
/
script.js
File metadata and controls
730 lines (601 loc) · 26 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
// --- Variáveis Globais ---
let tarefas = [];
let idAtual = 0;
let filtroCategoriaAtual = "todos";
let tarefaSendoEditadaId = null;
let tarefaArrastadaId = null; // Para Drag & Drop
// --- Referências DOM ---
const form = document.getElementById("task-form");
const inputNome = document.getElementById("task-name");
const selectPrioridade = document.getElementById("task-priority");
const selectCategoria = document.getElementById("task-category");
const filterCategorySelect = document.getElementById("filter-category");
const pendingTasksContainer = document.getElementById("pending-tasks");
const archivedTasksContainer = document.getElementById("archived-tasks");
const noPendingTasksMessage = document.getElementById("no-pending-tasks-message");
const noArchivedTasksMessage = document.getElementById("no-archived-tasks-message");
const themeToggleBtn = document.getElementById("theme-toggle");
const backButton = document.getElementById("back-button");
const editTaskModal = document.getElementById("edit-task-modal");
const editTaskForm = document.getElementById("edit-task-form");
const editTaskNameInput = document.getElementById("edit-task-name");
const editTaskPrioritySelect = document.getElementById("edit-task-priority");
const editTaskCategorySelect = document.getElementById("edit-task-category");
const editTaskReminderDatetimeInput = document.getElementById("edit-task-reminder-datetime");
const cancelEditButton = document.getElementById("cancel-edit-button");
const exportTxtButton = document.getElementById("export-txt-button");
const exportJsonButton = document.getElementById("export-json-button");
// Referências DOM para o novo modal de mensagem
const messageModal = document.getElementById("message-modal");
const messageModalTitle = document.getElementById("message-modal-title");
const messageModalText = document.getElementById("message-modal-text");
const messageModalOkButton = document.getElementById("message-modal-ok-button");
const notificationTimeouts = {};
// --- Funções Auxiliares de UI (para substituir alert/confirm) ---
function showMessageBox(title, message, callback = () => {}) {
messageModalTitle.textContent = title;
messageModalText.textContent = message;
messageModal.classList.add("visible");
// Limpa qualquer listener anterior para evitar múltiplos disparos
messageModalOkButton.onclick = null;
messageModalOkButton.onclick = () => {
messageModal.classList.remove("visible");
callback();
};
}
function showConfirmBox(title, message, onConfirm, onCancel = () => {}) {
// Reutiliza o modal de mensagem, mas adiciona um botão de cancelar e ajusta o OK
messageModalTitle.textContent = title;
messageModalText.textContent = message;
messageModal.classList.add("visible");
// Cria um botão de cancelar temporário
let cancelButton = document.createElement('button');
cancelButton.textContent = 'Cancelar';
cancelButton.classList.add('modal-cancel-button'); // Use sua classe de botão cancelar
cancelButton.onclick = () => {
messageModal.classList.remove("visible");
onCancel();
cancelButton.remove(); // Remove o botão após o uso
};
// Adiciona o botão de cancelar antes do botão OK
messageModalOkButton.parentNode.insertBefore(cancelButton, messageModalOkButton);
// Ajusta o botão OK para a ação de confirmação
messageModalOkButton.textContent = 'Confirmar'; // Muda o texto para "Confirmar"
messageModalOkButton.onclick = () => {
messageModal.classList.remove("visible");
onConfirm();
cancelButton.remove(); // Remove o botão de cancelar
messageModalOkButton.textContent = 'OK'; // Volta o texto do botão OK para o padrão
};
}
// --- Funções de Persistência (localStorage) ---
function carregarTarefas() {
const tarefasSalvas = localStorage.getItem("tarefas");
if (tarefasSalvas) {
tarefas = JSON.parse(tarefasSalvas);
idAtual = tarefas.length > 0 ? Math.max(...tarefas.map(t => t.id)) + 1 : 0;
tarefas.forEach(tarefa => {
// Garante que o contador de pomodoros existe
if (typeof tarefa.pomodorosCompletos === 'undefined') {
tarefa.pomodorosCompletos = 0;
}
if (tarefa.lembreteAgendado && !tarefa.concluida && !tarefa.arquivada) {
const agora = Date.now();
if (tarefa.lembreteAgendado > agora) {
const tempoRestante = tarefa.lembreteAgendado - agora;
agendarNotificacaoReal(tarefa.id, tarefa.nome, tempoRestante);
} else {
tarefa.lembreteAgendado = null;
}
}
});
}
}
function salvarTarefas() {
localStorage.setItem("tarefas", JSON.stringify(tarefas));
}
// --- Funções de Tema ---
function aplicarTema(isDarkMode) {
if (isDarkMode) {
document.body.classList.add("dark-mode");
} else {
document.body.classList.remove("dark-mode");
}
}
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
aplicarTema(true);
} else {
aplicarTema(false);
}
themeToggleBtn.addEventListener("click", () => {
const isCurrentlyDarkMode = document.body.classList.contains("dark-mode");
aplicarTema(!isCurrentlyDarkMode);
if (!isCurrentlyDarkMode) {
localStorage.setItem("theme", "dark");
} else {
localStorage.setItem("theme", "light");
}
});
// --- Permissão de Notificação ---
function solicitarPermissaoNotificacao() {
if (!("Notification" in window)) {
console.warn("Este navegador não suporta notificações de desktop.");
return Promise.resolve("unsupported");
}
if (Notification.permission === "granted") {
return Promise.resolve("granted");
}
if (Notification.permission === "denied") {
return Promise.resolve("denied");
}
return Notification.requestPermission();
}
// --- Event Listeners Principais ---
document.addEventListener("DOMContentLoaded", () => {
carregarTarefas();
renderizarTarefas();
setupDragAndDrop();
solicitarPermissaoNotificacao();
// Event Listener para o botão de voltar - MOVIDO PARA AQUI
if (backButton) {
backButton.addEventListener("click", () => {
history.back(); // Esta função do navegador faz a página voltar na história
});
}
});
form.addEventListener("submit", function (e) {
e.preventDefault();
const nome = inputNome.value.trim();
const prioridade = selectPrioridade.value;
const categoria = selectCategoria.value;
if (nome === "") {
showMessageBox("Erro", "O nome da tarefa não pode ser vazio!");
return;
}
const novaTarefa = {
id: idAtual++,
nome,
prioridade,
categoria,
concluida: false,
arquivada: false,
lembreteAgendado: null,
pomodorosCompletos: 0
};
tarefas.push(novaTarefa);
inputNome.value = "";
selectPrioridade.value = "baixa";
selectCategoria.value = "todos";
salvarTarefas();
renderizarTarefas();
});
filterCategorySelect.addEventListener("change", function () {
filtroCategoriaAtual = this.value;
renderizarTarefas();
});
exportTxtButton.addEventListener("click", exportarTarefasTxt);
exportJsonButton.addEventListener("click", exportarTarefasJson);
// --- Funções de Renderização e Lógica de Tarefas ---
function renderizarTarefas() {
pendingTasksContainer.innerHTML = "";
archivedTasksContainer.innerHTML = "";
noPendingTasksMessage.classList.add("hidden");
noArchivedTasksMessage.classList.add("hidden");
const pendingTasks = tarefas.filter(t => !t.arquivada && (filtroCategoriaAtual === "todos" || t.categoria === filtroCategoriaAtual));
const archivedTasks = tarefas.filter(t => t.arquivada && (filtroCategoriaAtual === "todos" || t.categoria === filtroCategoriaAtual));
pendingTasks.forEach((tarefa) => {
const div = criarElementoTarefa(tarefa);
pendingTasksContainer.appendChild(div);
// Garante que os ícones Lucide sejam criados dentro da nova tarefa
lucide.createIcons({ container: div });
});
archivedTasks.forEach((tarefa) => {
const div = criarElementoTarefa(tarefa);
archivedTasksContainer.appendChild(div);
// Garante que os ícones Lucide sejam criados dentro da nova tarefa
lucide.createIcons({ container: div });
});
if (pendingTasks.length === 0) {
noPendingTasksMessage.classList.remove("hidden");
}
if (archivedTasks.length === 0) {
noArchivedTasksMessage.classList.remove("hidden");
}
configurarDragAndDropContainers();
}
function criarElementoTarefa(tarefa) {
const div = document.createElement("div");
div.className = `task prioridade-${tarefa.prioridade}`;
div.dataset.id = tarefa.id;
div.setAttribute('draggable', 'true');
div.addEventListener('dragstart', (e) => {
tarefaArrastadaId = tarefa.id;
e.dataTransfer.setData('text/plain', tarefa.id);
div.classList.add('dragging');
});
div.addEventListener('dragend', () => {
div.classList.remove('dragging');
tarefaArrastadaId = null;
});
div.addEventListener('dragover', (e) => {
e.preventDefault();
const draggingElement = document.querySelector('.dragging');
if (!draggingElement || draggingElement === div) return;
const bounding = div.getBoundingClientRect();
const offset = bounding.y + (bounding.height / 2);
if (e.clientY < offset) {
div.classList.add('drag-over-top');
div.classList.remove('drag-over-bottom');
} else {
div.classList.add('drag-over-bottom');
div.classList.remove('drag-over-top');
}
});
div.addEventListener('dragleave', () => {
div.classList.remove('drag-over-top', 'drag-over-bottom');
});
div.addEventListener('drop', (e) => {
e.preventDefault();
div.classList.remove('drag-over-top', 'drag-over-bottom');
const draggedId = parseInt(e.dataTransfer.getData('text/plain'));
if (isNaN(draggedId) || draggedId === tarefa.id) return;
reordenarTarefas(draggedId, tarefa.id, div.classList.contains('drag-over-bottom'));
});
const nomeSpan = document.createElement("span");
const strongNome = document.createElement("strong");
strongNome.textContent = tarefa.nome;
const priorityBadge = document.createElement("span");
priorityBadge.className = `task-priority-badge prioridade-${tarefa.prioridade}`;
let priorityText = "";
switch (tarefa.prioridade) {
case "baixa": priorityText = "Baixa"; break;
case "média": priorityText = "Média"; break;
case "alta": priorityText = "Alta"; break;
default: priorityText = tarefa.prioridade;
}
priorityBadge.textContent = priorityText;
const categoryBadge = document.createElement("span");
categoryBadge.className = `task-category-badge categoria-${tarefa.categoria}`;
const categoryDisplayText = tarefa.categoria.charAt(0).toUpperCase() + tarefa.categoria.slice(1);
categoryBadge.textContent = categoryDisplayText;
nomeSpan.appendChild(strongNome);
nomeSpan.appendChild(priorityBadge);
nomeSpan.appendChild(categoryBadge);
const btnConcluirOuDesarquivar = document.createElement("button");
btnConcluirOuDesarquivar.classList.add("btn-concluir"); // Adicionando a classe base
if (tarefa.arquivada) {
btnConcluirOuDesarquivar.innerHTML = `
<span data-lucide="folder-open" class="lucide-icon"></span>
<span class="button-text-hidden">Desarquivar</span>
`;
btnConcluirOuDesarquivar.onclick = () => desarquivarTarefa(tarefa.id);
} else {
btnConcluirOuDesarquivar.innerHTML = `
<span data-lucide="check-circle" class="lucide-icon"></span>
<span class="button-text-hidden">Concluir</span>
`;
btnConcluirOuDesarquivar.onclick = () => concluirTarefa(tarefa.id);
}
const btnEditar = document.createElement("button");
btnEditar.classList.add("btn-editar"); // Adicionando a classe base
btnEditar.innerHTML = `
<span data-lucide="pencil" class="lucide-icon"></span>
<span class="button-text-hidden">Editar</span>
`;
btnEditar.onclick = () => abrirModalEdicao(tarefa.id);
if (tarefa.arquivada) {
btnEditar.disabled = true;
btnEditar.style.opacity = 0.5;
btnEditar.style.cursor = 'not-allowed';
}
const btnExcluir = document.createElement("button");
btnExcluir.classList.add("btn-excluir"); // Adicionando a classe base
btnExcluir.innerHTML = `
<span data-lucide="trash-2" class="lucide-icon"></span>
<span class="button-text-hidden">Excluir</span>
`;
btnExcluir.onclick = () => showConfirmBox(
"Confirmar Exclusão",
`Tem certeza que deseja excluir a tarefa "${tarefa.nome}"?`,
() => removerTarefa(tarefa.id, div)
);
// ADIÇÃO AQUI: Adicionar uma classe específica para o botão de exclusão de alta prioridade
if (tarefa.prioridade === 'alta') {
btnExcluir.classList.add("btn-excluir-critico"); // Nova classe
}
const pomodoroElement = document.createElement("span");
if (!tarefa.arquivada) {
if (tarefa.pomodorosCompletos > 0) {
pomodoroElement.className = "pomodoro-counter";
pomodoroElement.textContent = `Pomodoros: ${tarefa.pomodorosCompletos}`;
}
const btnPomodoro = document.createElement("button");
btnPomodoro.classList.add("pomodoro-button"); // Adicionando a classe base
btnPomodoro.innerHTML = `
<span data-lucide="timer" class="lucide-icon"></span>
<span class="button-text-hidden">Pomodoro Concluído</span>
`;
btnPomodoro.onclick = () => {
showConfirmBox(
"Marcar Pomodoro",
`Marcar um Pomodoro concluído para "${tarefa.nome}"?`,
() => {
tarefa.pomodorosCompletos = (tarefa.pomodorosCompletos || 0) + 1;
salvarTarefas();
renderizarTarefas();
}
);
};
div.appendChild(btnPomodoro);
if (tarefa.pomodorosCompletos > 0) {
div.appendChild(pomodoroElement);
}
}
div.appendChild(nomeSpan);
const actionsContainer = document.createElement('div');
actionsContainer.className = 'task-actions';
actionsContainer.appendChild(btnConcluirOuDesarquivar);
actionsContainer.appendChild(btnEditar);
// Reorganiza a adição dos botões e contadores de pomodoro
const existingBtnPomodoro = div.querySelector('.pomodoro-button');
if (existingBtnPomodoro) actionsContainer.appendChild(existingBtnPomodoro);
const existingPomodoroCounterSpan = div.querySelector('.pomodoro-counter');
if (existingPomodoroCounterSpan) actionsContainer.appendChild(existingPomodoroCounterSpan);
actionsContainer.appendChild(btnExcluir);
div.appendChild(actionsContainer);
return div;
}
function removerTarefa(id, element) {
element.classList.add('hide');
element.addEventListener('transitionend', function handler() {
element.remove();
tarefas = tarefas.filter((t) => t.id !== id);
cancelarLembrete(id, false);
salvarTarefas();
renderizarTarefas();
});
}
function concluirTarefa(id) {
const tarefa = tarefas.find((t) => t.id === id);
if (tarefa && !tarefa.concluida) {
tarefa.concluida = true;
tarefa.arquivada = true;
cancelarLembrete(id, false);
salvarTarefas();
renderizarTarefas();
}
}
function desarquivarTarefa(id) {
const tarefa = tarefas.find((t) => t.id === id);
if (tarefa && tarefa.arquivada) {
tarefa.concluida = false;
tarefa.arquivada = false;
salvarTarefas();
renderizarTarefas();
}
}
// --- Funções do Modal de Edição ---
function abrirModalEdicao(id) {
const tarefa = tarefas.find((t) => t.id === id);
if (!tarefa || tarefa.arquivada) {
showMessageBox("Edição Não Permitida", "Você não pode editar tarefas arquivadas. Por favor, desarquive-a primeiro.");
return;
}
tarefaSendoEditadaId = id;
editTaskNameInput.value = tarefa.nome;
editTaskPrioritySelect.value = tarefa.prioridade;
editTaskCategorySelect.value = tarefa.categoria;
if (tarefa.lembreteAgendado) {
const date = new Date(tarefa.lembreteAgendado);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
editTaskReminderDatetimeInput.value = `${year}-${month}-${day}T${hours}:${minutes}`;
} else {
editTaskReminderDatetimeInput.value = "";
}
editTaskModal.classList.add("visible");
}
function fecharModalEdicao() {
editTaskModal.classList.remove("visible");
tarefaSendoEditadaId = null;
}
cancelEditButton.addEventListener("click", fecharModalEdicao);
editTaskForm.addEventListener("submit", function (e) {
e.preventDefault();
const tarefa = tarefas.find((t) => t.id === tarefaSendoEditadaId);
if (!tarefa) return;
const novoNome = editTaskNameInput.value.trim();
const novaPrioridade = editTaskPrioritySelect.value;
const novaCategoria = editTaskCategorySelect.value;
const novoLembreteDatetime = editTaskReminderDatetimeInput.value;
if (novoNome === "") {
showMessageBox("Erro", "O nome da tarefa não pode ser vazio!");
return;
}
tarefa.nome = novoNome;
tarefa.prioridade = novaPrioridade;
tarefa.categoria = novaCategoria;
if (novoLembreteDatetime) {
const dataLembrete = new Date(novoLembreteDatetime).getTime();
const agora = Date.now();
if (dataLembrete <= agora) {
showMessageBox("Erro de Lembrete", "A data/hora do lembrete deve ser no futuro. Lembrete não agendado.");
tarefa.lembreteAgendado = null;
cancelarLembrete(tarefa.id, false);
} else {
tarefa.lembreteAgendado = dataLembrete;
agendarNotificacaoReal(tarefa.id, tarefa.nome, dataLembrete - agora);
}
} else {
tarefa.lembreteAgendado = null;
cancelarLembrete(tarefa.id, false);
}
salvarTarefas();
renderizarTarefas();
fecharModalEdicao();
});
// --- Funções de Notificação ---
function agendarNotificacaoReal(id, nomeTarefa, tempoParaNotificarMs) {
if (Notification.permission !== "granted") {
console.warn(`Permissão de notificação não concedida. Não é possível agendar lembrete para ${nomeTarefa}.`);
return;
}
if (notificationTimeouts[id]) {
clearTimeout(notificationTimeouts[id]);
}
notificationTimeouts[id] = setTimeout(() => {
new Notification("Lembrete de Tarefa", {
body: `Não se esqueça de: "${nomeTarefa}"`,
icon: 'icon.png' // Certifique-se de ter um arquivo icon.png ou ajuste o caminho
});
delete notificationTimeouts[id];
const tarefa = tarefas.find(t => t.id === id);
if (tarefa) {
tarefa.lembreteAgendado = null;
salvarTarefas();
renderizarTarefas();
}
}, tempoParaNotificarMs);
console.log(`Lembrete agendado para "${nomeTarefa}" em ${tempoParaNotificarMs / 1000} segundos.`);
}
function cancelarLembrete(id, shouldRender = true) {
const tarefa = tarefas.find(t => t.id === id);
if (!tarefa) return;
if (notificationTimeouts[id]) {
clearTimeout(notificationTimeouts[id]);
delete notificationTimeouts[id];
tarefa.lembreteAgendado = null;
salvarTarefas();
if (shouldRender) {
renderizarTarefas();
}
console.log(`Lembrete para "${tarefa.nome}" cancelado.`);
} else {
console.log("Não há lembrete agendado para esta tarefa.");
}
}
// --- Funções de Exportação ---
function downloadFile(filename, text, type) {
const element = document.createElement('a');
element.setAttribute('href', `data:${type};charset=utf-8,${encodeURIComponent(text)}`);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function exportarTarefasTxt() {
if (tarefas.length === 0) {
showMessageBox("Aviso", "Não há tarefas para exportar.");
return;
}
let textContent = "Lista de Tarefas:\n\n";
const pendentes = tarefas.filter(t => !t.arquivada);
const arquivadas = tarefas.filter(t => t.arquivada);
textContent += "--- Tarefas Pendentes ---\n";
if (pendentes.length > 0) {
pendentes.forEach((tarefa, index) => {
const lembreteInfo = tarefa.lembreteAgendado ?
` (Lembrete: ${new Date(tarefa.lembreteAgendado).toLocaleString()})` : '';
const pomodoroInfo = tarefa.pomodorosCompletos > 0 ?
` (Pomodoros: ${tarefa.pomodorosCompletos})` : '';
textContent += `${index + 1}. [${tarefa.prioridade.toUpperCase()}] [${tarefa.categoria.toUpperCase()}] ${tarefa.nome}${lembreteInfo}${pomodoroInfo}\n`;
});
} else {
textContent += "Nenhuma tarefa pendente.\n";
}
textContent += "\n--- Histórico de Tarefas (Concluídas) ---\n";
if (arquivadas.length > 0) {
arquivadas.forEach((tarefa, index) => {
const lembreteInfo = tarefa.lembreteAgendado ?
` (Lembrete Original: ${new Date(tarefa.lembreteAgendado).toLocaleString()})` : '';
const pomodoroInfo = tarefa.pomodorosCompletos > 0 ?
` (Pomodoros: ${tarefa.pomodorosCompletos})` : '';
textContent += `${index + 1}. [CONCLUÍDA] [${tarefa.prioridade.toUpperCase()}] [${tarefa.categoria.toUpperCase()}] ${tarefa.nome}${lembreteInfo}${pomodoroInfo}\n`;
});
} else {
textContent += "Nenhuma tarefa arquivada.\n";
}
downloadFile("minhas_tarefas.txt", textContent, "text/plain");
showMessageBox("Sucesso", "Tarefas exportadas como minhas_tarefas.txt!");
}
function exportarTarefasJson() {
if (tarefas.length === 0) {
showMessageBox("Aviso", "Não há tarefas para exportar.");
return;
}
const jsonContent = JSON.stringify(tarefas, null, 2);
downloadFile("minhas_tarefas.json", jsonContent, "application/json");
showMessageBox("Sucesso", "Tarefas exportadas como minhas_tarefas.json!");
}
// --- Funções de Drag & Drop ---
function setupDragAndDrop() { // Renomeado para evitar conflito com o nome da variável
configurarDragAndDropContainers();
}
function configurarDragAndDropContainers() {
[pendingTasksContainer, archivedTasksContainer].forEach(container => {
container.addEventListener('dragover', (e) => {
e.preventDefault();
const draggingElement = document.querySelector('.dragging');
if (draggingElement && !container.contains(draggingElement)) {
container.classList.add('drag-over-container');
}
});
container.addEventListener('dragleave', (e) => {
if (!container.contains(e.relatedTarget)) {
container.classList.remove('drag-over-container');
}
});
container.addEventListener('drop', (e) => {
e.preventDefault();
container.classList.remove('drag-over-container');
const draggedId = parseInt(e.dataTransfer.getData('text/plain'));
if (isNaN(draggedId)) return;
const draggedTask = tarefas.find(t => t.id === draggedId);
if (!draggedTask) return;
const isArchivedTarget = container.id === 'archived-tasks';
if (isArchivedTarget && !draggedTask.arquivada) {
draggedTask.arquivada = true;
draggedTask.concluida = true;
cancelarLembrete(draggedId, false);
salvarTarefas();
renderizarTarefas();
} else if (!isArchivedTarget && draggedTask.arquivada) {
draggedTask.arquivada = false;
draggedTask.concluida = false;
salvarTarefas();
renderizarTarefas();
} else if (!isArchivedTarget && !draggedTask.arquivada) {
salvarTarefas();
renderizarTarefas();
}
});
});
}
function reordenarTarefas(draggedId, targetId, insertAfter) {
const draggedIndex = tarefas.findIndex(t => t.id === draggedId);
const targetIndex = tarefas.findIndex(t => t.id === targetId);
if (draggedIndex === -1 || targetIndex === -1) return;
const [draggedTask] = tarefas.splice(draggedIndex, 1);
let insertIndex = targetIndex;
if (insertAfter) {
if (draggedIndex < targetIndex) {
insertIndex = targetIndex;
} else {
insertIndex = targetIndex + 1;
}
} else {
if (draggedIndex > targetIndex) {
insertIndex = targetIndex;
} else {
insertIndex = targetIndex;
}
}
tarefas.splice(insertIndex, 0, draggedTask);
salvarTarefas();
renderizarTarefas();
}