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
|
import { action, makeObservable, IReactionDisposer, reaction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Docs } from '../../documents/Documents';
import { DocumentType } from '../../documents/DocumentTypes';
import { FieldView } from './FieldView';
import { DateField } from '../../../fields/DateField';
import { Doc } from '../../../fields/Doc';
import './TaskBox.scss';
import { GoogleAuthenticationManager } from '../../apis/GoogleAuthenticationManager';
/**
* Props (reference to document) for Task Box
*/
interface TaskBoxProps {
Document: Doc;
}
/**
* TaskBox class for adding task information + completing tasks
*/
@observer
export class TaskBox extends React.Component<TaskBoxProps> {
// contains the last synced task information
lastSyncedTask: {
title: string;
text: string;
due?: string;
completed: boolean;
} = {
title: '',
text: '',
due: '',
completed: false,
};
state = {
needsSync: false,
};
/**
* Method to reuturn the
* @param fieldStr
* @returns
*/
public static LayoutString(fieldStr: string) {
return FieldView.LayoutString(TaskBox, fieldStr);
}
/**
* Method to update the task description
* @param e - event of changing the description box input
*/
@action
updateText = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
this.props.Document.text = e.target.value;
};
/**
* Method to update the task title
* @param e - event of changing the title box input
*/
@action
updateTitle = (e: React.ChangeEvent<HTMLInputElement>) => {
this.props.Document.title = e.target.value;
};
/**
* Method to update the all day status
* @param e - event of changing the all day checkbox
*/
@action
updateAllDay = (e: React.ChangeEvent<HTMLInputElement>) => {
this.props.Document.$task_allDay = e.target.checked;
if (e.target.checked) {
delete this.props.Document.$task_startTime;
delete this.props.Document.$task_endTime;
}
this.setTaskDateRange();
};
/**
* Method to update the task start time
* @param e - event of changing the start time input
*/
@action
updateStart = (e: React.ChangeEvent<HTMLInputElement>) => {
const newStart = new Date(e.target.value);
this.props.Document.$task_startTime = new DateField(newStart);
const endDate = this.props.Document.$task_endTime instanceof DateField ? this.props.Document.$task_endTime.date : undefined;
if (endDate && newStart > endDate) {
// Alert user
alert('Start time cannot be after end time. End time has been adjusted.');
// Fix end time
const adjustedEnd = new Date(newStart.getTime() + 60 * 60 * 1000);
this.props.Document.$task_endTime = new DateField(adjustedEnd);
}
this.setTaskDateRange();
};
/**
* Method to update the task end time
* @param e - event of changing the end time input
*/
@action
updateEnd = (e: React.ChangeEvent<HTMLInputElement>) => {
const newEnd = new Date(e.target.value);
this.props.Document.$task_endTime = new DateField(newEnd);
const startDate = this.props.Document.$task_startTime instanceof DateField ? this.props.Document.$task_startTime.date : undefined;
if (startDate && newEnd < startDate) {
// Alert user
alert('End time cannot be before start time. Start time has been adjusted.');
// Fix start time
const adjustedStart = new Date(newEnd.getTime() - 60 * 60 * 1000);
this.props.Document.$task_startTime = new DateField(adjustedStart);
}
this.setTaskDateRange();
};
/**
* Method to update the task date range
*/
@action
setTaskDateRange() {
const doc = this.props.Document;
if (doc.$task_allDay) {
const range = typeof doc.$task_dateRange === 'string' ? doc.$task_dateRange.split('|') : [];
const dateStr = range[0] ?? new Date().toISOString().split('T')[0]; // default to today
doc.$task_dateRange = `${dateStr}|${dateStr}`;
doc.$task_allDay = true;
} else {
const startField = doc.$task_startTime;
const endField = doc.$task_endTime;
const startDate = startField instanceof DateField ? startField.date : null;
const endDate = endField instanceof DateField ? endField.date : null;
if (startDate && endDate && !isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
doc.$task_dateRange = `${startDate.toISOString()}|${endDate.toISOString()}`;
doc.$task_allDay = false;
}
}
}
/**
* Method to set task's completion status
* @param e - event of changing the "completed" input checkbox
*/
@action
toggleComplete = (e: React.ChangeEvent<HTMLInputElement>) => {
this.props.Document.$task_completed = e.target.checked;
};
/**
* Constructor for the task box
* @param props - props containing the document reference
*/
constructor(props: TaskBoxProps) {
super(props);
makeObservable(this);
}
_googleTaskCreateDisposer?: IReactionDisposer;
_heightDisposer?: IReactionDisposer;
_widthDisposer?: IReactionDisposer;
componentDidMount() {
this.setTaskDateRange();
const doc = this.props.Document;
// adding task on creation to google
(async () => {
if (!doc.$googleTaskId && doc.title) {
try {
const token = await GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken();
if (!token) return;
const body: any = {
title: doc.title || 'Untitled Task',
notes: doc.text || '',
status: doc.$task_completed ? 'completed' : 'needsAction',
completed: doc.$task_completed ? new Date().toISOString() : undefined,
};
if (doc.$task_allDay && typeof doc.$task_dateRange === 'string') {
const datePart = doc.$task_dateRange.split('|')[0];
if (datePart && !isNaN(new Date(datePart).getTime())) {
const baseDate = datePart.includes('T') ? datePart : datePart + 'T00:00:00Z';
body.due = new Date(baseDate).toISOString();
}
} else if (doc.$task_endTime instanceof DateField) {
body.due = doc.$task_endTime.date.toISOString();
}
const res = await fetch('/googleTasks/create', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
const result = await res.json();
if (result?.id) {
doc.$googleTaskId = result.id;
console.log('✅ Google Task created on mount:', result);
} else {
console.warn('❌ Google Task creation failed:', result);
}
} catch (err) {
console.error('❌ Error creating Google Task:', err);
}
}
})();
this._heightDisposer = reaction(
() => Number(doc._height),
height => {
const minHeight = Number(doc.height_min ?? 0);
if (!isNaN(height) && height < minHeight) {
doc._height = minHeight;
}
}
);
this._widthDisposer = reaction(
() => Number(doc._width),
width => {
const minWidth = Number(doc.width_min ?? 0);
if (!isNaN(width) && width < minWidth) {
doc._width = minWidth;
}
}
);
this._googleTaskCreateDisposer = reaction(
() => {
const { title, text, $task_completed, $task_dateRange, $task_startTime, $task_endTime, $task_allDay } = doc;
const completed = !!$task_completed;
let due: string | undefined;
if ($task_allDay && typeof $task_dateRange === 'string') {
const datePart = $task_dateRange.split('|')[0];
if (datePart && !isNaN(new Date(datePart).getTime())) {
due = new Date(datePart + 'T00:00:00Z').toISOString();
}
} else if ($task_endTime && $task_endTime instanceof DateField && $task_endTime.date) {
due = $task_endTime.date.toISOString();
} else if ($task_startTime && $task_startTime instanceof DateField && $task_startTime.date) {
due = $task_startTime.date.toISOString();
}
return { title, text, completed, due };
},
current => {
const hasChanged = current.title !== this.lastSyncedTask.title || current.text !== this.lastSyncedTask.text || current.due !== this.lastSyncedTask.due || current.completed !== this.lastSyncedTask.completed;
this.setState({ needsSync: hasChanged });
},
{ fireImmediately: true }
);
}
componentWillUnmount() {
const doc = this.props.Document;
this._googleTaskCreateDisposer?.();
this._heightDisposer?.();
this._widthDisposer?.();
// task deletion
if (doc.$googleTaskId) {
(async () => {
try {
const token = await GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken();
if (!token) return;
await fetch(`/googleTasks/${doc.$googleTaskId}`, {
method: 'DELETE',
credentials: 'include',
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log(`✅ Deleted Google Task ${doc.$googleTaskId}`);
} catch (err) {
console.warn('❌ Failed to delete Google Task:', err);
}
})();
}
}
/**
* Method to render the task box
* @returns - HTML with taskbox components
*/
render() {
function toLocalDateTimeString(date: Date): string {
const pad = (n: number) => n.toString().padStart(2, '0');
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes());
}
const doc = this.props.Document;
const taskDesc = typeof doc.text === 'string' ? doc.text : '';
const taskTitle = typeof doc.title === 'string' ? doc.title : '';
const allDay = !!doc.$task_allDay;
const isCompleted = !!this.props.Document.$task_completed;
const startTime = doc.$task_startTime instanceof DateField && doc.$task_startTime.date instanceof Date ? toLocalDateTimeString(doc.$task_startTime.date) : '';
const endTime = doc.$task_endTime instanceof DateField && doc.$task_endTime.date instanceof Date ? toLocalDateTimeString(doc.$task_endTime.date) : '';
const handleGoogleTaskSync = async () => {
console.log('GT button clicked');
try {
const token = await GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken();
if (!token) {
const listener = () => {
window.removeEventListener('focusin', listener);
if (confirm('✅ Authorization complete. Try syncing the task again?')) {
// you could refactor the click handler here
handleGoogleTaskSync();
}
window.removeEventListener('focusin', listener);
};
setTimeout(() => window.addEventListener('focusin', listener), 100);
return;
}
let due: string | undefined;
if (allDay) {
const rawRange = typeof doc.$task_dateRange === 'string' ? doc.$task_dateRange : '';
const datePart = rawRange.split('|')[0];
if (datePart && !isNaN(new Date(datePart).getTime())) {
// Set time to midnight UTC to represent the start of the all-day event
const baseDate = datePart.includes('T') ? datePart : datePart + 'T00:00:00Z';
due = new Date(baseDate).toISOString();
} else {
due = undefined;
}
} else if (doc.$task_endTime instanceof DateField && doc.$task_endTime.date) {
due = doc.$task_endTime.date.toISOString();
} else if (doc.$task_startTime instanceof DateField && doc.$task_startTime.date) {
due = doc.$task_startTime.date.toISOString();
} else {
due = undefined;
}
const isUpdate = !!doc.$googleTaskId;
const endpoint = isUpdate ? `/googleTasks/${doc.$googleTaskId}` : '/googleTasks/create';
const method = isUpdate ? 'PATCH' : 'POST';
const response = await fetch(endpoint, {
method,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
title: taskTitle || 'Untitled Task',
notes: taskDesc,
due,
status: doc.$task_completed ? 'completed' : 'needsAction',
completed: doc.$task_completed ? new Date().toISOString() : undefined,
}),
});
const result = await response.json();
console.log('Google Task result:', result);
if (result?.id) {
alert('✅ Task synced with Google Tasks!');
if (result?.id) {
this.lastSyncedTask = {
title: taskTitle,
text: taskDesc,
due,
completed: isCompleted,
};
this.setState({ needsSync: false });
}
} else {
alert(`❌ Failed: ${result?.error?.message || 'Unknown error'}`);
}
} catch (err) {
console.error('Fetch error:', err);
alert('❌ Task syncing failed.');
}
};
return (
<div className="task-manager-container">
<input className="task-manager-title" type="text" placeholder="Task Title" value={taskTitle} onChange={this.updateTitle} disabled={isCompleted} style={{ opacity: isCompleted ? 0.7 : 1 }} />
<textarea className="task-manager-description" placeholder="What’s your task?" value={taskDesc} onChange={this.updateText} disabled={isCompleted} style={{ opacity: isCompleted ? 0.7 : 1 }} />
<div className="task-manager-checkboxes">
<label className="task-manager-allday" style={{ opacity: isCompleted ? 0.7 : 1 }}>
<input type="checkbox" checked={allDay} onChange={this.updateAllDay} disabled={isCompleted} />
All day
{allDay && (
<input
type="date"
value={(() => {
const rawRange = doc.$task_dateRange;
if (typeof rawRange !== 'string') return '';
const datePart = rawRange.split('|')[0];
if (!datePart) return '';
const d = new Date(datePart);
return !isNaN(d.getTime()) ? d.toISOString().split('T')[0] : '';
})()}
onChange={e => {
const newDate = new Date(e.target.value);
if (!isNaN(newDate.getTime())) {
const dateStr = e.target.value;
if (dateStr) {
doc.$task_dateRange = `${dateStr}T00:00:00|${dateStr}T00:00:00`;
}
}
}}
disabled={isCompleted}
style={{ marginLeft: '8px' }}
/>
)}
</label>
<label className="task-manager-complete">
<input type="checkbox" checked={isCompleted} onChange={this.toggleComplete} />
Complete
</label>
<button
className="task-manager-google"
disabled={!this.state.needsSync}
onClick={event => {
event.preventDefault();
handleGoogleTaskSync();
}}>
Sync to Google
</button>
</div>
{!allDay && (
<div className="task-manager-times" style={{ opacity: isCompleted ? 0.7 : 1 }}>
<label>
Start:
<input type="datetime-local" value={startTime} onChange={this.updateStart} disabled={isCompleted} />
</label>
<label>
End:
<input type="datetime-local" value={endTime} onChange={this.updateEnd} disabled={isCompleted} />
</label>
</div>
)}
</div>
);
}
}
Docs.Prototypes.TemplateMap.set(DocumentType.TASK, {
layout: { view: TaskBox, dataField: 'text' },
options: {
acl: '',
_height: 35,
_xMargin: 10,
_yMargin: 10,
_layout_autoHeight: true,
_layout_nativeDimEditable: true,
_layout_reflowVertical: true,
_layout_reflowHorizontal: true,
task: '',
defaultDoubleClick: 'ignore',
systemIcon: 'BsCheckSquare',
height_min: 300,
width_min: 300,
},
});
|