-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
565 lines (521 loc) · 21.6 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
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
//
//
// Models
//
//
let newNodeParent,
plane = document.getElementById('plane'),
dragObject = {},
styleLine = {
},
Base = function() {
// объект базы
//
let instanse = this;
this.tree = {
root: {
name: 'root',
description: 'Задачи',
type: 'root'
}
};
this.undoArr = [];
this.redoArr = [];
// отправка данных на сервер.
this.sendAjax = (data) => {
$.post(
'send.php', {
submit: data
},
function(resp) {
console.log('Save successful', resp);
}
)
};
this.sendFetch = (data) => {
fetch('send.php', {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin",
mode: 'cors'
})
.then(res => {
res.text().then(text => {
console.log('Save successful', text);
})
});
};
// получение данных с сервера.
this.updateAjax = (parse, convert) => {
let that = this;
$.post(
'update.php', '',
function(data) {
that.tree = convert(parse(data));
drawing.drawList();
}
)
};
// получение данных с сервера.
this.updateFetch = (parse, convert) => {
let that = this;
fetch('update.php', {
mode: 'cors',
headers: {
'content-type': 'application/json;charset=UTF-8'
}
})
.then(res => {
res.json().then(data => {
that.tree = convert(data);
drawing.drawList();
});
})
};
this.undo = () => {
this.redoArr.push(this.parsingToJSON());
this.tree = this.convertToNodes(this.parsingFromJSON(this.undoArr.splice(this.undoArr.length - 1, 1)[0]));
};
this.redo = () => {
this.undoArr.push(this.parsingToJSON());
this.tree = this.convertToNodes(this.parsingFromJSON(this.redoArr.splice(this.redoArr.length - 1, 1)[0]));
};
// работа с базой
this.getProperty = (name, property) => {
let node = base.findNode(name);
if (!node || node[property] === undefined || typeof node[property] === 'object') {
console.error('Invalid arguments');
return null;
}
return node[property];
}
this.setProperty = (name, property, value) => {
let node = base.findNode(name);
if (!node || typeof node[property] === 'object' || node[property] === undefined || value === '') {
console.error('Invalid arguments');
return null;
}
// не забываем менять запись у родителя
if (property === 'name') {
if (base.findNode(value)) return null;
let parent = base.findNode(node.parent),
previousName = node.name;
parent[value] = node;
delete parent[previousName];
for (let item in node) {
if (typeof node[item] !== 'object') continue;
node[item].parent = value;
}
}
node[property] = value;
return node[property];
}
this.move = (point, to) => {
let node = base.findNode(point),
parentNode = node ? base.findNode(node.parent) : {},
toNode = base.findNode(to);
if (!node || !toNode || parentNode === toNode) return null;
node.parent = to;
if (toNode instanceof SubPoint) this.changeRole(to, 'MainPoint');
toNode[point] = node;
delete parentNode[point];
return node;
}
this.save = (data = this.tree, upload = this.uploadTest, parse = this.parsingToJSON) => {
return upload(parse(data));
}
this.parsingToJSON = (data = this.tree) => {
return JSON.stringify(data).replace(/"/g, '\"');
}
this.open = (download = this.downloadTest) => {
let data = download();
}
this.convertToNodes = (data = this.tree) => {
for (item in data) {
if (typeof data[item] === 'object') this.convertToNodes(data[item]);
}
if (data === this.tree) return data;
if (data.type === 'MainPoint') data.__proto__ = MainPoint.prototype;
else if (data.type === 'SubPoint') data.__proto__ = SubPoint.prototype;
return data;
}
this.downloadServer = (parse = this.parsingFromJSON, convert = this.convertToNodes, update = this.updateFetch) => {
return update(parse, convert);
}
this.downloadTest = (parse = this.parsingFromJSON, convert = this.convertToNodes) => {
let nodeDraw = new MainPoint('Node_Draw', 'root', 'Разработать TODO-лист'),
nodeDraw2 = new MainPoint('Node_Draw_2', 'Node_Draw', 'Создать надёжную расширяемую модель'),
nodeDraw1 = new MainPoint('Node_Draw_1', 'Node_Draw', 'Создать интерфейс (отображение)'),
nodeDraw1_2 = new MainPoint('Node_Draw_1_2', 'Node_Draw_1', 'Реализовать блоковое построение списка'),
nodeDrawLeaf1 = new SubPoint('Node_Draw_leaf1', 'Node_Draw_1_2', 'Сделать создание листовых задач'),
nodeDrawLeaf2 = new SubPoint('Node_Draw_leaf2', 'Node_Draw_1_2', 'Сделать создание узловых задач'),
nodeDraw3 = new MainPoint('Node_Draw_3', 'Node_Draw', 'Покрыть тестами'),
nodeDraw4 = new MainPoint('Node_Draw_4', 'Node_Draw', 'Создать интерфейс (редактирование)'),
nodeDraw4_1 = new SubPoint('Node_Draw_4_1', 'Node_Draw_4', 'Реализовать удаление'),
nodeDraw4_2 = new MainPoint('Node_Draw_4_2', 'Node_Draw_4', 'Реализовать редактирование'),
nodeDraw5_1 = new MainPoint('Node_Draw_5_1', 'Node_Draw_4_2', 'Реализовать создание'),
nodeDraw5_2 = new MainPoint('Node_Draw_5_2', 'Node_Draw_4_2', 'Реализовать изменение описания'),
nodeDraw6_1 = new MainPoint('Node_Draw_6_1', 'Node_Draw_4_2', 'Реализовать изменение структуры');
drawing.drawList();
}
this.parsingFromJSON = (data) => {
return JSON.parse(data);
}
this.uploadServer = (data, send = base.sendFetch) => {
send(data);
return data;
}
this.uploadTest = (data) => {
//
}
this.overviewDoneTree = (node = this.tree) => {
this.done = true;
for (let item in this) {
if (typeof this[item] !== 'object') continue;
else this[item].done = this.overviewDoneTree(this[item]);
if (!this[item].done) {
this.done = false;
}
}
return this.done;
}
this.findNode = (name, obj = this.tree) => {
if (obj[name]) return obj[name];
for (let item in obj) {
if (typeof obj[item] !== 'object') continue;
let res = this.findNode(name, obj[item]);
if (res) return res;
}
}
this.buildList = (data = this.tree.root) => {
let mainPoint = drawing.createLine(data);
for (let item in data) {
if (data[item] instanceof MainPoint) drawing.putIn(this.buildList(data[item]), mainPoint);
else if (data[item] instanceof SubPoint) drawing.putIn(drawing.createLine(data[item]), mainPoint);
}
return mainPoint;
}
this.changeRole = (name, newType) => {
let node = this.findNode(name);
if (!node || (newType !== 'MainPoint' && newType !== 'SubPoint') || node.type === newType) {
console.error('Invalid arguments');
return null;
}
node.type = newType;
if (newType === 'MainPoint') node.__proto__ = MainPoint.prototype;
else node.__proto__ = SubPoint.prototype;
return node;
}
Base = function() {
return instanse;
};
},
base = new Base();
function Point() {
this.name = '';
this.description = '';
this.type = '';
this.parent = '';
this.done = false;
}
Point.prototype.constructor = Point;
Point.prototype.remove = function() {
let parentNode = base.findNode(this.parent);
delete parentNode[this.name];
}
Point.prototype.overviewDoneChild = function() {
for (let item in this) {
if (typeof this[item] !== 'object') continue;
if (!this[item].done) return false;
}
return true;
}
Point.prototype.overviewDone = function() {
let parent = base.findNode(this.parent);
for (let item in parent) {
if (typeof parent[item] !== 'object') continue;
if (!parent[item].done) {
parent.done = false;
if (parent instanceof MainPoint) parent.overviewDone();
return;
}
}
parent.done = true;
if (parent instanceof MainPoint) parent.overviewDone();
}
function MainPoint(name, parent, description = '') {
if (base.findNode(name) || name === '' || parent === '' || !base.findNode(parent)) {
console.error('Invalid arguments');
return;
}
this.name = name;
this.description = description;
this.parent = parent;
this.type = 'MainPoint';
// записываем в дерево пункт
let parentNode = base.findNode(parent);
parentNode[name] = this;
}
MainPoint.prototype = new Point();
MainPoint.prototype.constructor = MainPoint;
MainPoint.prototype.countChildren = 0;
MainPoint.prototype.open = true;
MainPoint.prototype.childrens = function() {
let result = [];
for (item in this)
if (this[item] instanceof MainPoint) result.push(this[item]);
return result.length ? result : null;
};
function SubPoint(name, parent, description = '') {
if (base.findNode(name) || name === '' || parent === '' || !base.findNode(parent)) {
console.error('Invalid arguments');
return;
}
if (base.findNode(parent) instanceof SubPoint) {
base.changeRole(parent, 'MainPoint')
}
this.name = name;
this.description = description;
this.parent = parent;
this.type = 'SubPoint';
// записываем в дерево пункт
let parentNode = base.findNode(parent);
parentNode[name] = this;
}
SubPoint.prototype = new Point();
SubPoint.prototype.constructor = SubPoint;
function idFunc(str) {
return str.split('').map(item => item.charCodeAt(0)).join('');
}
//
//
// Views
//
//
let Drawing = function() {
this.createElement = (type, id, parameters) => {
if (!type || !id || !! document.getElementById(id)) {
console.error('Invalid arguments');
return null;
}
let element = document.createElement(type);
element.id = id;
for (item in parameters) {
if (typeof parameters[item] === 'object') {
element[item] = {};
for (itemIns in parameters[item]) {
element[item][itemIns] = parameters[item][itemIns];
}
} else element[item] = parameters[item]
}
return element;
}
this.createLine = (data, style = styleLine, createFunc = this.createElement) => {
if (!data || !data.name || !! document.getElementById(data.name)) {
console.error('Invalid arguments');
return null;
}
let type = data.type;
let outerBlock = createFunc('div', 'outer-of-' + data.name, {
className: data.name + ' ' + type + ' outer',
style: style.outerBlock
}),
innerBlock = createFunc('div', 'inner-of-' + data.name, {
className: data.name + ' ' + type + ' inner ',
style: style.innerBlock
}),
moveBlock = createFunc('div', 'moveBlock-of-' + data.name, {
className: data.name + ' move draggable inner ' + type,
innerHTML: '☰',
style: style.innerBlock
}),
checkboxBlock = createFunc('label', 'checkboxBlock-of-' + data.name, {
className: data.name + ' ' + type + ' custom-control custom-checkbox',
style: style.innerBlock
}),
textCheckboxBlock = createFunc('div', 'textCheckboxBlock-' + data.name, {
className: data.name + ' ' + type + ' textCheckboxBlock custom-control-label',
innerHTML: '',
style: style.innerBlock
}),
checkbox = createFunc('input', 'checkbox-of-' + data.name, {
disabled: data.type === 'MainPoint' ? (base.findNode(data.name).overviewDoneChild() ? '' : 'disable') : '',
type: 'checkbox',
checked: data.done ? 'checked' : '',
className: data.name + ' line-checkbox ' + type + ' custom-control-input',
}),
description = createFunc('div', 'description-' + data.name, {
className: data.name + ' ' + type + ' description ',
style: style.description
}),
descriptionText = createFunc('span', 'descriptionText-of-' + data.name, {
className: data.name + ' ' + type + ' descriptionText droppable',
innerHTML: data.description || '',
style: style.description
}),
descriptionInput = createFunc('input', 'descriptionInput-of-' + data.name, {
className: data.name + ' ' + type + ' descriptionInput' + (data.done ? ' done' : ''),
type: 'text',
value: data.description || '',
style: {
width: data.description.length * 11
}
}),
plus = createFunc('span', 'plus-of-' + data.name, {
className: data.name + ' plus ',
innerHTML: '+'
}),
remove = createFunc('span', 'remove-of-' + data.name, {
className: data.name + ' remove',
innerHTML: '×'
});
if (type === 'root') {
let description = createFunc('div', 'description-' + data.name, {
className: data.name + ' description droppable',
innerHTML: data.description,
style: style.description
});
this.putIn(plus, description);
this.putIn(description, innerBlock);
return this.putIn(innerBlock, outerBlock);
}
this.putIn(checkbox, checkboxBlock);
this.putIn(textCheckboxBlock, checkboxBlock);
this.putIn(moveBlock, innerBlock);
this.putIn(checkboxBlock, innerBlock);
this.putIn(descriptionInput, description);
this.putIn(descriptionText, description);
this.putIn(plus, description);
this.putIn(remove, description);
this.putIn(description, innerBlock);
return type === 'MainPoint' ? this.putIn(innerBlock, outerBlock) : innerBlock;
}
this.putIn = (element, box) => {
if (!element || !box) {
console.error('Invalid arguments');
return null;
}
box.appendChild(element);
return box;
}
this.drawList = () => {
document.getElementsByClassName('undo')[0].className = 'undo ' + (base.undoArr.length ? 'active' : 'mute');
document.getElementsByClassName('redo')[0].className = 'redo ' + (base.redoArr.length ? 'active' : 'mute');
plane = document.getElementById('plane');
plane.innerHTML = '';
this.putIn(base.buildList(), plane);
base.save();
}
},
drawing = new Drawing();
//
//
// Controllers
//
//
window.addEventListener('load', () => {
base.open();
});
plane.onclick = function(event) {
let node = base.findNode(event.target.id.split('-of-')[1]);
if (~event.target.className.indexOf('line-checkbox')) {
base.undoArr.push(base.parsingToJSON());
node.done = !node.done;
node.overviewDone();
drawing.drawList();
} else if (~event.target.className.indexOf('remove')) {
base.undoArr.push(base.parsingToJSON());
node.remove();
// для красоты))0
$('#' + (node instanceof MainPoint ? 'outer' : 'inner') + '-of-' + event.target.id.split('-of-')[1]).hide(300, function() {
drawing.drawList();
})
} else if (~event.target.className.indexOf('plus')) {
base.undoArr.push(base.parsingToJSON());
newNodeParent = node.name;
$('#newModal').modal('show');
} else if (~event.target.className.indexOf('descriptionText')) {
let input = document.getElementById('descriptionInput-of-' + event.target.id.split('-of-')[1]);
input.style.display = 'inline';
input.style.width = event.target.offsetWidth + 'px';
input.focus();
input.oninput = function() {
input.style.width = input.value.length * 9 + 16;
}
input.onblur = function() {
base.undoArr.push(base.parsingToJSON());
base.setProperty(node.name, 'description', input.value);
drawing.drawList();
event.target.style.width = input.width;
}
event.target.style.display = 'none';
}
};
document.getElementById('save').onclick = function(event, createId = idFunc) {
let val = document.getElementById('newName').value,
newNode = new SubPoint(createId(val), newNodeParent, val);
newNode.overviewDone();
drawing.drawList();
document.getElementById('newName').value = newNodeParent = '';
$('#newModal').modal('hide');
}
document.getElementsByClassName('undo')[0].onclick = function(event) {
base.undo();
drawing.drawList();
}
document.getElementsByClassName('redo')[0].onclick = function(event) {
base.redo();
drawing.drawList();
}
document.onmousedown = function(e) {
let elem = e.target.closest('.draggable');
if (e.which != 1 || !elem) return;
dragObject.elem = elem.parentNode;
dragObject.elem = !~dragObject.elem.className.indexOf('SubPoint') ? dragObject.elem.parentNode : dragObject.elem
// запомнить координаты, с которых начат перенос объекта
dragObject.downX = e.pageX;
dragObject.downY = e.pageY;
}
document.onmousemove = function(e) {
if (!dragObject.elem) return;
if (!dragObject.avatar) {
if (Math.abs(e.pageX - dragObject.downX) < 3 && Math.abs(e.pageY - dragObject.downY) < 3) return;
dragObject.avatar = dragObject.elem.cloneNode(true);
dragObject.elem.style.opacity = '0.3';
var coords = getCoords(dragObject.elem);
dragObject.shiftX = dragObject.downX - coords.left;
dragObject.shiftY = dragObject.downY - coords.top;
}
dragObject.avatar.style.zIndex = 9999; // сделать, чтобы элемент был над другими
dragObject.avatar.style.position = 'absolute';
dragObject.avatar.style.backgroundColor = 'white';
dragObject.avatar.style.opacity = '0.5';
if (dragObject.avatar.parentNode != document.body) {
document.body.appendChild(dragObject.avatar); // переместить в BODY, если надо
}
dragObject.avatar.style.left = e.pageX - dragObject.shiftX * (~dragObject.elem.className.indexOf('SubPoint') ? 1 : 2) + 'px';
dragObject.avatar.style.top = e.pageY - dragObject.shiftY + 'px';
}
document.onmouseup = function(event) {
if (!dragObject.elem) return;
dragObject.avatar.style.zIndex = -99999;
let dropableElem = document.elementFromPoint(event.clientX, event.clientY).closest('.droppable'),
draggableElem = document.elementFromPoint(event.clientX, event.clientY).closest('.draggable');
dragObject.avatar.parentNode.removeChild(dragObject.avatar);
dragObject.elem.style.opacity = '1';
if (dropableElem) {
base.move(dragObject.elem.id.split('-of-')[1], dropableElem.id.split('-of-')[1]);
drawing.drawList();
}
dragObject = {};
}
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}