-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
456 lines (384 loc) · 13.3 KB
/
script.js
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
const $modal = document.getElementById('modal');
const $descriptionInput = document.getElementById('description');
const $tagsInput = document.getElementById('tags');
const $deadlineInput = document.getElementById('deadline');
const $idInput = document.getElementById('idInput');
const $creationModeTitle = document.getElementById('creationModeTitle');
const $editingModeTitle = document.getElementById('editingModeTitle');
const $creationModeBtn = document.getElementById('creationModeBtn');
const $editingModeBtn = document.getElementById('editingModeBtn');
// Usuários
class App {
constructor() {
this.$users = document.querySelector('#users');
this.selectedUserId = this.loadSelectedUserId(); // Carrega o ID do usuário selecionado do localStorage
this.users = this.loadUsers() || []; // Carrega a lista de usuários do localStorage ou inicializa uma vazia
this.fetchUsers();
}
async fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users'); // API de exemplo para usuários
if (!response.ok) {
throw new Error(`Erro na resposta da API: ${response.status} ${response.statusText}`);
}
const users = await response.json();
if (users.length === 0) {
throw new Error('Nenhum usuário encontrado.');
}
// Limitar a 4 usuários e adicionar uma URL de foto fictícia e tarefas fictícias
this.users = users.slice(0, 4).map(user => ({
...user,
photoUrl: `https://i.pravatar.cc/150?img=${user.id}`, // API de exemplo para fotos
tasks: this.loadTasksForUser(user.id) || [] // Carrega tarefas do localStorage
}));
// Define um usuário padrão como selecionado se não houver no localStorage
if (!this.selectedUserId) {
this.selectedUserId = this.users[0].id;
}
this.renderUsers();
this.renderTasks();
updateTaskCount();
} catch (error) {
console.error('Erro ao buscar usuários:', error);
}
}
saveUsers() {
localStorage.setItem('kanbanUsers', JSON.stringify(this.users));
}
loadUsers() {
return JSON.parse(localStorage.getItem('kanbanUsers'));
}
saveSelectedUserId() {
localStorage.setItem('selectedUserId', this.selectedUserId);
}
loadSelectedUserId() {
return parseInt(localStorage.getItem('selectedUserId'));
}
saveTasksForUser(userId) {
const user = this.users.find(user => user.id === userId);
if (user) {
localStorage.setItem(`tasks_${userId}`, JSON.stringify(user.tasks));
}
}
loadTasksForUser(userId) {
return JSON.parse(localStorage.getItem(`tasks_${userId}`));
}
renderUsers() {
const userListContainer = document.getElementById('user-list');
const html = this.users
.map((user) => {
const selectedClass = user.id === this.selectedUserId ? 'selected' : '';
return `
<div class="user-card ${selectedClass}" data-user-id="${user.id}">
<img src="${user.photoUrl}" alt="Foto de ${user.name}" />
</div>
`;
})
.join('');
userListContainer.innerHTML = html;
// Adicionar evento de clique a cada cartão de usuário
document.querySelectorAll('.user-card').forEach(card => {
card.addEventListener('click', (event) => {
const userId = event.currentTarget.getAttribute('data-user-id');
this.selectedUserId = parseInt(userId, 10);
this.saveSelectedUserId(); // Salva o usuário selecionado no localStorage
this.renderUsers();
this.renderTasks();
updateTaskCount();
});
});
}
renderTasks() {
const user = this.users.find(user => user.id === this.selectedUserId);
const taskListContainer = document.querySelectorAll('.cards_list');
if (user) {
taskListContainer.forEach(container => container.innerHTML = ''); // Limpar todas as colunas
user.tasks.forEach(task => {
const formattedDate = moment(task.deadline).format('DD/MM/YYYY');
const columnBody = document.querySelector(`[data-column="${task.column}"] .body .cards_list`);
if (!columnBody) return;
let cardClass = '';
switch (task.column) {
case 1:
cardClass = 'todo';
break;
case 2:
cardClass = 'in-progress';
break;
case 3:
cardClass = 'completed';
break;
}
const card = `
<div
id="${task.id}"
class="card ${cardClass}"
ondblclick="openModalToEdit(${task.id})"
draggable="true"
ondragstart="dragstart_handler(event)"
>
<div class="info">
<b>Atividade:</b>
<span>${task.description}</span>
</div>
<div class="info">
<b>Setor:</b>
<span>${task.tags}</span>
</div>
<div class="info">
<b>Prazo:</b>
<span>${formattedDate}</span>
</div>
<button class="material-symbols-outlined" onclick="deleteTask(${task.id})">delete</button>
</div>
`;
columnBody.innerHTML += card;
});
this.saveTasksForUser(this.selectedUserId);
updateTaskCount();
}
}
addTask(taskTitle, taskTags, taskDeadline) {
const user = this.users.find(user => user.id === this.selectedUserId);
if (user) {
const newTask = {
id: Math.floor(Math.random() * 9999999),
description: taskTitle,
tags: taskTags,
deadline: taskDeadline,
column: 1
};
user.tasks.push(newTask);
this.renderTasks();
this.saveTasksForUser(this.selectedUserId);
updateTaskCount();
}
}
updateTask(taskId, taskTitle, taskTags, taskDeadline) {
const user = this.users.find(user => user.id === this.selectedUserId);
if (user) {
const index = user.tasks.findIndex(task => task.id == taskId);
if (index === -1) {
console.error("Erro: Tarefa não encontrada para atualização.");
return;
}
const existingTask = user.tasks[index];
const updatedTask = {
id: existingTask.id,
description: taskTitle,
tags: taskTags,
deadline: taskDeadline,
column: existingTask.column
};
user.tasks[index] = updatedTask;
this.renderTasks();
this.saveTasksForUser(this.selectedUserId);
updateTaskCount();
}
}
}
// Funções de Manipulação de Modal
function openModal() {
$modal.style.display = 'flex';
$creationModeTitle.style.display = 'block';
$creationModeBtn.style.display = 'block';
$editingModeTitle.style.display = 'none';
$editingModeBtn.style.display = 'none';
}
function closeModal() {
$modal.style.display = 'none';
$idInput.value = '';
$descriptionInput.value = '';
$tagsInput.value = '';
$deadlineInput.value = '';
}
function openModalToEdit(id) {
$modal.style.display = "flex";
$creationModeTitle.style.display = "none";
$creationModeBtn.style.display = "none";
$editingModeTitle.style.display = "block";
$editingModeBtn.style.display = "block";
const user = app.users.find(user => user.id === app.selectedUserId);
if (user) {
const task = user.tasks.find(task => task.id == id);
if (task) {
$idInput.value = task.id;
$descriptionInput.value = task.description;
$tagsInput.value = task.tags;
$deadlineInput.value = task.deadline;
}
}
}
function createTask() {
const taskTitle = $descriptionInput.value;
const taskTags = $tagsInput.value;
const taskDeadline = $deadlineInput.value;
app.addTask(taskTitle, taskTags, taskDeadline);
updateTaskCount();
closeModal();
}
function deleteTask(taskId) {
const user = app.users.find(user => user.id === app.selectedUserId);
if (user) {
user.tasks = user.tasks.filter(task => task.id !== taskId);
app.renderTasks();
app.saveUsers();
updateTaskCount();
}
}
function updateTask() {
const taskId = $idInput.value;
const taskTitle = $descriptionInput.value;
const taskTags = $tagsInput.value;
const taskDeadline = $deadlineInput.value;
app.updateTask(taskId, taskTitle, taskTags, taskDeadline);
updateTaskCount();
closeModal();
}
let selectedTag = 'all';
function filterTasks(tag) {
// Alterna a tag selecionada entre 'all' e a tag clicada
if (selectedTag === tag) {
selectedTag = 'all'; // Se clicar na mesma tag novamente, volta para 'Todos'
} else {
selectedTag = tag;
}
renderFilteredTasks();
updateTagStyles();
}
function updateTagStyles() {
const tags = document.querySelectorAll('.tag');
tags.forEach(tag => {
tag.classList.remove('selected');
// Verifica a tag atual e aplica a cor correta
if (tag.textContent.trim() === 'Todos' && selectedTag === 'all') {
tag.classList.add('selected');
tag.style.backgroundColor = '#DE8200';
tag.style.color = '#FFF';
} else if (tag.textContent.trim().toLowerCase() === selectedTag) {
tag.classList.add('selected');
tag.style.backgroundColor = '#de9f47';
tag.style.color = '#FFF';
} else {
// Reseta o estilo para as tags não selecionadas
tag.style.backgroundColor = '#F5F5F5';
tag.style.color = '#757575';
}
});
}
function renderFilteredTasks() {
const user = app.users.find(user => user.id === app.selectedUserId);
const taskListContainers = document.querySelectorAll('.cards_list');
if (user) {
taskListContainers.forEach(container => container.innerHTML = '');
// Percorre as tarefas do usuário
user.tasks.forEach(task => {
if (selectedTag === 'all' || task.tags.includes(selectedTag)) {
const formattedDate = moment(task.deadline).format('DD/MM/YYYY');
const columnBody = document.querySelector(`[data-column="${task.column}"] .body .cards_list`);
if (!columnBody) return;
// Define a classe CSS do card com base na coluna
let cardClass = '';
switch (task.column) {
case 1:
cardClass = 'todo';
break;
case 2:
cardClass = 'in-progress';
break;
case 3:
cardClass = 'completed';
break;
}
const card = `
<div
id="${task.id}"
class="card ${cardClass}"
ondblclick="openModalToEdit(${task.id})"
draggable="true"
ondragstart="dragstart_handler(event)"
>
<div class="info">
<b>Atividade:</b>
<span>${task.description}</span>
</div>
<div class="info">
<b>Setor:</b>
<span>${task.tags}</span>
</div>
<div class="info">
<b>Prazo:</b>
<span>${formattedDate}</span>
</div>
<button class="material-symbols-outlined" onclick="deleteTask(${task.id})">delete</button>
</div>
`;
columnBody.insertAdjacentHTML('beforeend', card);
}
});
updateTaskCount();
}
}
// Funções de Drag and Drop
function dragstart_handler(ev) {
ev.dataTransfer.setData("task_id", ev.target.id); // Armazena o ID da tarefa que está sendo arrastada
ev.dataTransfer.effectAllowed = "move";
}
function dragover_handler(ev) {
ev.preventDefault(); // Necessário para permitir o drop
ev.dataTransfer.dropEffect = "move"; // Visualização do efeito de "movimento"
}
function drop_handler(ev) {
ev.preventDefault();
const task_id = ev.dataTransfer.getData("task_id"); // Recupera o ID da tarefa arrastada
const columnElement = ev.target.closest(".column"); // Encontra a coluna onde o drop ocorreu
if (columnElement) {
const column_id = columnElement.getAttribute('data-column'); // Obtém o ID da coluna (1, 2 ou 3)
changeColumn(task_id, column_id); // Muda a tarefa de coluna
}
}
function changeColumn(task_id, column_id) {
const user = app.users.find(user => user.id === app.selectedUserId);
if (user) {
user.tasks = user.tasks.map((task) => {
if (task.id != task_id) return task;
const updatedTask = {
...task,
column: parseInt(column_id),
};
const cardElement = document.getElementById(task.id);
if (cardElement) {
cardElement.classList.remove('todo', 'in-progress', 'completed');
switch (column_id) {
case '1':
cardElement.classList.add('todo');
break;
case '2':
cardElement.classList.add('in-progress');
break;
case '3':
cardElement.classList.add('completed');
break;
}
}
return updatedTask;
});
app.renderTasks();
app.saveUsers();
updateTaskCount();
}
}
// Atualização de Contagem de Tarefas
function updateTaskCount() {
const columns = [1, 2, 3]; // IDs das colunas "To Do", "In Progress", e "Completed"
columns.forEach(columnId => {
const user = app.users.find(user => user.id === app.selectedUserId);
if (!user) return;
const count = user.tasks.filter(task => parseInt(task.column) === columnId).length;
const columnHeader = document.querySelector(`[data-column="${columnId}"] .head span`);
if (columnHeader) {
columnHeader.innerText = `${columnHeader.innerText.split('(')[0].trim()} (${count})`;
}
});
}
const app = new App();