/
datascribbler.js
5253 lines (4860 loc) · 251 KB
/
datascribbler.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$(document).ready(function() {
// basic state
var atoms = { // state of the current version of the document that you're viewing
'0': {
id: '0',
formula: 'list',
args: [],
type: 'list',
data: [],
isExpanded: true,
isDirty: false,
// isChanged: true,
traversedYet: false
}
};
var actionsHistory = {}; // the entire revision history of the document
var actionsHistoryPointer = -1; // id of the current display version ('action')
var maximumActionsHistoryId = -1; // the largest action id
var uiState = 'normal';
var wrapCollapsed = false; // whether long strings are truncated or not
var dataLinkIndex = {}; // a hack to help preserve expanded/collapsed state on collections a little bit (not perfect)
// column layout state - used for scrolling and animating columns (when the screen is too narrow to fit them all)
var columnFirst = 0;
var highestDepth = 0;
var previousWidth = 0;
var scrollLeftAllowed = false;
var scrollRightAllowed = false;
var timeOfLastColumnRecalculate = 0;
var inScrollAnimation = false;
var timeWhenAnimationFinishes;
var timeWhenAnimationStarts;
var scrollDirection; // 'left' or 'right'
var timeLastScrolledDragging = 0;
// other display state
var statusCenterDisplay = 0;
var tooltipHide;
var userNotices = []; // each value is object, in form: {element: $elem, when: 0}
var changeHighlight = {}; // key is atom id, value is time placed (number)
// move/dragging state
var $moveDraggingElement;
var $moveDraggingElementContainer;
var moveDraggingElementOffsetX;
var moveDraggingElementOffsetY;
var moveDraggingElementContainerOffsetX;
var moveDraggingElementContainerOffsetY;
// formula picker state
var formulaChoosingIsChange;
var formulaChoosingIsPrivate;
var formulaChoosingAtomId;
var formulaChoosingParentId;
var formulaChoosingParentPosition;
var formulaChoosingFormula;
var formulaChoosingAtomArgs;
var formulaChoosingTransformState;
// sync-related state
var isPrivate = false; // private mode - no data is sent to the server. all revision functionality still works in private mode.
var documentId = '';
var isReadOnly = false;
var readOnlyDocumentId = ''; // if we're viewing an edit document, then this is the id the server told us so we can share the link to the view-only document.
var lastTimeResetUpdateInterval = new Date().getTime(); // the update-checking interval gradually increases over time. this is the time of the last event that "resets" it to the lowest (fastest) checking interval.
var lastTimeUpdated = 0;
var inSaveCall = false;
var inUpdateCall = false;
// The basic data model:
//
// Each permanent cell is called an "atom". Every atom has an "element", which is a visual cell in the UI.
// However, some elements do not have atoms. These non-atom elements include children of calculated atoms,
// and set members. Such elements cannot be the arguments of a formula.
//
// The "formula" and "args" members are the stable attributes of an atom. They never change as the result
// of a recalculation. The "type" and "data" members are recalculated every cycle, and are volatile.
//
// For literal data, the "formula" is one of the provided formulas for literal data types, and the data itself
// is stored in "args". For computation formulas, the "args" are usually references to other atoms, but for
// a few formula types, they are also user-specified and -editable strings. For explicit (not-computed) collections,
// the args are:
// * lists - references to the children atoms
// * dictiontaries - an array of objects, in the form {key: "key", value: value} where the keys are strings and
// the values are refernences to the children atoms
// * sets - an array of explicit literal values (sets cannot hold collections, formulas, other atoms, etc.)
// data is a proprietary, ad-hoc data format that resembles JSON (but isn't quite) and stores the results of
// the calculated data and its children. all three collection types are JavaScript arrays (not objects, even dictionaries),
// with the 'collectionType' member indicating the type. "undefined" and "circular reference" are stored like:
// {specialType: "undefined"} and {specialType: "circularReference"}
// We cannot store them directly because we need to transit between JSON sometimes (to send to the server, etc.).
//
// Therefore, this application has two parallel data formats. One for the "args" portion of the atom, the other for
// the "data" portion. We have helper functions to translate between the two.
//
// This is not the only possible data model that this application could have been designed with. It has
// advantages and disadvantages. The advantage is the simplicity in the constraint that atoms cannot be created
// or destroyed via transient calculation. The disadvantage is that computed elements cannot be referenced. This
// will be regarded as unintuitive and frustrating to many users and only makes any sense if you take some time
// to digest how the data model works.
//
// Specifically, the existence of "sets" (unordered collections of unique values) as a third collection type
// significantly contributed to the complexity of this application and to its data model and implementation.
// A significant amount of logic needed extensive special casing to deal with sets, including but not only
// because of the departure from JSON. If I were to rebuild this application, I would probably no longer include sets.
//
// The basic data syncing model:
//
// This application uses a surprisingly dumb "bent pipe" model to handle real-time collaborative data syncing.
// "Bent pipe" is a reference to old communications satellites that had very little computation logic in the satellite,
// and instead simply relay radio signals from a phone to a base station, which contains all the logic.
//
// This is in contrast to much smarter communications satellites such as the Iridum network, which do extensive
// data processing on each satellite, and intelligently route data from satellite to satellite, so that a large network
// of satellites routes all of the data through a small number of base stations (which may only be within line of site
// of a small portion of the satellite network).
//
// You may be thinking that the server must do extensive processing of things like resolving document conflicts,
// and so on. In fact, the server does very little. It mainly stores incremental differences sent by the client sight-unseen,
// and sends them to other clients upon request. Document versions ("actions") have a sequential identifier. If two
// clients send an action with the same identifier, the earlier one wins, and the second is rejected. The client,
// not server, then decides what to do with it.
//
// Here is what the client decides to do when it loses in the race to save an action:
// It holds on to the unsaved changes. It then asks the server for the other user(s)'s changes. It then runs two simulations:
// One, with the remote actions performed first, and the local actions performed afterward. It serializes the state
// into a blob and holds on to it. The second simulation performs the local actions first, and the remote ones afterward.
// We look at the state blob for that one too. If the both state blobs match, then we declare the actions to be in harmony,
// and keep them. We adjust the sequential IDs of the local actions and attempt to re-save them to the server, just as if they
// had never been in conflict. (The server does not treat them any different, as the follow-up to a failed conflict, or anything
// like that.) However, if both state blobs don't match, or if we got an exception (or failures in a couple of other errors we
// check for), then the actions are regarded to be in conflict. We "accept" the remote actions (as we must, because the server
// blessed them), and discard the local actions, and display a brief note to the user that actions were in conflict and reverted.
//
// The "dumb pipe" model also means we don't validate remote user actions except as needed to prevent script injection, and
// to mitigate against errors that can happen if all users are legitimately using the UI.
//
// Because edit access to a document basically lets you clobber everything anyway, it is not considered a bug or security vulnerability
// if users can submit actions which will permanently corrupt a document.
//
// It is only considered a bug or security vulnerability if a user can inject script to another user, or edit a read-only document
// (or obtain its ID).
var atomTemplate = {
id: '',
formula: '',
args: [],
type: '',
data: null,
isExpanded: true,
isDirty: false,
// isChanged: true, // not used for now, so every code reference to isChanged is commented. may be used for re-rendering optimization in the future
traversedYet: false
};
var indentWidth = 24;
var uiStates = [
'normal',
'moveDragging',
'formulaChoosing',
'preload'
];
var types = [
'string',
'number',
'boolean',
'null',
'undefined',
'list',
'set',
'dictionary',
'circularReference'
];
var formulaNames = {
'literalString': 'string',
'literalNumber': 'number',
'literalBoolean': 'boolean',
'literalNull': 'null',
'literalUndefined': 'undefined',
'list': 'list',
'set': 'set',
'dictionary': 'dictionary'
};
var formulas = {
'noop': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: false, minArguments: 0, maxArguments: 0, allowedInSet: false, isCollection: false, description: ''},
'literalString': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: true, minArguments: 1, maxArguments: 1, allowedInSet: true, isCollection: false, description: ''},
'literalNumber': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: true, minArguments: 1, maxArguments: 1, allowedInSet: true, isCollection: false, description: ''},
'literalBoolean': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: true, minArguments: 1, maxArguments: 1, allowedInSet: true, isCollection: false, description: ''},
'literalNull': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: false, minArguments: 0, maxArguments: 0, allowedInSet: true, isCollection: false, description: ''},
'literalUndefined': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: false, minArguments: 0, maxArguments: 0, allowedInSet: true, isCollection: false, description: ''},
'list': {isComputed: false, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 0, maxArguments: undefined, allowedInSet: false, isCollection: true, description: ''},
'set': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: true, minArguments: 0, maxArguments: undefined, allowedInSet: false, isCollection: true, description: ''},
'dictionary': {isComputed: false, hasAtomArguments: false, hasNonAtomArguments: false, minArguments: 0, maxArguments: undefined, allowedInSet: false, isCollection: true, description: ''},
'jsonPath': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, promptArguments: ['', 'Query:'], atomArguments: [0], description: 'List of results from a query on an element using the JSONPath query language', promptDescription: 'JSONPath is like XPath for JSON. Uses the JSONPath Plus implementation. Some complex filter scripts (implemented using the () or ?() syntax) are disabled, for security reasons.<br/><br/><a href="https://github.com/s3u/JSONPath" target="_blank">Documentation and reference</a>'},
'generate': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 3, maxArguments: 3, allowedInSet: false, isCollection: false, promptArguments: ['', '', 'Expression formula:'], atomArguments: [0, 1], description: 'Generate a list using a loop and arbitrary expression formula (first two arguments are start value (inclusive) and end value (exclusive))', promptDescription: 'Use @ for the iteration counter. Some complex formulas are not allowed, for security reasons. When using object literals, object keys must be quoted.'},
'expression': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, promptArguments: ['', 'Expression formula:'], atomArguments: [0], description: 'Generate a list from a collection and an arbitrary expression formula', promptDescription: 'Use @ for the item value. Some complex formulas are not allowed, for security reasons. When using object literals, object keys must be quoted.'},
'expressionDual': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 3, maxArguments: 3, allowedInSet: false, isCollection: false, promptArguments: ['', '', 'Expression formula:'], atomArguments: [0, 1], description: 'Generate a list from two collections and an arbitrary expression formula', promptDescription: 'Use @ and # for the item values. Some complex formulas are not allowed, for security reasons. When using object literals, object keys must be quoted.'},
'clone': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A recursive mirror of all elements'},
'cloneShallow': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A mirror of all top-level elements, with collections empty'},
'flatten': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A recursive mirror of all elements, flattened to a one-level deep array'},
'count': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'Number of sub-elements, measured recursively'},
'smallest': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'The smallest of all number-type elements'},
'largest': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'The largest of all number-type elements'},
'mean': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'The arithmetic mean of all number-type elements'},
'median': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'The median of all number-type elements'},
'sum': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'The sum of all number-type elements; or a number added to each number-type element in a collection; or the sum of adjacent values from two collections'},
'product': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'The product of all number-type elements; or a number multiplied by each number-type element in a collection; or the product of adjacent values from two collections'},
'parseNumber': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A string converted to a number type'},
'length': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'The combined length of all string-type elements'},
'concatenate': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'All string-type elements concatenated to a single string'},
'lowercase': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'All string-type elements converted to lowercase'},
'uppercase': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'All string-type elements converted to uppercase'},
'trim': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'All string-type elements with starting and ending whitespace trimmed'},
'reverseStrings': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'All string-type elements with their characters in reverse order'},
'replace': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 3, maxArguments: 3, allowedInSet: false, isCollection: false, promptArguments: ['', 'Find:', 'Replace:'], atomArguments: [0], description: 'All string-type elements with a particular substring replaced'},
'regex': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 4, maxArguments: 4, allowedInSet: false, isCollection: false, promptArguments: ['', 'Find regular expression:', 'Regular expression flags:', 'Replace:'], atomArguments: [0], description: 'All string-type elements with a particular substring replaced using a regular expression', promptDescription: '<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" target="_blank">Regular expression reference</a>'},
'join': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, promptArguments: ['', 'Delimiter:'], atomArguments: [0], description: 'All string-type elements from a collection (non-recursive) combined to a single string with a delimiter'},
'split': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: true, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, promptArguments: ['', 'Delimiter:'], atomArguments: [0], description: 'A string-type element converted to an array based on a provided delimiter'},
'union': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'Set with combined members of both collection arguments'},
'intersection': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'Set with members that are in both collection arguments'},
'unique': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'Set with members that each occur only in one or the other collection argument, but not both. Also known as "symmetric difference".'},
'uniqueLeft': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'Set with members that are in the first argument but not the second. In set theory, the "difference" operation.'},
'uniqueRight': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 2, maxArguments: 2, allowedInSet: false, isCollection: false, description: 'Set with members that are in the second argument but not the first. In set theory, the "difference" operation.'},
'sort': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A mirror of an array, sorted'},
'reverse': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A mirror of an array, in reverse order'},
'keys': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'A set with the keys of an array or dictionary as its members'},
'values': {isComputed: true, hasAtomArguments: true, hasNonAtomArguments: false, minArguments: 1, maxArguments: 1, allowedInSet: false, isCollection: false, description: 'An array with the values of a collection as its members'}
};
var isJson = function(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
// This is a helper function to work around the limitation in $.extend that skips over "undefined" values.
// It was needed in an older version of the data model that used "undefined" literals. It turns out,
// we no longer need that workaround. However, just keeping this function in the code to avoid transplanting it.
var cloneArrayWithoutExcludingUndefined = function(array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
newArray.push(array[i]);
}
return newArray;
};
var refresh = function() {
recalculate();
render();
$.each(actionsHistory, function(i, action) {
action.traversedYet = false;
});
};
var advanceToRevision = function(n) {
$.each(actionsHistory, function(i, action) {
action.traversedYet = false;
});
return advanceToRevisionIterate(n);
}
var advanceToRevisionIterate = function(n) {
if (actionsHistory[n].traversedYet == false) {
actionsHistory[n].traversedYet = true;
} else {
}
if (actionsHistory[n].fullStateAtoms !== null) {
atoms = $.extend(true, {}, actionsHistory[n].fullStateAtoms);
$.each(atoms, function(i, atom) {
// Commented as some of the cookbook recipes intentionally have some of the collections collapsed at the start, for neatness.
// atom.isExpanded = true;
});
updateHistoryStatus(n);
recalculate();
} else {
advanceToRevisionIterate(actionsHistory[n].basedOn);
processAction(actionsHistory[n]);
}
};
var updateHistoryStatus = function(n) {
actionsHistoryPointer = n;
if (actionsHistoryPointer == maximumActionsHistoryId) {
$('.revision-current').html('Viewing latest revision');
} else {
$('.revision-current').html('Older revision – ' + $('<div>').text(actionsHistory[n].description).html());
}
};
var revisionDescription = function(n) {
var action = actionsHistory[n];
var html = '';
if (action.who) {
html += $('<div>').text(action.who.substr(0, 15)).html() + ' – ';
}
html += $('<div>').text(action.description).html() + '<br/><span style="font-size: smaller;"><em>';
var age = new Date().getTime() - action.when;
if (age < 8000) {
html += 'Just now'
}
if (age >= 8000 && age < 20000) {
html += 'A few seconds ago';
}
if (age >= 20000 && age < 60000) {
html += 'Less than 1 minute ago';
}
if (age >= 60000 && age < 120000) {
html += '1 minute ago';
}
if (age >= 120000 && age < 3600000) {
html += Math.floor(age / 60000) + ' minutes ago';
}
if (age >= 3600000 && age < 7200000) {
html += '1 hour ago';
}
if (age >= 7200000 && age < 86400000) {
html += Math.floor(age / 3600000) + ' hours ago';
}
if (age >= 86400000 && age < 172800000) {
html += '1 day ago';
}
if (age >= 172800000) {
html += Math.floor(age / 86400000) + ' days ago';
}
html += '</em></span>';
return html;
};
var actionTemplate = {
id: 0,
basedOn: -1,
fullStateAtoms: null,
who: '',
when: new Date().getTime(),
steps: [],
jumpTo: null,
jumpType: 'normal', // or 'undo' or 'redo'
description: '',
isSaved: false,
isRejected: false,
traversedYet: false
};
var stepTemplate = {
predicate: '',
atomId: '', // all predicates except 'import'
childOf: '', // 'create' and 'move'
position: '', // 'create' and 'move' (ordinal or key)
formula: '', // 'create' and 'change'
args: [], // 'create' and 'change'
atoms: [], // 'import'
columnAtoms: [] // 'import'
};
var predicateList = [
'import',
'create',
'delete',
'change',
'move',
'noop'
];
var processAction = function(action) {
var atom;
if (action.jumpTo !== null) {
advanceToRevisionIterate(action.jumpTo);
} else {
$.each(action.steps, function(stepNum, step) {
switch (step.predicate) {
case 'import':
$.each(step.atoms, function(i, importAtom) {
var newAtom = $.extend(true, {}, importAtom);
newAtom.type = '';
newAtom.data = 0;
newAtom.isDirty = false;
// newAtom.isChanged = false;
newAtom.traversedYet = false;
atoms[importAtom.id] = newAtom;
});
$.each(step.columnAtoms, function(i, columnAtomId) {
atoms['0'].args.push(columnAtomId);
});
break;
case 'create':
atom = $.extend(true, {}, atomTemplate);
atom.id = step.atomId;
atom.formula = step.formula;
atom.args = cloneArrayWithoutExcludingUndefined(step.args);
if (atoms[step.childOf].formula == 'list') {
atoms[step.childOf].args.splice(step.position, 0, step.atomId);
} else { // dictionary
atoms[step.childOf].args.push({
key: step.position,
value: step.atomId
});
atoms[step.childOf].args.sort(dictionaryCompare);
}
atoms[atom.id] = atom;
break;
case 'delete':
deleteAtom(step.atomId, true);
break;
case 'change':
atom = atoms[step.atomId];
// Changing the formula always deletes children of a list or dictionary.
// (These are the only two formula types that can have child atoms.)
if (atom.formula == 'list') {
$.each(atom.args, function(i, child) {
deleteAtom(child, false);
});
}
if (atom.formula == 'dictionary') {
$.each(atom.args, function(i, child) {
deleteAtom(child.value, false);
});
}
// Update the target atom.
atom.formula = step.formula;
atom.args = cloneArrayWithoutExcludingUndefined(step.args);
break;
case 'move':
// Find the container atom and remove the target atom.
$.each(atoms, function(i, atom) {
var found = -1;
if (atom.formula == 'list') {
$.each(atom.args, function(j, subAtom) {
if (subAtom == step.atomId) {
found = j;
}
});
if (found != -1) {
atom.args.splice(found, 1);
}
}
if (atom.formula == 'dictionary') {
$.each(atom.args, function(j, subAtom) {
if (subAtom.value == step.atomId) {
found = j;
}
});
if (found != -1) {
atom.args.splice(found, 1);
}
}
});
// Insert the target atom in the new container.
if (atoms[step.childOf].formula == 'list') {
atoms[step.childOf].args.splice(step.position, 0, step.atomId);
} else { // dictionary
atoms[step.childOf].args.push({
key: step.position,
value: step.atomId
});
atoms[step.childOf].args.sort(dictionaryCompare);
}
break;
}
assertNoAtomLoops();
});
// If uncommented, this would make every action store the entire state and basically moot the notion of incremental action steps. Simpler, but hugely memory and bandwidth inefficient.
// action.fullStateAtoms = $.extend(true, {}, atoms);
}
updateHistoryStatus(action.id);
lastTimeResetUpdateInterval = new Date().getTime();
};
var deleteAtom = function(atom, deleteFromParent) {
// Delete children.
if (atoms[atom].formula == 'list') {
$.each(atoms[atom].args, function(i, child) {
deleteAtom(child, false);
});
}
if (atoms[atom].formula == 'dictionary') {
$.each(atoms[atom].args, function(i, child) {
deleteAtom(child.value, false);
});
}
// Delete from parent.
if (deleteFromParent) {
$.each(atoms, function(i, container) {
var found = -1;
if (container.formula == 'list') {
$.each(container.args, function(j, subAtom) {
if (subAtom == atom) {
found = j;
}
});
if (found != -1) {
container.args.splice(found, 1);
}
}
if (container.formula == 'dictionary') {
$.each(container.args, function(j, subAtom) {
if (subAtom.value == atom) {
found = j;
}
});
if (found != -1) {
container.args.splice(found, 1);
}
}
});
}
// Change formulas with this atom as an argument to literalUndefined
$.each(atoms, function(id, referee) {
var refersTo = false;
if (formulas[referee.formula].hasAtomArguments && !formulas[referee.formula].hasNonAtomArguments) {
$.each(referee.args, function(i, arg) {
if (arg == atom) {
refersTo = true;
}
});
}
if (formulas[referee.formula].hasAtomArguments && formulas[referee.formula].hasNonAtomArguments && formulas[referee.formula].hasOwnProperty('atomArguments')) {
$.each(formulas[referee.formula].atomArguments, function(i, argNum) {
var arg = referee.args[argNum];
if (arg == atom) {
refersTo = true;
}
});
}
if (refersTo) {
referee.formula = 'literalUndefined';
referee.args = [];
}
});
// Delete target atom.
delete atoms[atom];
};
// Loops in atom references can only happen as a result of data conflicts--never any solely single-user actions taken through the UI.
// This function is used (within a try/catch block) when determining whether data sync conflicts can be cleanly resolved.
// It throws an exception if a loop is found.
var assertNoAtomLoops = function() {
$.each(atoms, function(i, atom) {
atom.traversedYet = false;
});
assertNoAtomLoopsIterate('0');
};
var assertNoAtomLoopsIterate = function(atomId) {
var atom = atoms[atomId];
if (atom.traversedYet) {
throw "loop";
}
atom.traversedYet = true;
if (atom.formula == 'list') {
$.each(atom.args, function(i, arg) {
assertNoAtomLoopsIterate(arg);
});
}
if (atom.formula == 'dictionary') {
$.each(atom.args, function(i, arg) {
assertNoAtomLoopsIterate(arg.value);
});
}
};
var dictionaryCompare = function(a, b) {
// sort strings numerically
if (!isNaN(a.key) && !isNaN(b.key) && a.key.search(/ /) == -1 && b.key.search(/ /) == -1) {
return (+a.key) - (+b.key);
}
// sort numeric strings before non-numeric strings
if (!isNaN(a.key) && a.key.search(/ /) == -1) {
return -1;
}
if (!isNaN(b.key) && b.key.search(/ /) == -1) {
return 1;
}
return a.key.localeCompare(b.key);
};
// When set elements are different types, sort in this order
var typeSort = {
'number': 1,
'string': 2,
'boolean': 3,
'null': 4,
'undefined': 5,
'circularReference': 6
};
var dataCompare = function(a, b) {
// sort strings numerically
if (typeof a == 'string' && typeof b == 'string' && !isNaN(a) && !isNaN(b) && a.search(/ /) == -1 && b.search(/ /) == -1) {
a = +a;
b = +b;
}
var aType = typeSort[getType(a)];
var bType = typeSort[getType(b)];
if (aType < bType) {
return -1;
}
if (bType < aType) {
return 1;
}
if (aType == 1 || aType == 3) {
return a - b;
}
if (aType == 2) {
return a.localeCompare(b);
}
return 0;
};
var recalculate = function() {
$.each(atoms, function(i, atom) {
atom.isDirty = true;
});
var anyDirty = true;
var madeProgress = false;
while (anyDirty) {
anyDirty = false;
madeProgress = false;
$.each(atoms, function(i, atom) {
if (atom.isDirty) {
recalculateAtom(atom);
if (atom.isDirty) {
anyDirty = true;
} else {
madeProgress = true;
}
}
});
if (!madeProgress) {
$.each(atoms, function(i, atom) {
if (atom.isDirty && !formulas[atom.formula].isCollection) {
atom.isDirty = false;
atom.type = 'circularReference';
atom.data = {specialType: 'circularReference'};
}
});
}
}
};
var recalculateAtom = function(atom) {
var previousType = atom.type;
var previousData = atom.data;
var args = atom.args;
var type;
var data;
var argIsDirty = false;
var argDoesntExist = false; // not checked currently, probably not necessary
if (formulas[atom.formula].hasAtomArguments && !formulas[atom.formula].hasNonAtomArguments) {
$.each(atom.args, function(i, arg) {
if (atoms.hasOwnProperty(arg)) {
if (atoms[arg].isDirty) {
argIsDirty = true;
}
} else {
argDoesntExist = true;
}
});
}
if (formulas[atom.formula].hasAtomArguments && formulas[atom.formula].hasNonAtomArguments && formulas[atom.formula].hasOwnProperty('atomArguments')) {
$.each(formulas[atom.formula].atomArguments, function(i, argNum) {
var arg = atom.args[argNum];
if (atoms.hasOwnProperty(arg)) {
if (atoms[arg].isDirty) {
argIsDirty = true;
}
} else {
argDoesntExist = true;
}
});
}
if (atom.formula == 'dictionary') {
$.each(atom.args, function(i, item) {
if (atoms[item.value].isDirty) {
argIsDirty = true;
}
});
}
if (!argIsDirty) {
var box = [undefined]; // used to pass a reference to a function generator that we can read out of later
switch (atom.formula) {
case 'literalString':
// type = 'string';
data = args[0];
break;
case 'literalNumber':
// type = 'number';
data = args[0];
break;
case 'literalBoolean':
// type = 'boolean';
data = args[0];
break;
case 'literalNull':
// type = 'null';
data = null;
break;
case 'literalUndefined':
// type = 'undefined';
data = {specialType: 'undefined'};
break;
case 'list':
// type = 'list';
data = [];
data.collectionType = 'list';
data.isExpanded = atom.isExpanded;
$.each(args, function(i, arg) {
data.push(atoms[arg].data);
});
break;
case 'set':
// type = 'set';
data = cloneArrayWithoutExcludingUndefined(args);
data.collectionType = 'set';
data.isExpanded = atom.isExpanded;
break;
case 'dictionary':
// type = 'dictionary';
data = [];
data.collectionType = 'dictionary';
data.isExpanded = atom.isExpanded;
for (var i = 0; i < args.length; i++) {
data.push({
key: args[i].key,
value: atoms[args[i].value].data
});
}
break;
case 'jsonPath':
try {
var result = JSONPath({json: exportJson(atoms[args[0]].data).json, path: args[1]});
if (result === false) {
data = [];
data.collectionType = 'list';
} else {
data = importFromJson(result);
}
} catch (e) {
if (e.message.indexOf('query not executed because filter contains possibly unsafe code') != -1) {
data = e.message.replace(/jsonPath: /, '');
} else {
data = {specialType: 'undefined'};
}
}
// type = getType(data);
break;
case 'generate':
var argStart = atoms[args[0]].data;
var argEnd = atoms[args[1]].data;
var code = args[2];
if (typeof argStart == 'number' && typeof argEnd == 'number') {
if (argEnd - argStart <= 10000) {
// this is playing with fire
if ((' ' + code).match(/[^.\'\"a-zA-Z0-9_$][a-zA-Z_$][a-zA-Z0-9]*/g) || code.match(/\.prototype/gi)) {
data = 'error: not executed because formula contains possibly unsafe code';
} else {
code = code.replace(/@/g, 'j');
var results = [];
var result;
for (var i = Math.ceil(argStart); i < argEnd; i++) {
result = undefined;
var j = i; // "security" to prevent formula from changing i
try {
result = eval('(' + code + ')');
} catch(e) {
}
results.push(result);
}
data = importFromJson(results);
}
} else {
data = 'error: number of iterations limited to 10000';
}
} else {
data = 'error: arguments are not numbers';
}
// type = getType(data);
break;
case 'expression':
data = operationExpression(args[0], undefined, args[1]);
// type = getType(data);
break;
case 'expressionDual':
data = operationExpression(args[0], args[1], args[2]);
// type = getType(data);
break;
case 'clone':
data = recalculateTraverse(atoms[args[0]].data, operationClone);
// type = getType(data);
break;
case 'cloneShallow':
data = recalculateTraverse(atoms[args[0]].data, operationClone, true);
// type = getType(data);
break;
case 'flatten':
recalculateTraverse(atoms[args[0]].data, operationFlatten(box));
data = box[0];
data.collectionType = 'list';
// type = getType(data);
break;
case 'count':
if ($.inArray(atoms[args[0]].type, ['set', 'list', 'dictionary']) != -1) {
data = atoms[args[0]].data.length;
} else {
data = 1;
}
// type = 'number';
break;
case 'smallest':
recalculateTraverse(atoms[args[0]].data, operationSmallest(box));
data = box[0];
// type = getType(data);
break;
case 'largest':
recalculateTraverse(atoms[args[0]].data, operationLargest(box));
data = box[0];
// type = getType(data);
break;
case 'mean':
recalculateTraverse(atoms[args[0]].data, operationNumbers(box));
if (box[0].length == 0) {
data = undefined;
} else {
data = 0;
$.each(box[0], function(i, v) {
data += v;
});
data /= box[0].length;
}
// type = getType(data);
break;
case 'median':
recalculateTraverse(atoms[args[0]].data, operationNumbers(box));
if (box[0].length == 0) {
data = undefined;
} else {
box[0].sort(function(a, b) { return a - b; });
if (box[0].length % 2 == 0) {
data = (box[0][box[0].length / 2 - 1] + box[0][box[0].length / 2]) / 2;
} else {
data = box[0][(box[0].length - 1) / 2];
}
}
// type = getType(data);
break;
case 'sum':
if (args.length == 1) {
recalculateTraverse(atoms[args[0]].data, operationSumAccum(box));
data = box[0];
}
if (args.length == 2) {
if ($.inArray(atoms[args[0]].type, ['list', 'dictionary', 'set']) != -1) {
if ($.inArray(atoms[args[1]].type, ['list', 'dictionary', 'set']) != -1) {
data = recalculateTraversePaired(atoms[args[0]].data, atoms[args[1]].data, operationSumPair, operationSum);
} else {
data = recalculateTraverse(atoms[args[0]].data, operationSum(atoms[args[1]].data));
}
} else {
if ($.inArray(atoms[args[1]].type, ['list', 'dictionary', 'set']) != -1) {
data = recalculateTraverse(atoms[args[1]].data, operationSum(atoms[args[0]].data));
}
}
if (atoms[args[0]].type == 'number' && atoms[args[1]].type == 'number') {
data = atoms[args[0]].data + atoms[args[1]].data;
}
if (atoms[args[0]].type == 'number' && data === undefined) {
data = atoms[args[0]].data;
}
if (atoms[args[1]].type == 'number' && data === undefined) {
data = atoms[args[1]].data;
}
}
// type = getType(data);
break;
case 'product':
if (args.length == 1) {
recalculateTraverse(atoms[args[0]].data, operationProductAccum(box));
data = box[0];
}
if (args.length == 2) {
if ($.inArray(atoms[args[0]].type, ['list', 'dictionary', 'set']) != -1) {
if ($.inArray(atoms[args[1]].type, ['list', 'dictionary', 'set']) != -1) {
data = recalculateTraversePaired(atoms[args[0]].data, atoms[args[1]].data, operationProductPair, operationProduct);
} else {
data = recalculateTraverse(atoms[args[0]].data, operationProduct(atoms[args[1]].data));
}
} else {
if ($.inArray(atoms[args[1]].type, ['list', 'dictionary', 'set']) != -1) {
data = recalculateTraverse(atoms[args[1]].data, operationProduct(atoms[args[0]].data));
}
}
if (atoms[args[0]].type == 'number' && atoms[args[1]].type == 'number') {
data = atoms[args[0]].data * atoms[args[1]].data;
}
if (atoms[args[0]].type == 'number' && data === undefined) {
data = atoms[args[0]].data;
}
if (atoms[args[1]].type == 'number' && data === undefined) {
data = atoms[args[1]].data;
}
}
// type = getType(data);
break;
case 'parseNumber':
data = recalculateTraverse(atoms[args[0]].data, operationParseNumber);
// type = getType(data);
break;
case 'length':
recalculateTraverse(atoms[args[0]].data, operationLength(box));
data = box[0];
// type = getType(data);
break;
case 'concatenate':
recalculateTraverse(atoms[args[0]].data, operationStrings(box));
data = box[0].join('');
// type = 'string';
break;
case 'lowercase':
data = recalculateTraverse(atoms[args[0]].data, operationLowercase);
// type = getType(data);
break;
case 'uppercase':
data = recalculateTraverse(atoms[args[0]].data, operationUppercase);
// type = getType(data);
break;
case 'trim':
data = recalculateTraverse(atoms[args[0]].data, operationTrim);
// type = getType(data);
break;
case 'reverseStrings':
data = recalculateTraverse(atoms[args[0]].data, operationReverseStrings);
// type = getType(data);
break;
case 'replace':
data = recalculateTraverse(atoms[args[0]].data, operationReplace(args[1], args[2]));
// type = getType(data);
break;
case 'regex':
data = recalculateTraverse(atoms[args[0]].data, operationRegex(args[1], args[2], args[3]));
// type = getType(data);
break;
case 'join':
recalculateTraverse(atoms[args[0]].data, operationStrings(box), true);
data = box[0].join(args[1]);
// type = 'string';
break;
case 'split':
if (typeof atoms[args[0]].data == 'string') {
data = atoms[args[0]].data.split(args[1]);
data.collectionType = 'list';
} else {
data = undefined;
}
// type = getType(data);
break;
case 'union':
data = calculateSetLogic(atoms[args[0]].data, atoms[args[1]].data, 2, operationUnion);
// type = getType(data);
break;
case 'intersection':
data = calculateSetLogic(atoms[args[0]].data, atoms[args[1]].data, 2, operationIntersection);
// type = getType(data);
break;
case 'unique':
if (args.length == 2) {
data = calculateSetLogic(atoms[args[0]].data, atoms[args[1]].data, 2, operationUnique);
} else {
data = calculateSetLogic(atoms[args[0]].data, undefined, 1, operationUnique);
}
// type = getType(data);
break;
case 'uniqueLeft':
data = calculateSetLogic(atoms[args[0]].data, atoms[args[1]].data, 2, operationUniqueLeft);
// type = getType(data);
break;