Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
574 lines (500 loc) · 20 KB
/
Copy pathscript.js
File metadata and controls
574 lines (500 loc) · 20 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
class TodoApp {
constructor() {
this.tasks = this.loadTasks();
this.taskCounter = this.getNextTaskId();
this.settings = this.loadSettings();
this.initializeEventListeners();
this.renderTasks();
}
// Initialize all event listeners
initializeEventListeners() {
const taskInput = document.getElementById('taskInput');
const addTaskBtn = document.getElementById('addTaskBtn');
const settingsBtn = document.getElementById('settingsBtn');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
const testConnectionBtn = document.getElementById('testConnectionBtn');
const settingsModal = document.getElementById('settingsModal');
// Add task button click
addTaskBtn.addEventListener('click', () => this.addMainTask());
// Enter key in task input
taskInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.addMainTask();
}
});
// Settings modal
settingsBtn.addEventListener('click', () => this.showSettings());
closeSettingsBtn.addEventListener('click', () => this.hideSettings());
settingsModal.addEventListener('click', (e) => {
if (e.target === settingsModal) {
this.hideSettings();
}
});
// Settings actions
saveSettingsBtn.addEventListener('click', () => this.saveSettings());
testConnectionBtn.addEventListener('click', () => this.testConnection());
// Escape key to close modal
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && settingsModal.classList.contains('show')) {
this.hideSettings();
}
});
}
// Load tasks from localStorage
loadTasks() {
try {
const savedTasks = localStorage.getItem('todoAppTasks');
return savedTasks ? JSON.parse(savedTasks) : [];
} catch (error) {
console.error('Error loading tasks:', error);
return [];
}
}
// Load settings from localStorage
loadSettings() {
try {
const savedSettings = localStorage.getItem('todoAppSettings');
return savedSettings ? JSON.parse(savedSettings) : {
apiEndpoint: '',
apiKey: '',
deploymentName: ''
};
} catch (error) {
console.error('Error loading settings:', error);
return {
apiEndpoint: '',
apiKey: '',
deploymentName: ''
};
}
}
// Save tasks to localStorage
saveTasks() {
try {
localStorage.setItem('todoAppTasks', JSON.stringify(this.tasks));
} catch (error) {
console.error('Error saving tasks:', error);
}
}
// Save settings to localStorage
saveSettingsData() {
try {
localStorage.setItem('todoAppSettings', JSON.stringify(this.settings));
} catch (error) {
console.error('Error saving settings:', error);
}
}
// Get next available task ID
getNextTaskId() {
const maxId = this.tasks.reduce((max, task) => {
const taskMaxId = Math.max(max, task.id);
const subtaskMaxId = task.subtasks ?
task.subtasks.reduce((subMax, subtask) => Math.max(subMax, subtask.id), 0) : 0;
return Math.max(taskMaxId, subtaskMaxId);
}, 0);
return maxId + 1;
}
// Add a new main task
addMainTask() {
const taskInput = document.getElementById('taskInput');
const title = taskInput.value.trim();
if (!title) {
taskInput.focus();
return;
}
const newTask = {
id: this.taskCounter++,
title: title,
completed: false,
subtasks: []
};
this.tasks.push(newTask);
taskInput.value = '';
this.saveTasks();
this.renderTasks();
taskInput.focus();
}
// Add a subtask to a main task
addSubtask(taskId, title) {
const task = this.tasks.find(t => t.id === taskId);
if (!task || !title.trim()) return;
const newSubtask = {
id: this.taskCounter++,
title: title.trim(),
completed: false
};
task.subtasks.push(newSubtask);
this.saveTasks();
this.renderTasks();
}
// Toggle task completion status
toggleTaskCompletion(taskId) {
const task = this.tasks.find(t => t.id === taskId);
if (task) {
task.completed = !task.completed;
this.saveTasks();
this.renderTasks();
}
}
// Toggle subtask completion status
toggleSubtaskCompletion(taskId, subtaskId) {
const task = this.tasks.find(t => t.id === taskId);
if (task) {
const subtask = task.subtasks.find(st => st.id === subtaskId);
if (subtask) {
subtask.completed = !subtask.completed;
this.saveTasks();
this.renderTasks();
}
}
}
// Update task title
updateTaskTitle(taskId, newTitle) {
const task = this.tasks.find(t => t.id === taskId);
if (task && newTitle.trim()) {
task.title = newTitle.trim();
this.saveTasks();
}
}
// Update subtask title
updateSubtaskTitle(taskId, subtaskId, newTitle) {
const task = this.tasks.find(t => t.id === taskId);
if (task && newTitle.trim()) {
const subtask = task.subtasks.find(st => st.id === subtaskId);
if (subtask) {
subtask.title = newTitle.trim();
this.saveTasks();
}
}
}
// Delete a main task
deleteTask(taskId) {
this.tasks = this.tasks.filter(t => t.id !== taskId);
this.saveTasks();
this.renderTasks();
}
// Delete a subtask
deleteSubtask(taskId, subtaskId) {
const task = this.tasks.find(t => t.id === taskId);
if (task) {
task.subtasks = task.subtasks.filter(st => st.id !== subtaskId);
this.saveTasks();
this.renderTasks();
}
}
// Settings management
showSettings() {
const modal = document.getElementById('settingsModal');
const apiEndpoint = document.getElementById('apiEndpoint');
const apiKey = document.getElementById('apiKey');
const deploymentName = document.getElementById('deploymentName');
// Populate current settings
apiEndpoint.value = this.settings.apiEndpoint || '';
apiKey.value = this.settings.apiKey || '';
deploymentName.value = this.settings.deploymentName || '';
modal.classList.add('show');
}
hideSettings() {
const modal = document.getElementById('settingsModal');
const status = document.getElementById('connectionStatus');
modal.classList.remove('show');
status.style.display = 'none';
}
saveSettings() {
const apiEndpoint = document.getElementById('apiEndpoint').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
const deploymentName = document.getElementById('deploymentName').value.trim();
if (!apiEndpoint || !apiKey || !deploymentName) {
this.showConnectionStatus('Please fill in all fields', 'error');
return;
}
this.settings = {
apiEndpoint: apiEndpoint,
apiKey: apiKey,
deploymentName: deploymentName
};
this.saveSettingsData();
this.showConnectionStatus('Settings saved successfully!', 'success');
}
async testConnection() {
const apiEndpoint = document.getElementById('apiEndpoint').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
const deploymentName = document.getElementById('deploymentName').value.trim();
if (!apiEndpoint || !apiKey || !deploymentName) {
this.showConnectionStatus('Please fill in all fields first', 'error');
return;
}
const testBtn = document.getElementById('testConnectionBtn');
testBtn.disabled = true;
testBtn.textContent = '🔄 Testing...';
try {
const response = await this.callAzureAI('Test connection', apiEndpoint, apiKey, deploymentName);
if (response) {
this.showConnectionStatus('✅ Connection successful!', 'success');
} else {
this.showConnectionStatus('❌ Connection failed. Please check your settings.', 'error');
}
} catch (error) {
this.showConnectionStatus(`❌ Connection failed: ${error.message}`, 'error');
} finally {
testBtn.disabled = false;
testBtn.textContent = '🔗 Test Connection';
}
}
showConnectionStatus(message, type) {
const status = document.getElementById('connectionStatus');
status.textContent = message;
status.className = `connection-status ${type}`;
status.style.display = 'block';
}
// AI Integration
async planForMe(taskId) {
const task = this.tasks.find(t => t.id === taskId);
if (!task) return;
if (!this.settings.apiEndpoint || !this.settings.apiKey || !this.settings.deploymentName) {
alert('Please configure your AI settings first by clicking the Settings button.');
this.showSettings();
return;
}
this.showLoading();
try {
const subtasks = await this.callAzureAI(task.title, this.settings.apiEndpoint, this.settings.apiKey, this.settings.deploymentName);
if (subtasks && subtasks.length > 0) {
// Add the AI-generated subtasks
subtasks.forEach(subtaskTitle => {
if (subtaskTitle.trim()) {
const newSubtask = {
id: this.taskCounter++,
title: subtaskTitle.trim(),
completed: false
};
task.subtasks.push(newSubtask);
}
});
this.saveTasks();
this.renderTasks();
}
} catch (error) {
console.error('Error calling AI:', error);
alert('Failed to generate subtasks. Please check your AI settings and try again.');
} finally {
this.hideLoading();
}
}
async callAzureAI(taskTitle, endpoint, apiKey, deploymentName) {
const url = `${endpoint}/openai/deployments/${deploymentName}/chat/completions?api-version=2024-02-15-preview`;
const prompt = `Break down this task into 3-7 actionable subtasks. Return only a JSON array of strings, no other text or formatting:
Task: "${taskTitle}"
Example response format: ["Subtask 1", "Subtask 2", "Subtask 3"]`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': apiKey
},
body: JSON.stringify({
messages: [
{
role: 'system',
content: 'You are a helpful assistant that breaks down tasks into smaller, actionable subtasks. Always respond with a valid JSON array of strings.'
},
{
role: 'user',
content: prompt
}
],
max_tokens: 500,
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const content = data.choices[0]?.message?.content?.trim();
if (!content) {
throw new Error('No response from AI');
}
try {
// Parse the JSON response
const subtasks = JSON.parse(content);
if (Array.isArray(subtasks)) {
return subtasks.slice(0, 10); // Limit to 10 subtasks
} else {
throw new Error('Response is not an array');
}
} catch (parseError) {
console.error('Failed to parse AI response:', content);
// Fallback: try to extract lines as subtasks
const lines = content.split('\n')
.map(line => line.replace(/^\d+\.?\s*/, '').replace(/^[-*]\s*/, '').trim())
.filter(line => line.length > 0)
.slice(0, 10);
return lines.length > 0 ? lines : null;
}
}
showLoading() {
document.getElementById('loadingOverlay').classList.add('show');
}
hideLoading() {
document.getElementById('loadingOverlay').classList.remove('show');
}
// Render all tasks
renderTasks() {
const tasksContainer = document.getElementById('tasksContainer');
const emptyState = document.getElementById('emptyState');
if (this.tasks.length === 0) {
tasksContainer.innerHTML = '';
emptyState.classList.add('show');
return;
}
emptyState.classList.remove('show');
tasksContainer.innerHTML = this.tasks.map(task => this.renderTask(task)).join('');
// Add event listeners after rendering
this.addTaskEventListeners();
}
// Render a single task
renderTask(task) {
const subtasksHtml = task.subtasks.map(subtask => this.renderSubtask(task.id, subtask)).join('');
return `
<div class="task-item ${task.completed ? 'completed' : ''}">
<div class="main-task">
<input type="checkbox" class="task-checkbox"
${task.completed ? 'checked' : ''}
data-task-id="${task.id}">
<input type="text" class="task-title ${task.completed ? 'completed' : ''}"
value="${this.escapeHtml(task.title)}"
data-task-id="${task.id}"
maxlength="100">
<div class="task-actions">
<button class="plan-for-me-btn" data-task-id="${task.id}" title="Generate subtasks with AI">
🪄 PlanForMe
</button>
<button class="add-subtask-btn" data-task-id="${task.id}">+ Subtask</button>
<button class="delete-task-btn" data-task-id="${task.id}">×</button>
</div>
</div>
${task.subtasks.length > 0 ? `
<div class="subtasks-container">
${subtasksHtml}
</div>
` : ''}
</div>
`;
}
// Render a single subtask
renderSubtask(taskId, subtask) {
return `
<div class="subtask-item">
<input type="checkbox" class="subtask-checkbox"
${subtask.completed ? 'checked' : ''}
data-task-id="${taskId}" data-subtask-id="${subtask.id}">
<input type="text" class="subtask-title ${subtask.completed ? 'completed' : ''}"
value="${this.escapeHtml(subtask.title)}"
data-task-id="${taskId}" data-subtask-id="${subtask.id}"
maxlength="100">
<button class="delete-subtask-btn"
data-task-id="${taskId}" data-subtask-id="${subtask.id}">×</button>
</div>
`;
}
// Add event listeners to task elements
addTaskEventListeners() {
const tasksContainer = document.getElementById('tasksContainer');
// Task checkboxes
tasksContainer.addEventListener('change', (e) => {
if (e.target.classList.contains('task-checkbox')) {
const taskId = parseInt(e.target.dataset.taskId);
this.toggleTaskCompletion(taskId);
} else if (e.target.classList.contains('subtask-checkbox')) {
const taskId = parseInt(e.target.dataset.taskId);
const subtaskId = parseInt(e.target.dataset.subtaskId);
this.toggleSubtaskCompletion(taskId, subtaskId);
}
});
// Task title editing
tasksContainer.addEventListener('blur', (e) => {
if (e.target.classList.contains('task-title')) {
const taskId = parseInt(e.target.dataset.taskId);
this.updateTaskTitle(taskId, e.target.value);
} else if (e.target.classList.contains('subtask-title')) {
const taskId = parseInt(e.target.dataset.taskId);
const subtaskId = parseInt(e.target.dataset.subtaskId);
this.updateSubtaskTitle(taskId, subtaskId, e.target.value);
}
}, true);
// Enter key for saving edits
tasksContainer.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.target.blur();
}
});
// Button clicks
tasksContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('plan-for-me-btn')) {
const taskId = parseInt(e.target.dataset.taskId);
this.planForMe(taskId);
} else if (e.target.classList.contains('add-subtask-btn')) {
const taskId = parseInt(e.target.dataset.taskId);
this.showSubtaskInput(taskId, e.target);
} else if (e.target.classList.contains('delete-task-btn')) {
const taskId = parseInt(e.target.dataset.taskId);
if (confirm('Are you sure you want to delete this task and all its subtasks?')) {
this.deleteTask(taskId);
}
} else if (e.target.classList.contains('delete-subtask-btn')) {
const taskId = parseInt(e.target.dataset.taskId);
const subtaskId = parseInt(e.target.dataset.subtaskId);
if (confirm('Are you sure you want to delete this subtask?')) {
this.deleteSubtask(taskId, subtaskId);
}
}
});
}
// Show subtask input field
showSubtaskInput(taskId, button) {
// Check if input already exists
if (button.parentNode.parentNode.querySelector('.add-subtask-input')) {
return;
}
const input = document.createElement('input');
input.type = 'text';
input.className = 'add-subtask-input';
input.placeholder = 'Enter subtask title...';
input.maxLength = 100;
const handleSubtaskAdd = () => {
const title = input.value.trim();
if (title) {
this.addSubtask(taskId, title);
} else {
input.remove();
}
};
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleSubtaskAdd();
} else if (e.key === 'Escape') {
input.remove();
}
});
input.addEventListener('blur', handleSubtaskAdd);
const taskItem = button.parentNode.parentNode.parentNode;
taskItem.appendChild(input);
input.focus();
}
// Escape HTML to prevent XSS
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
// Initialize the app when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new TodoApp();
});
// Export for potential testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = TodoApp;
}