-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
507 lines (478 loc) · 15.3 KB
/
Copy pathscript.js
File metadata and controls
507 lines (478 loc) · 15.3 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
// starting
document.addEventListener('DOMContentLoaded', init);
function init() {
if (init.called) return;
init.called = true;
console.log('init');
loadFromLocalStorage();
fixCanvas();
fixDraw();
dateCalc();
updateView();
}
function fixDraw() {
console.log('fixDraw');
const allNodes = nodes.get();
allNodes.forEach(node => {
nodes.update({id: node.id, shape: 'box'});
});
debouncedSaveToLocalStorage();
}
// Auxiliar tools
// Debuncing function
const debounce = (func, wait) => {
let timeout;
return function() {
const context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
};
// Function formating dates
function formatDate (date) {
console.log('formatDate');
const yyyy = date.getFullYear();
const MM = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
return `${yyyy}-${MM}-${dd}`;
}
//Function long formating dates
function formatLongDate (date) {
console.log('formatLongDate');
const shortDate = formatDate(date);
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
const ss = String(date.getSeconds()).padStart(2, '0');
return shortDate+`--${hh}-${mm}-${ss}`;
}
// Function to add days to a date
function addDays(date, days) {
console.log('addDays');
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Dating variables
const today = new Date();
const getTodayDate = () => formatDate(today);
const getTodayLongDate = () => formatLongDate(today);
// Building the view
// HTML references
const container = document.getElementById('mynetwork');
const filterContainer = document.getElementById('filterContainer');
const filterTagsContainer = document.getElementById('filterTagsContainer');
const updateToday = document.getElementById('updateToday');
const optimizeDates = document.getElementById('optimizeDates');
const detailContainer = document.getElementById('detailContainer');
const labelInput = document.getElementById('labelInput');
const dateInput = document.getElementById('dateInput');
const cdateInput = document.getElementById('cdateInput');
const timeInput = document.getElementById('timeInput');
const descriptionInput = document.getElementById('descriptionInput');
const saveDetailButton = document.getElementById('saveDetailButton');
const tagInput = document.getElementById('tagInput');
const addTagButton = document.getElementById('addTagButton');
const tagsList = document.getElementById('tagsList');
const exportButton = document.getElementById('exportButton');
const importButton = document.getElementById('importButton');
// Creating a network
const nodes = new vis.DataSet([
{id: 1, label: 'Node 1\n2025-01-01\n0d', date: '2025-01-01', cdate: '', time: '3',description: 'Descripción del Nodo 1', tags: ['tag1']},
{id: 2, label: 'Node 2\n2025-02-01\n40d', date: '2025-02-01', cdate: '', time: '40', description: 'Descripción del Nodo 2', tags: ['tag2']},
{id: 3, label: 'Node 3\n2025-03-01\n0d', date: '2025-03-01', cdate: '', time: '0', description: 'Descripción del Nodo 3', tags: ['tag3']},
{id: 4, label: 'Node 4\n2025-04-01\n10d', date: '2025-04-01', cdate: '', time: '10', description: 'Descripción del Nodo 4', tags: ['tag4']},
{id: 5, label: 'Node 5\n2025-05-01\n0d', date: '2025-05-01', cdate: '', time: '0', description: 'Descripción del Nodo 5', tags: ['tag5']}
]);
const edges = new vis.DataSet([
{from: 1, to: 3, arrows: 'to'},
{from: 1, to: 2, arrows: 'to'},
{from: 2, to: 4, arrows: 'to'},
{from: 2, to: 5, arrows: 'to'},
{from: 4, to: 5, arrows: 'to'}
]);
const data = { nodes, edges };
const options = {
interaction: {
hover: false,
multiselect: true,
dragView: true,
selectable: true,
selectConnectedEdges: false,
},
manipulation: {
enabled: true,
addNode: function (data, callback) {
console.log('addNode');
data.label = `Nuevo objetivo\n${getTodayDate()}\n0d`;
data.date = getTodayDate();
data.cdate = '';
data.time = '0';
data.description = '';
data.tags = [];
callback(data);
dateCalc();
updateView();
},
addEdge: function (data, callback) {
console.log('addEdge');
if (data.from !== data.to) {
data.arrows = 'to';
callback(data);
dateCalc();
updateView();
}
}
},
physics: {
enabled: false,
},
nodes: { shape: 'box' },
edges: {
smooth: {
type: 'continuous',
forceDirection: 'none',
roundness: 0.5
},
},
layout: { randomSeed: 3 }
};
const network = new vis.Network(container, data, options);
function fixCanvas() {
console.log('fixCanvas');
const canvas = document.getElementsByTagName('canvas')[0];
canvas.setAttribute('height', '10000');
const ctx = canvas.getContext("2d");
ctx.scale(2, 2);
}
// Updating the view
function updateView() {
console.log('updateView');
sortNodesByDate();
alertEdges();
updateTagsFilter();
debouncedSaveToLocalStorage();
}
// Function sorting nodes by date
function sortNodesByDate() {
console.log('sortNodesByDate');
const allNodes = nodes.get();
allNodes.sort((a, b) => {
const dateComparison = new Date(a.date) - new Date(b.date);
return dateComparison !== 0 ? dateComparison : b.y - a.y;
});
let xPosition = -allNodes.length * 75;
let yPosition = allNodes.length * 75;
let date = new Date(0);
let children = [];
allNodes.forEach(node => {
let newDate = new Date(node.date);
const connectedNodes = network.getConnectedNodes(node.id, 'to');
if (newDate > date) {
children = connectedNodes;
xPosition += 125;
} else {
children.push(...connectedNodes);
if (children.flat().includes(node.id)) {
xPosition += 125;
}
}
yPosition -= 75;
date = newDate;
nodes.update({ id: node.id, x: xPosition, y: yPosition });
});
}
// Function alerting impossible edges going from future to past
function alertEdges() {
console.log('alertEdges');
const allNodes = nodes.get();
const allEdges = edges.get();
allEdges.forEach(edge => {
const color= edge.color.color;
const from = edge.from;
const to = edge.to;
const nodeFrom = allNodes.find(node => node.id === from);
const nodeTo = allNodes.find(node => node.id === to);
edges.update({
id: edge.id,
color: { color: nodeFrom.date > nodeTo.date || nodeFrom.y < nodeTo.y ? "red" : `${color}` }
});
});
}
// Function calculating date
function dateCalc() {
console.log('dateCalc');
const allNodes = nodes.get();
allNodes.sort((a, b) => {
const dateComparison = new Date(a.date) - new Date(b.date);
return dateComparison !== 0 ? dateComparison : b.y - a.y;
});
allNodes.forEach(node => {
const parentsIds = network.getConnectedNodes(node.id, 'from');
const parentsNodes = nodes.get(parentsIds);
if (parentsNodes.length > 0) {
const datesFromParents = parentsNodes.map(parent => addDays(new Date(parent.date), Number(node.time)));
const newCdate = formatDate(new Date(Math.max.apply(null, datesFromParents)));
nodes.update({
id: node.id,
cdate: newCdate
});
} else {
nodes.update({
id: node.id,
cdate: node.date
});
}
const updatedNode = nodes.get(node.id);
nodes.update({
id: node.id,
font: { color: new Date(updatedNode.date) < new Date(updatedNode.cdate) ? "red" : "#343434" }
});
const criticalParents = parentsNodes.filter(parent => parent.date === formatDate(addDays(new Date(updatedNode.cdate), -Number(updatedNode.time))));
const parentsEdgesIds = network.getConnectedEdges(node.id);
const parentsEdges = edges.get(parentsEdgesIds);
parentsEdges.forEach(edge => {
edges.update({
id: edge.id,
color: { color: criticalParents.map(parent => parent.id).includes(edge.from) && new Date(updatedNode.date) < new Date(updatedNode.cdate) ? "red" : "blue" }
});
});
});
}
// Function updating box with tags to be filtered
let tagsChecked = [];
function updateTagsFilter() {
console.log('updateTagsFilter');
filterTagsContainer.innerHTML = '';
const allNodes = nodes.get();
const allTags = new Set();
allNodes.forEach(node => {
if (node.tags && Array.isArray(node.tags)) {
node.tags.forEach(tag => allTags.add(tag));
}
});
const arrayAllTags = Array.from(allTags).sort();
arrayAllTags.forEach(tag => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = tag;
checkbox.name = 'filterTag';
checkbox.value = tag;
if (tagsChecked.includes(tag)) {
checkbox.checked = true;
}
const label = document.createElement('label');
label.htmlFor = tag;
label.appendChild(document.createTextNode(tag));
const br = document.createElement('br');
filterTagsContainer.appendChild(checkbox);
filterTagsContainer.appendChild(label);
filterTagsContainer.appendChild(br);
});
}
// Working with network
// Event saving node position
network.on("dragEnd", function (params) {
if (params.nodes.length >= 1) {
console.log('dragEnd');
params.nodes.forEach(nodeId => {
const position = network.getPositions([nodeId])[nodeId];
nodes.update({ id: nodeId, x: position.x, y: position.y });
});
updateView();
}
});
// Event filtering nodes by selected tags
filterTagsContainer.addEventListener("change", function(event) {
console.log('filterTagsContainer');
const allNodes = nodes.get();
if (event.target.checked) {
tagsChecked.push(event.target.value);
} else {
tagsChecked = tagsChecked.filter(item => item !== event.target.value);
}
allNodes.forEach(node => {
nodes.update({id: node.id, shape: 'box'});
node.tags.forEach(tag => {
if (tagsChecked.includes(tag)) {
nodes.update({id: node.id, shape: 'ellipse'});
}
});
});
updateView();
});
// Event updating to today date
updateToday.addEventListener('click', function(event) {
console.log('updateToday');
const today = getTodayDate();
const allNodes = nodes.get();
allNodes.forEach(node => {
if (node.date < today) {
nodes.update({
id: node.id,
date: today,
label: `${node.label.split('\n')[0]}\n${today}\n${node.time}d`
});
}
})
dateCalc();
updateView();
});
// Event optimizing dates
optimizeDates.addEventListener('click', function(event) {
console.log('optimizeDates');
const allNodes = nodes.get();
allNodes.sort((a, b) => {
const dateComparison = new Date(a.date) - new Date(b.date);
return dateComparison !== 0 ? dateComparison : b.y - a.y;
});
allNodes.forEach(node => {
const getNode = nodes.get(node.id);
dateCalc();
nodes.update({id: getNode.id, date: getNode.cdate, label: `${getNode.label.split('\n')[0]}\n${getNode.cdate}\n${node.time}d`,});
});
updateView();
});
// Woking with details
// Event displaying node details
let selectedNodeId = null;
network.on("click", function (params) {
console.log('display detailsclick');
if (params.nodes.length === 1) {
selectedNodeId = params.nodes[0];
const node = nodes.get(selectedNodeId);
detailContainer.style.display = 'block';
labelInput.value = node.label.split('\n')[0];
dateInput.value = node.date;
dateInput.style.color = new Date(node.date) < new Date(node.cdate) ? 'red' : 'black';
cdateInput.value = node.cdate;
timeInput.value = node.time;
descriptionInput.value = node.description;
updateTagsList(node.tags);
} else {
detailContainer.style.display = 'none';
}
});
// Managing tags in node details
addTagButton.addEventListener('click', function() {
console.log('addTagButton');
if (selectedNodeId !== null) {
const tag = tagInput.value.trim();
if (tag) {
const node = nodes.get(selectedNodeId);
if (!node.tags.includes(tag)) {
node.tags.push(tag);
updateTagsList(node.tags);
tagInput.value = '';
}
}
}
});
function updateTagsList(tags) {
console.log('updateTagsList');
tagsList.innerHTML = '';
tags.forEach(tag => {
const tagElement = document.createElement('span');
tagElement.className = 'tag';
tagElement.textContent = tag;
const deleteButton = document.createElement('span');
deleteButton.className = 'delete-tag';
deleteButton.textContent = 'x';
deleteButton.addEventListener('click', function() {
console.log('deleteButton');
const node = nodes.get(selectedNodeId);
node.tags = node.tags.filter(t => t !== tag);
updateTagsList(node.tags);
});
tagElement.appendChild(deleteButton);
tagsList.appendChild(tagElement);
});
}
function getTagsFromUI() {
console.log('getTagsFromUI');
const tags = [];
tagsList.querySelectorAll('.tag').forEach(tagElement => {
tags.push(tagElement.textContent.slice(0, -1));
});
return tags;
}
// Event saving node details
saveDetailButton.addEventListener('click', function() {
console.log('saveDetailButton');
if (selectedNodeId !== null) {
const newLabel = labelInput.value;
const newDate = dateInput.value;
const newTime = timeInput.value;
const newDescription = descriptionInput.value;
const newTags = getTagsFromUI();
nodes.update({
id: selectedNodeId,
label: `${newLabel}\n${newDate}\n${newTime}d`,
date: newDate,
time: newTime,
description: newDescription,
tags: newTags
});
detailContainer.style.display = 'none';
dateCalc();
updateView();
}
});
// Managing persistence
// Loading from local Storage
function loadFromLocalStorage() {
console.log('loadFromLocalStorage');
const storedData = localStorage.getItem('graphData');
if (storedData) {
const graphData = JSON.parse(storedData);
nodes.clear();
nodes.add(graphData.nodes);
edges.clear();
edges.add(graphData.edges);
}
}
// Saving to local storage
function saveToLocalStorage() {
console.log('saveToLocalStorage');
const graphData = {
nodes: nodes.get(),
edges: edges.get()
};
localStorage.setItem('graphData', JSON.stringify(graphData));
}
const debouncedSaveToLocalStorage = debounce(saveToLocalStorage, 1000);
// Exporting datos to JSON file
exportButton.addEventListener('click', function() {
console.log('exportButton');
const graphData = {
nodes: nodes.get().map(node => {
const position = network.getPositions([node.id])[node.id];
return {...node, x: position.x, y: position.y};
}),
edges: edges.get()
};
const fileName = window.location.pathname.split('/').pop().split('.').slice(0, -1).join('.');
const blob = new Blob([JSON.stringify(graphData)], {type: 'application/json'});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `${fileName}_${getTodayLongDate()}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
// Importing data from JSON file
importButton.addEventListener('change', function(event) {
console.log('importButton');
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
console.log('reader.onload');
const graphData = JSON.parse(event.target.result);
nodes.clear();
nodes.add(graphData.nodes);
edges.clear();
edges.add(graphData.edges);
dateCalc();
updateView();
};
reader.readAsText(file);
});