-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhistory.js
508 lines (430 loc) · 13.7 KB
/
history.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
/*
properties of a history object:
id : unique identifier, generates via newHistID
type
A : ADD
D : DELETE
M : MOVE, ?
E : EDIT, ?
state: {T:T,S:S} of a view where it happened
timestamp: timestamp of that action
node_ids: ids of node objects under said action in history
oldValues : for MOVE and EDIT events old values of specified parameters
( are stored in _HISTORY )
newValues : for reverting aand going forward again
nodes : for Actions, nodes to be created
newValues : for Actions, new Values of MOVE/EDIT events
(get converted to _HISTORY notation of oldValues via processAction)
*/
const btnUndo = _('#btnUndo');
const btnRedo = _('#btnRedo');
const btnHistoryStatus = _('#btnHistoryStatus');
const historyContainer = _('#historyContainer');
let _HISTORY = null;
let _HISTORY_Map = new Map();
let _HISTORY_j_Map = new Map();
let _HISTORY_CURRENT_ID = null; // ID of the last applied history action
function genHistIDMap () {
_HISTORY_Map = new Map(_HISTORY.map(h => [h.id, h]));
_HISTORY_Map.set(null, null);
_HISTORY_j_Map = new Map([...Array(_HISTORY.length).keys()].map(j => [_HISTORY[j].id, j]));
_HISTORY_j_Map.set(null, -1);
}
function getHistory (id) {
return _HISTORY_Map.get(id);
}
function lastHistoryID () {
return _HISTORY.length > 0 ? _HISTORY[_HISTORY.length - 1].id : null;
}
function newHistID (id = null) {
return newID(id || 'h', getHistory);
}
function getAllHistoryProps(h){
const R = [];
h.oldValues.forEach( vs => {
Object.keys(vs).forEach( prop => {
R.push(prop);
})
})
return R;
}
function processAction (A) {
// h = resulting history event
const h = { type: A.type };
switch (h.type) {
case 'A':
// ADD
let doms = [];
if('node_ids' in A){
// just de-delete them, ok?
h.node_ids = A.node_ids.slice();
h.node_ids.forEach( id => {
idNode(id).deleted = false;
})
}else{
h.node_ids = A.nodes.map(function (node) {
doms.push(newNode(node, false));
return node.id;
});
}
// selectNode(doms);
break;
case 'D':
// delete
h.node_ids = A.node_ids.slice();
h.node_ids.forEach(n_id => {
idNode(n_id).deleted = true;
});
break;
case 'M':
// move and edit are basically the same
case 'E':
// edit
h.node_ids = A.node_ids.slice();
h.oldValues = [];
// h.newValues = [];
let anythingChanged = false;
const allProps = [];
for (let j = 0; j < h.node_ids.length; j++) {
const tnode = idNode(h.node_ids[j]);
const oldValues = {};
const newValues = {};
Object.keys(A.newValues[j]).forEach(prop => {
newValues[prop] = A.newValues[j][prop];
if(prop.indexOf('.')>0){
oldValues[prop] = ('oldValues' in A)?A.oldValues[j][prop]:dotProp(tnode,prop);
setDotProp(tnode, prop, newValues[prop]);
}else{
oldValues[prop] = ('oldValues' in A)?A.oldValues[j][prop]:tnode[prop];
tnode[prop] = newValues[prop];
}
if(oldValues[prop] != newValues[prop]){
anythingChanged = true;
}
allProps.push(prop);
});
h.oldValues.push(oldValues);
// h.newValues.push(newValues);
}
if (h.type === 'E'){
// really redraw nodes
h.node_ids.forEach( id => { newNode(idNode(id).dom, false); } );
}
if(!anythingChanged){
return null;
}
if (_HISTORY.length > 0) {
const lh = _HISTORY[_HISTORY.length - 1];
if (lh.type == h.type) {
if (h.node_ids.length == lh.node_ids.length) {
if(equalSetsOfItems(h.node_ids, lh.node_ids)) {
if (equalSetsOfItems(allProps, getAllHistoryProps(lh))) {
// same action basically,
// +old Values stay the same, new ones - already applied.
return null;
}
}
}
}
}
break;
default:
throw Error('processAction error: What type of history is [' + h.type + '] ??!');
break;
}
return h;
}
function applyAction (A) {
/*
* Applies Action A and saves it in _HISTORY
*
*
*/
log('applyAction');
log(JSON.stringify(A));
// if we are not at the end of _HISTORY, clear all after
if (_HISTORY_CURRENT_ID !== lastHistoryID()) {
_HISTORY = _HISTORY.slice(0, _HISTORY_j_Map.get(_HISTORY_CURRENT_ID) + 1);
}
// do the actual thing, make proper _HISTORY event
const h = processAction(A);
if(h !== null){
redraw();
h.id = newHistID();
h.timestamp = now();
// TODO: probably calculate state based on action itself?
h.state = currentState();
// add to _HISTORY and to indices
_HISTORY.push(h);
_HISTORY_CURRENT_ID = h.id;
_HISTORY_Map.set(h.id, h);
_HISTORY_j_Map.set(h.id, _HISTORY.length - 1);
// save?
_localStorage.save(h.node_ids);
fillHistoryList();
updateUndoRedoEnabled();
}else{
// nothing changed!
log('no changes')
}
return h;
}
function revertHistory (id) {
/*
*
* Reverts back specified history object
* situation is supposed to be congruent with history
*
*/
// get history object
let h = id.hasOwnProperty('id') ? id:_HISTORY_Map.get(id);
switch (h.type) {
case 'A':
// ADD
// => delete
h.node_ids.forEach(n_id => {
idNode(n_id).deleted = true;
});
break;
case 'D':
// delete
// => un-delete ;)
h.node_ids.forEach(n_id => {
idNode(n_id).deleted = false;
});
break;
case 'M':
// move
// edit but with a fancy name hence no break
case 'E':
// edit
log('reverting EDIT');
h.newValues = [];
for (let j = 0; j < h.node_ids.length; j++) {
const tnode = idNode(h.node_ids[j]);
const newValues = {};
log(' node ' + idNode(h.node_ids[j]).id);
for (let prop of Object.keys(h.oldValues[j])) {
log(' prop ' + prop);
if(prop.indexOf('.')>0){
// like style.color
newValues[prop] = dotProp(tnode,prop);
setDotProp(tnode, prop, h.oldValues[j][prop]);
}else{
newValues[prop] = tnode[prop];
tnode[prop] = h.oldValues[j][prop];
}
log(' -> ' + newValues[prop]);
}
h.newValues.push(newValues);
}
// sometimes an Update just won't cut it
h.node_ids.forEach( id => { newNode(idNode(id).dom); } );
break;
default:
throw Error('revertHistory error: What type of history is [' + h.type + '] ??!');
break;
}
}
function goBackInHistory () {
log('goBackInHstory');
let nowj = _HISTORY_j_Map.get(_HISTORY_CURRENT_ID);
log('current nowj=' + nowj);
if (nowj === -1) {
// before the first one : impossible!
return 0;
}
revertHistory(_HISTORY[nowj]);
gotoState(_HISTORY[nowj].state);
nowj--;
_HISTORY_CURRENT_ID = nowj >= 0 ? _HISTORY[nowj].id:null;
log('nowj=' + nowj);
log('_HISTORY_CURRENT_ID=' + _HISTORY_CURRENT_ID);
}
function goForwardInHistory () {
log('goForwardInHistory');
let nowj = _HISTORY_j_Map.get(_HISTORY_CURRENT_ID);
log('current nowj=' + nowj);
if (nowj === _HISTORY.length - 1) {
// after the last one : impossible!
return 0;
}
nowj++;
processAction(_HISTORY[nowj]);
gotoState(_HISTORY[nowj].state);
_HISTORY_CURRENT_ID = _HISTORY[nowj].id;
log('nowj=' + nowj);
log('_HISTORY_CURRENT_ID=' + _HISTORY_CURRENT_ID);
}
function clearAllHistory() {
_HISTORY = [];
_HISTORY_CURRENT_ID = null;
// delete the deleted nodes ;)
_NODES = _NODES.filter(n => ((!('deleted' in n)) || (n.deleted == false)))
genHistIDMap();
fillHistoryList();
}
// :::::::: ::::::::::: ::: ::::::::: ::::::::::: ::: ::: :::::::::
// :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
// +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
// +#++:++#++ +#+ +#++:++#++: +#++:++#: +#+ +#+ +:+ +#++:++#+
// +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+
// #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+#
// ######## ### ### ### ### ### ### ######## ###
if (localStorage['noteplace.history'] !== undefined) {
try {
_HISTORY = JSON.parse(localStorage['noteplace.history']);
}catch (e) {
_HISTORY = null;
}
}
_HISTORY = _HISTORY || [
// { id: '0', type: 'A', state: { T: [0, 0], S: 1 }, timestamp: 1620040025793, node_ids: ['0', '1'] },
// { id: '1', type: 'D', state: { T: [0, 0], S: 1 }, timestamp: 1620040305793, node_ids: ['1'] },
// { id: '2', type: 'M', state: { T: [0, 0], S: 1 }, timestamp: 1620044005793, node_ids: ['0'], oldValues: [{ x: -100, y: -100 }] },
// { id: '3', type: 'E', state: { T: [-200, -200], S: 0.6 }, timestamp: 1620050025793, node_ids: ['0'], oldValues: [{ rotate: -0.3 }] }
];
genHistIDMap();
if (localStorage['noteplace.history_current'] !== undefined) {
if (getHistory(localStorage['noteplace.history_current'])) {
_HISTORY_CURRENT_ID = localStorage['noteplace.history_current'];
}else {
_HISTORY_CURRENT_ID = null;
}
}
_HISTORY_CURRENT_ID = _HISTORY_CURRENT_ID || lastHistoryID();
function updateUndoRedoEnabled(){
btnUndo.disabled = (_HISTORY_CURRENT_ID === null);
btnRedo.disabled = (_HISTORY_CURRENT_ID === lastHistoryID());
}
btnUndo.onclick = function(e) {
goBackInHistory();
updateUndoRedoEnabled();
fillHistoryList();
}
btnRedo.onclick = function(e) {
goForwardInHistory();
updateUndoRedoEnabled();
fillHistoryList();
}
function fillHistoryList () {
console.log("idNode");
console.log(idNode);
historyContainer.innerHTML = '';
const nowDate = new Date();
for( let j=_HISTORY.length-1 ; j>=0 ; j-- ){
const h = _HISTORY[j];
const date = new Date(h.timestamp);
const isToday = nowDate.toLocaleDateString() == date.toLocaleDateString();
// no need for date if it was today
let datestr = isToday ? date.toLocaleTimeString() : date.toLocaleString();
datestr = datestr.replaceAll(' ',' ');
let actionStr = '';
if (h.type === 'A') {
actionStr = '<i class="bi-file-earmark-plus" title="Added"></i>';
}else if(h.type === 'D'){
actionStr = '<i class="bi-file-earmark-x" title="Deleted"></i>';
}else if(h.type === 'M'){
actionStr = '<i class="bi-arrows-move" title="Moved"></i>';
}else if(h.type === 'E'){
actionStr = '<i class="bi-pencil" title="Edited"></i>';
}
let nodeStr = '';
if(h.node_ids.length > 1) {
nodeStr = h.node_ids.length + ' node' + (h.node_ids.length>1?'s':'') ;
} else {
var temp = idNode(h.node_ids[0]);
if(temp) {
nodeStr = temp.text.split('\n')[0];
}else{
nodeStr = '???';
console.error('No node with id=',h.node_ids[0])
}
}
let allstr = datestr + ' ' + actionStr + ' ' + nodeStr;
const nodePreview = _ce('div'
,'className', 'np-h-r-c'
,'innerHTML', allstr
)
const row = _ce('div'
,'className','row btn btn-outline-' + ( h.id == _HISTORY_CURRENT_ID ? 'primary' : 'secondary')
,'onmouseenter', function (e) {
const _h_id = this.dataset['histodyID'];
previewState(getHistory(_h_id).state);
}
,'onmouseleave', function (e) {
exitPreview();
}
,'onclick', function (e) {
const _h_id = this.dataset['histodyID'];
const clickJ = _HISTORY_j_Map.get(_h_id);
const nowJ = _HISTORY_j_Map.get(_HISTORY_CURRENT_ID);
let goBtn = btnUndo;
if(nowJ < clickJ){
goBtn = btnRedo;
}
while(_HISTORY_CURRENT_ID !== _h_id){
goBtn.click();
}
}
);
row.dataset['histodyID'] = h.id;
row.appendChild(nodePreview);
// log(allstr);
historyContainer.appendChild(row);
}
// start row
const row = _ce('div'
,'className','row btn btn-outline-' + ( null == _HISTORY_CURRENT_ID ? 'primary' : 'secondary')
,'innerHTML','T = 0 , all STARTED'
,'onmouseenter', function (e) {
_HISTORY.length > 0 ? previewState(_HISTORY[0].state) : '';
}
,'onmouseleave', function (e) {
_HISTORY.length > 0 ? exitPreview() : '';
}
,'onclick', function (e) {
while(_HISTORY_CURRENT_ID !== null){
btnUndo.click();
}
}
);
historyContainer.appendChild(row);
// history status : how many changes, when it all started, ..
let html = '<i class="bi-calendar2"></i>';
let title = 'No history';
if(_HISTORY.length > 0) {
let sameDay = false;
if( (new Date(_HISTORY[0].timestamp)).toLocaleDateString
== (new Date()).toLocaleDateString ) {
// same day
sameDay = true;
html = '<i class="bi-calendar2-event"></i>';
} else if ( ( now() - _HISTORY[0].timestamp ) < 24 * 3600 * 7 * 1000 ) {
// same week
html = '<i class="bi-calendar2-week"></i>';
} else {
html = '<i class="bi-calendar2-minus"></i>';
}
const firstDate = (new Date(_HISTORY[0].timestamp));
const lastHistDate = new Date(_HISTORY[_HISTORY.length - 1].timestamp);
title = _HISTORY.length + ' event'
+ ( (_HISTORY.length > 1) ? 's' : '')
+ ', ' + ( sameDay
? firstDate.toLocaleDateString() + ', from ' + firstDate.toLocaleTimeString()
: 'from ' + firstDate.toLocaleString()
)
+ ' to ' + ( sameDay ? lastHistDate.toLocaleTimeString() : lastHistDate.toLocaleString() )
}
btnHistoryStatus.innerHTML = html;
btnHistoryStatus.title = title;
}
_('#btnHistoryClear').onclick = function () {
showModalYesNo(
'Really?',
'Are you sure you want to delete all <b>History</b>?',
function () {
clearAllHistory();
}
)
}