-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOutline.jsx
More file actions
381 lines (333 loc) · 12 KB
/
Outline.jsx
File metadata and controls
381 lines (333 loc) · 12 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
import PropTypes from 'prop-types';
import React from 'react';
import Tree, { mutateTree, moveItemOnTree } from '@atlaskit/tree';
import update from 'immutability-helper';
import clone from 'lodash.clonedeep';
import * as Icon from 'react-feather';
import network from './network'; // Performs network calls to the Rails backend
import send from './send'; // Sends task updates to the Rails backend
import sendTaskMovement from './sendTaskMovement'; // Tells the Rails backend that a task has a new parent and/or a new position in a list
import taskUpdates from './taskUpdates'; // Broadcasts task changes to other components
import FrontSideTask from './FrontSideTask';
export default class Outline extends React.Component {
static propTypes = {
tasks: PropTypes.object.isRequired,
completedTasksVisible: PropTypes.bool.isRequired,
checkboxChange: PropTypes.func,
parentId: PropTypes.number,
}
constructor(props) {
super(props);
this.state = {
treeData: this.props.tasks,
subscribedToTaskUpdates: false,
new_task_name: ""
}
// data structure for adding new subtasks to tree items
Object.entries(this.state.treeData.items).forEach(([key, item]) => {
if (item.data) {
item.data.newSubtaskName = "";
item.data.addSubtaskId = null;
item.hidden = false;
}
});
}
// METHODS (alphabetical)
addNewTask = event => {
event.preventDefault();
var task = {
name: this.state.new_task_name
};
if (this.props.parentId) task.parent_id = this.props.parentId;
network.post("/tasks", task)
.then(response => {
this.setState(state => {
var newTask = response.data;
var newState = {...state}
var newId = newTask.id;
newTask.id = newTask.id.toString();
var newTask = {
id: newTask.id,
children: [],
isExpanded: true,
data: newTask,
}
newState.treeData.items[newId] = newTask;
newState.treeData.items[newState.treeData.rootId].children.push(newTask.id);
return newState;
})
});
this.setState({ new_task_name: '' });
}
addSubtask = (event, itemData) => {
event.preventDefault();
const newSubtaskName = itemData.newSubtaskName;
const parentId = itemData.id;
var task = {
name: newSubtaskName,
parent_id: parentId,
};
network.post("/tasks", task)
.then(response => {
this.updateAncestors(parentId, 'descendant_count', 1, 0);
this.setState(state => {
var newTask = response.data;
var newState = {...state};
var newId = newTask.id;
newTask.id = newTask.id.toString();
var newTask = {
id: newTask.id,
children: [],
isExpanded: true,
data: newTask,
}
newState.treeData.items[newId] = newTask;
newState.treeData.items[parentId].children.push(newTask.id);
return newState;
})
}).catch(error => {
toastr.error(error.message);
});
const newState = update(this.state, {
treeData: {items: {[parentId]: {data: {newSubtaskName: {$set: ''}}}}},
});
this.setState(newState);
}
checkboxChange = (task, broadcast = true) => {
// Update tree
const newState = update(this.state, {
treeData: {items: {[task.id]: {data: {completed: {$set: task.completed}}}}},
});
this.setState(newState, () => {
this.updateAncestors(this.getParentId(task.id), 'completed_descendant_count', task.completed ? 1 : -1, 250);
});
// Tasks which were blocked by this one are no longer blocked
if (task.blocked_by_ids) task.blocked_by_ids.forEach(id => {
this.toggleTaskBlock(task.id, id, 'blocking_ids');
});
// Tasks which blocked this one are no longer blocking
if (task.blocking_ids) task.blocking_ids.forEach(id => {
this.toggleTaskBlock(task.id, id, 'blocked_by_ids');
});
// Update server
send(task);
// Notify other components
if (broadcast) taskUpdates.broadcast(task, "outline");
// Fire callback
if (this.props.checkboxChange) {
this.props.checkboxChange(task);
}
}
deleteTask = (task) => {
if (confirm(`Delete ${task.name}?`)) {
let id = task.id;
network.delete(`/tasks/${id}.json`).then(() => {
window.location.reload();
});
}
}
getIcon = (item, onExpand, onCollapse) => { // Returns a disclosure triangle if a list item has children
if (item.children && item.children.length > 0) {
if (item.isExpanded) {
return <button className="tree-node-icon" onClick={() => onCollapse(item.id)}>▾</button>
} else {
return <button className="tree-node-icon" onClick={() => onExpand(item.id)}>▸</button>
}
} else {
return <span className="tree-node-icon"></span>;
}
}
getParentId = taskId => {
const parentId = Object.keys(this.state.treeData.items).find(id => {
return (this.state.treeData.items[id].children.includes(Number(taskId)) || this.state.treeData.items[id].children.includes(String(taskId)));
});
if (parentId === undefined || parentId === 'root') {
return null;
} else {
return Number(parentId); // IDs are stored as strings sometimes, which is undesirable but changing it breaks @atlaskit/tree
}
}
handleAddNewTaskEdit = event => {
this.setState({ new_task_name: event.target.value });
}
handleNewSubtaskEdit = (event, item) => {
const newState = update(this.state, {
treeData: {items: {[item.id]: {data: {newSubtaskName: {$set: event.target.value}}}}},
});
this.setState(newState);
}
// handleToggleShowCompleted = event => {
// this.setState({ completedTasksVisible: event.detail.completedTasksVisible },
// () => { this.setHiddenOnTasks(); }
// );
// }
onDragStart = itemId => {
// work around bug where New Task field at the bottom pops up and covers last list item
var treeHeight = this.treeElement.clientHeight; // offsetHeight or clientHeight
var itemElement = document.querySelectorAll(`[data-item-number='${itemId}']`)[0];
var itemHeight = itemElement.clientHeight;
treeHeight = treeHeight + itemHeight;
this.treeElement.style.height = `${treeHeight}px`;
// collapse items before dragging them
const item = this.state.treeData.items[itemId];
if (item.children && item.children.length > 0) {
if (item.isExpanded) {
this.onCollapse(itemId);
}
}
}
onDragEnd = (source, destination) => {
this.treeElement.style.height = "";
const tree = this.state.treeData;
if (!destination) return;
const taskId = tree.items[source.parentId].children[source.index];
const newTree = moveItemOnTree(tree, source, destination);
this.setState({ treeData: newTree });
sendTaskMovement(taskId, destination.index, destination.parentId);
}
onExpand = (itemId) => {
const treeData = this.state.treeData;
network.patch(`/tasks/${itemId}.json`, {id: itemId, is_expanded: true});
this.setState({
treeData: mutateTree(treeData, itemId, { isExpanded: true }),
});
}
onCollapse = (itemId) => {
const treeData = this.state.treeData;
network.patch(`/tasks/${itemId}.json`, {id: itemId, is_expanded: false});
this.setState({
treeData: mutateTree(treeData, itemId, { isExpanded: false }),
});
}
setHiddenOnTasks = () => { // Go through all tasks and mark the appropriate ones (and their children) as hidden
const treeData = clone(this.state.treeData);
// first go through and unhide everything
Object.entries(treeData.items).forEach(([key, item]) => {
if (key === "root") return;
treeData.items[key].hidden = false;
});
if (this.props.completedTasksVisible === false) {
Object.entries(treeData.items).forEach(([key, item]) => {
if (key === "root") return;
if (item.data && item.data.completed === true) {
treeData.items[key].hidden = true;
this.hideSubtasks(treeData, item);
}
});
}
this.setState({treeData});
}
hideSubtasks = (treeData, parent) => { // Recursively hide all the children of a parent task
const childIds = parent.children;
Object.entries(treeData.items).forEach(([key, item]) => {
if (childIds.includes(Number(item.id))) { // item is a child of the parent
item.hidden = true;
this.hideSubtasks(treeData, item);
}
})
}
showAddSubtask = (item, event) => {
const newState = update(this.state, {
treeData: {items: {[item.id]: {data: {addSubtaskHere: {$set: !item.data.addSubtaskHere}}}}},
});
this.setState(newState);
// Focus the Add Subtask field after showing it
if (!item.data.addSubtaskHere) {
event.persist();
window.setTimeout(function() {
event.target.closest('.tree-node').querySelector('.add-subtask').focus();
}, 15)
}
}
updateAncestors = (parentId, property, change, delay) => {
if (!parentId) return false;
var that = this;
window.setTimeout(function() {
that.setState(state => {
return update(state, {
treeData: {items: {[parentId]: {data: {[property]: {$apply: value => value + change}}}}}
})
})
const grandparentId = that.getParentId(parentId);
if (grandparentId) that.updateAncestors(grandparentId, property, change, delay);
}, delay)
}
toggleTaskBlock = (thisTaskId, targetTaskId, relationship) => {
thisTaskId = Number(thisTaskId);
targetTaskId = Number(targetTaskId);
const index = this.state.treeData.items[targetTaskId].data[relationship].indexOf(thisTaskId);
if (index > -1) { // blocking relationship found
// remove thisTaskId from targetTaskId's relationship array
this.setState(state => {
return update(state, {
treeData: {items: {[targetTaskId]: {data: {[relationship]: {$splice: [[index, 1]] }}}}}
})
})
} else {
// add thisTaskId to targetTaskId's relationship array
this.setState(state => {
return update(state, {
treeData: {items: {[targetTaskId]: {data: {[relationship]: {$push: [thisTaskId] }}}}}
})
})
}
}
// EVENTS
componentDidMount() {
const outline = document.getElementsByClassName('outline')[0];
const tree = outline.firstChild;
this.treeElement = tree;
this.setHiddenOnTasks();
document.addEventListener('toggleCompletedTasksVisible', () => {
window.setTimeout(() => { this.setHiddenOnTasks() }, 10);
});
taskUpdates.subscribe(event => {
if (event.detail.from != "outline") { // prevent us from receiving our own broadcasts
// A task has been completed elsewhere. Update it in the outline.
const task = event.detail.task;
this.checkboxChange(task, false);
}
});
}
componentWillUnmount() {
taskUpdates.unsubscribe();
}
// RENDERING
renderTreeItem = ({item, provided, snapshot, onExpand, onCollapse}) => {
const icon = this.getIcon(item, onExpand, onCollapse);
const addSubtaskIsHere = item.data.addSubtaskHere;
const addSubtaskField = <form className="subtask-adder" onSubmit={() => {this.addSubtask(event, item.data)}}>
<input type="text" className="add-subtask" placeholder="Add subtask" value={item.data.newSubtaskName} onChange={(event) => { this.handleNewSubtaskEdit(event, item) }} />
<button>Add</button>
</form>
if (item.hidden === true) return <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} data-item-number={item.id}></div>;
return <div className="tree-node" ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} data-item-number={item.id}>
{icon}
<FrontSideTask task={item.data} disableDescendantCount={true} checkboxChange={this.checkboxChange} />
<div className="outline-task-actions">
<button title="Add subtask" className="add-subtask-button" onClick={event => {this.showAddSubtask(item, event)}}><Icon.Plus size="16"/></button>
<button title="Delete" className="delete-task-button" onClick={event => {this.deleteTask(item.data)}}><Icon.Trash2 size="16"/></button>
</div>
{ addSubtaskIsHere ? addSubtaskField : null}
</div>
}
render() {
return <div className="outline">
<Tree
tree={this.state.treeData}
renderItem={this.renderTreeItem}
offsetPerLevel={23}
onDragStart={this.onDragStart}
onDragEnd={this.onDragEnd}
onExpand={this.onExpand}
onCollapse={this.onCollapse}
isDragEnabled
isNestingEnabled
/>
<form className="task-adder" onSubmit={this.addNewTask} >
<input type="text" placeholder={this.props.parentId ? "Add subtask" : "New task"} value={this.state.new_task_name} onChange={this.handleAddNewTaskEdit} />
<button>Add</button>
</form>
</div>
}
}