-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
421 lines (394 loc) · 12.1 KB
/
index.tsx
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
import React, { KeyboardEvent, SyntheticEvent, ReactElement } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus, faArrowAltCircleRight } from '@fortawesome/free-solid-svg-icons';
import 'react-toastify/dist/ReactToastify.css';
import styles from './index.module.css';
import TagPicker from './TagPicker';
import DatePicker from './DatePicker';
import FocusPicker from './FocusPicker';
import { randomId } from '../../util/general-util';
import { OneTimeTask, RepeatingTask, RepeatMetaData, SubTask } from '../../store/store-types';
import { NONE_TAG_ID } from '../../util/tag-util';
import { isToday } from '../../util/datetime-util';
import { addTask, TaskWithoutIdOrderChildren } from '../../firebase/actions';
import SamwiseIcon from '../UI/SamwiseIcon';
type SimpleTaskMapper<T> = Pick<T, Exclude<keyof T, 'type' | 'order' | 'children'>>
type OneTimeSimpleTask = SimpleTaskMapper<OneTimeTask>;
type RepeatedSimpleTask = SimpleTaskMapper<RepeatingTask>
type SimpleTask = OneTimeSimpleTask | RepeatedSimpleTask;
type State = SimpleTask & {
readonly subTasks: SubTask[];
readonly opened: boolean;
readonly tagPickerOpened: boolean;
readonly datePickerOpened: boolean;
readonly datePicked: boolean;
readonly needToSwitchFocus: boolean;
readonly repeatData: RepeatMetaData | null;
};
/**
* The placeholder text in the main task input box.
*/
const PLACEHOLDER_TEXT = 'What do you have to do?';
/**
* Generate the initial state.
*/
const initialState = (): State => ({
id: randomId(),
name: '',
tag: NONE_TAG_ID, // the id of the None tag.
date: new Date(),
complete: false,
inFocus: false,
subTasks: [],
opened: false,
tagPickerOpened: false,
datePickerOpened: false,
datePicked: false,
needToSwitchFocus: false,
repeatData: null,
});
export default class TaskCreator extends React.PureComponent<{}, State> {
public readonly state: State = initialState();
private addTask: HTMLInputElement | null | undefined;
/*
* --------------------------------------------------------------------------------
* Part 1: Openers & Closers
* --------------------------------------------------------------------------------
*/
/**
* Open the new task editor.
*/
private openNewTask = () => this.setState({ opened: true });
/**
* Close (collapse) the new task editor.
*/
private closeNewTask = () => this.setState({ opened: false });
/**
* Open the tag picker and close the date picker.
*/
private openTagPicker = () => this.setState(({ tagPickerOpened }: State) => ({
tagPickerOpened: !tagPickerOpened,
datePickerOpened: false,
}));
/**
* Open the date picker and close the tag picker.
*/
private openDatePicker = () => this.setState(({ datePickerOpened }: State) => ({
datePickerOpened: !datePickerOpened,
tagPickerOpened: false,
}));
/*
* --------------------------------------------------------------------------------
* Part 2: Manager functions when finished editing.
* --------------------------------------------------------------------------------
*/
/**
* Focus on the task name, if possible.
*/
private focusTaskName = () => {
if (this.addTask) {
this.addTask.focus();
}
};
/**
* Handle on potential save.
*
* @param e the event that signals a potential save action.
*/
private handleSave = (e?: SyntheticEvent<HTMLElement>) => {
if (e != null) {
e.preventDefault();
}
const {
name, tag, date, complete, inFocus, subTasks, repeatData,
} = this.state;
if (name === '') {
return;
}
const newSubTasks = subTasks
.filter((subTask) => subTask.name !== '') // remove empty subtasks
// normalize orders: use current sequence as order;; remove useless id
.map(({ id, ...rest }, order) => ({ ...rest, order }));
const autoInFocus = inFocus || isToday(date); // Put task in focus is the due date is today.
const commonTask = { name, tag, date, complete, inFocus: autoInFocus };
let newTask: TaskWithoutIdOrderChildren;
if (repeatData === null) {
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
newTask = { ...commonTask, type: 'ONE_TIME', date };
} else {
const todayMidnight = new Date();
todayMidnight.setHours(23);
todayMidnight.setMinutes(59);
todayMidnight.setSeconds(59);
newTask = {
...commonTask,
date: todayMidnight,
type: 'MASTER_TEMPLATE',
forks: [],
repeats: repeatData,
inFocus: false,
};
}
// Add the task to the store.
addTask(newTask, newSubTasks);
// Reset the state.
this.setState({ ...initialState() });
this.closeNewTask();
if (this.addTask) {
this.addTask.blur();
}
};
/*
* --------------------------------------------------------------------------------
* Part 3: Various Editors
* --------------------------------------------------------------------------------
*/
/**
* Edit the task name.
*
* @param e the event that contains the new task name.
*/
private editTaskName = (e: SyntheticEvent<HTMLInputElement>) => this.setState(
{ name: e.currentTarget.value },
this.focusTaskName,
);
/**
* Edit the tag.
*
* @param {string} tag the new tag.
*/
private editTag = (tag: string) => this.setState(
{ tag, tagPickerOpened: false }, this.focusTaskName,
);
/**
* Edit the date.
*
* @param {Date} date the new date, or null for cancel.
*/
private editDate = (date: Date | RepeatMetaData | null) => {
const { datePicked } = this.state;
if (datePicked && date === null) {
// User cancelled, but date was already picked
this.setState(
{ datePickerOpened: false },
this.focusTaskName,
);
} else if (date instanceof Date || date === null) {
// Selecting a date, or user cancelled while date was not picked
this.setState(
{
date: date || new Date(),
datePickerOpened: false,
datePicked: Boolean(date),
repeatData: null,
},
this.focusTaskName,
);
} else {
// Repeating task
this.setState(
{
date: new Date(),
datePickerOpened: false,
datePicked: true,
repeatData: date,
},
this.focusTaskName,
);
}
};
/**
* Reset the date picker
*/
private clearDate = () => {
this.setState(
{ date: new Date(), datePickerOpened: false, datePicked: false, repeatData: null },
this.focusTaskName,
);
}
/**
* Toggle the pin status.
* @param {boolean} inFocus the new in-focus status.
*/
private togglePin = (inFocus: boolean) => this.setState({ inFocus }, this.focusTaskName);
/**
* Add a new subtask.
*
* @param e the event that contains the new name for new sub-task.
*/
private addNewSubTask = (e: SyntheticEvent<HTMLInputElement>) => {
const newSubTaskName = e.currentTarget.value;
if (newSubTaskName === '') {
return;
}
this.setState(({ subTasks }: State) => ({
subTasks: [...subTasks, {
id: String(subTasks.length),
order: 0, // some random order, will be ignored anyway
name: newSubTaskName,
complete: false,
inFocus: false,
}],
needToSwitchFocus: true,
}));
};
/**
* Handle a keypress event in a new subtask box.
* It can potentially make the form to lose focus to exit.
*
* @param e the event that contains the key pressed in the new subtask input box.
*/
private newSubTaskKeyPress = (e: KeyboardEvent<HTMLInputElement>): void => {
if (e.key === 'Tab') {
this.closeNewTask();
}
}
/**
* Edit a subtask.
*
* @param subTaskId id of the subtask to edit.
* @return the event handler.
*/
private editSubTask = (subTaskId: string) => (e: SyntheticEvent<HTMLInputElement>) => {
const name = e.currentTarget.value;
this.setState(({ subTasks }: State) => ({
subTasks: subTasks.map((s) => (s.id === subTaskId ? { ...s, name } : s)),
}));
};
/**
* Potentially submit a subtask.
*
* @param e the keyboard event.
*/
private submitSubTask = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
this.handleSave();
}
};
/**
* Delete a subtask.
*
* @param {string} subtaskId id of the subtask to delete.
* @return {Function<SyntheticEvent<HTMLInputElement>, void>} the event handler.
*/
private deleteSubTask = (subtaskId: string) => (e: SyntheticEvent<HTMLButtonElement>) => {
e.preventDefault();
this.setState(({ subTasks }: State) => ({
subTasks: subTasks.filter((s) => s.id !== subtaskId),
}));
};
/**
* Reset the task.
*/
private resetTask = () => this.setState({ ...initialState() }, this.focusTaskName);
/**
* Renders the editor for all the other info except main task name.
*
* @return the rendered other info editor.
*/
private renderOtherInfoEditor(): ReactElement | null {
const { opened } = this.state;
if (!opened) {
return null;
}
const {
tag, date, inFocus, subTasks,
tagPickerOpened, datePickerOpened, datePicked, needToSwitchFocus,
repeatData,
} = this.state;
const existingSubTaskEditor = (
{ id, name }: SubTask, i: number, arr: SubTask[],
): ReactElement => {
const refHandler = (inputElementRef: HTMLInputElement | null): void => {
if (i === arr.length - 1 && needToSwitchFocus && inputElementRef != null) {
inputElementRef.focus();
this.setState({ needToSwitchFocus: false });
}
};
return (
<li key={id}>
<button type="button" tabIndex={-1} onClick={this.deleteSubTask(id)}>
<SamwiseIcon iconName="x-dark" />
</button>
<input
type="text"
ref={refHandler}
value={name}
onChange={this.editSubTask(id)}
onKeyDown={this.submitSubTask}
/>
</li>
);
};
return (
<div className={styles.NewTaskActive}>
{repeatData === null && <FocusPicker pinned={inFocus} onPinChange={this.togglePin} />}
<div className={styles.TagPickWrap}>
<TagPicker
tag={tag}
opened={tagPickerOpened}
onTagChange={this.editTag}
onPickerOpened={this.openTagPicker}
/>
</div>
<DatePicker
date={repeatData || date}
opened={datePickerOpened}
datePicked={datePicked}
onDateChange={this.editDate}
onClearPicker={this.clearDate}
onPickerOpened={this.openDatePicker}
/>
<button tabIndex={-1} type="submit" className={styles.SubmitNewTask}>
<FontAwesomeIcon icon={faArrowAltCircleRight} />
</button>
<div className={styles.NewTaskModal}>
<ul>{subTasks.map(existingSubTaskEditor)}</ul>
<FontAwesomeIcon icon={faPlus} className={styles.PlusIcon} />
<input
type="text"
placeholder="Add a Subtask"
value=""
onChange={this.addNewSubTask}
onKeyDown={this.newSubTaskKeyPress}
/>
<button type="button" className={styles.ResetButton} onClick={this.resetTask}>
{'Clear'}
</button>
</div>
</div>
);
}
public render(): ReactElement {
const { name, opened } = this.state;
const toggleDisplayStyle = opened ? {} : { display: 'none' };
return (
<div>
<div
onClick={this.closeNewTask}
role="presentation"
className={styles.CloseNewTask}
style={toggleDisplayStyle}
/>
<form
className={styles.NewTaskWrap}
onSubmit={this.handleSave}
onFocus={this.openNewTask}
>
<input
required
type="text"
value={name}
onChange={this.editTaskName}
className={styles.NewTaskComponent}
placeholder={opened ? '' : PLACEHOLDER_TEXT}
ref={(e) => { this.addTask = e; }}
/>
{this.renderOtherInfoEditor()}
</form>
</div>
);
}
}