-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcatalyst.js
More file actions
1962 lines (1498 loc) · 59.7 KB
/
Copy pathcatalyst.js
File metadata and controls
1962 lines (1498 loc) · 59.7 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
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
"use strict";
// /" _ "\ /""\(" _ ") /""\ |" | |" \/" |/" )(" _ ")
// (: ( \___) / \)__/ \\__/ / \ || | \ \ /(: \___/ )__/ \\__/
// \/ \ /' /\ \ \\_ / /' /\ \ |: | \\ \/ \___ \ \\_ /
// // \ _ // __' \ |. | // __' \ \ |___ / / __/ \\ |. |
// (: _) \ / / \\ \\: | / / \\ \( \_|: \ / / /" \ :) \: |
// \_______)(___/ \___)\__|(___/ \___)\_______)|___/ (_______/ \__|
// Copyright (c) 2019 Soumik Chatterjee (github.com/badguppy) (soumik.chat@hotmail.com)
// MIT License
export default class Catalyst {
// ---------------------------
// CONSTRUCTOR
// ---------------------------
/**
* Creates a new state store.
* @constructor
* @param {Object} obj - The base object to create the store from.
* @param {Object[]} history - Array of history steps, recent to oldest. Obtained by historyObservers.
* @param {number} historyCurrent - The current state of the store relative to history steps. Most recent is 0.
* @param {historyFeedCB} historyFeed - Function called when Catalyst runs out of undoable steps - to be fed older history.
* @param {char} accessor - Character to be used as separation/ accessor in nested property paths.
* @returns {Object} The state store.
*/
constructor(obj, history = [], historyCurrent = 0, historyFeed, accessor = ".") {
// Check - cannot create store with array as base!
let objType = typeof obj;
if (objType != "undefined") {
if (Array.isArray(obj)) throw "Expected object, got array.";
else if (objType != "object") throw "Expected object, got value.";
}
// PREP
// ----
this.accessor = accessor; // PUBLIC:
this.resolveMode = false; // PRIVATE:
this.resolveContext = false; // PRIVATE:
this.preserveReferences = true; // PUBLIC:
this.preserveFragments = true; // PUBLIC:
// History - supports undo/redo, batched operations, aggregation!
this.history = history; // PRIVATE:
this.historyFeed = historyFeed || ((required, target, timestamp) => false); // PUBLIC:
this.historyLogger = this.logChange.bind(this); // PUBLIC:
this.historyLimit = 0; // PUBLIC: NOTE: best way to auto-prune is to use a setInterval and call prune ? Since multiple ops can trigger multiple autoprune calls! // TODO: Auto-prune might malfunction after history is fed via feed!
this.historyBatchModes = []; // PRIVATE:
this.historyDisabled = 0; // PUBLIC:
this.historyCurrent = historyCurrent; // PUBLIC:
this.historyBatched = 0; // PUBLIC:
this.historyObservers = {}; // PRIVATE:
this.batchStarter = this.batch.bind(this); // PRIVATE:
this.batchStopper = this.stopBatch.bind(this); // PRIVATE:
this.prunePending = false; // PRIVATE:
// Fragments - creates top-level-like state-chunks that preserve the reference to the main chunk.
this.fragmented = {};
this.fragments = {};
// Observer - does NOT support cascading changes to the store and can have side effects on history as they are called on undo-redo!
this.observers = {}; // PRIVATE:
this.observed = {prop: {}, child:{}, deep: {}}; // PRIVATE:
this.observerNotifier = this.notifyObservers.bind(this); // PRIVATE:
this.observeAsync = true; // PUBLIC: Whether observers are triggered asynchronously (via Promise microtask) !
this.observeDeferred = 0; // PUBLIC: Whether observations are batched together!
this.observations = { // PRIVATE:
stacks: [], // Array of maps
paths: {} // paths to stack index
};
// Interceptor - supports cascading changes to the store and are auto-batched to be atomic! They are not executed on undo/redo!
this.interceptors = {}; // PRIVATE:
this.intercepted = {prop: {}, child:{}, deep: {}}; // PRIVATE:
this.interceptorNotifier = this.notifyInterceptors.bind(this); // PRIVATE:
this.setterLevel = 0; // PRIVATE:
this.setterBatched = false; // PRIVATE:
// STORE CREATION
// ----
// Proxify and create our store
this.root = {};
this.store = this.proxify(this.root, this, "", []);
// Add the user provided object to the store - one prop at a time!
this.stopRecord();
for (var prop in obj) this.store[prop] = obj[prop];
this.record();
// CONTROLLER CREATION
// ---
// Prep catalyst controllers
let getAccessor = () => this.accessor,
getPreserveReferences = () => this.preserveReferences,
setPreserveReferences = value => this.preserveReferences = value,
getPreserveFragments = () => this.preserveFragments,
setPreserveFragments = value => this.preserveFragments = value,
getHistoryCurrent = () => this.historyCurrent,
setHistoryCurrent = index => (index >= this.historyCurrent ? (index == this.historyCurrent ? false : this.undo(index - this.historyCurrent)) : this.redo(this.historyCurrent - index)),
getHistoryLimit = () => this.historyLimit,
setHistoryLimit = limit => { this.historyLimit = limit; this.prune(); },
getHistory = () => this.history,
getHistoryFeed = () => this.historyFeed,
setHistoryFeed = fn => this.historyFeed = fn,
getHistoryDisabled = () => this.historyDisabled,
setHistoryDisabled = value => {
if (typeof value == "number") {
if (value < 0) value = 0;
this.historyDisabled = value;
}
else if (value) this.historyDisabled = this.historyDisabled || 1;
else this.historyDisabled = 0;
},
getHistoryBatched = () => this.historyBatched,
setHistoryBatched = value => {
if (typeof value == "number") {
if (value > this.historyBatched) {
if (this.historyBatched == 0) this.batch();
}
else if (value < this.historyBatched) {
if (value < 0) value = 0;
if (this.historyBatched > 0)
while (this.historyBatched > value)
this.stopBatch();
}
}
else if (value) {
if (!this.historyBatched) this.batch();
}
else {
if (this.historyBatched)
while (this.historyBatched > 0)
this.stopBatch();
}
},
getHistoryBatchModes = () => this.historyBatchModes,
getObserveAsync = () => this.observeAsync,
setObserveAsync = value => this.observeAsync = value,
getObserveDeffered = () => this.observeDeferred,
setObserveDeffered = value => {
if (typeof value == "number") {
if (value > this.observeDeffered) {
if (this.observeDeffered == 0) this.deferObservers();
}
else if (value < this.observeDeffered) {
if (value < 0) value = 0;
if (this.observeDeffered > 0)
while (this.observeDeffered > value)
this.resumeObservers();
}
}
else if (value) {
if (!this.observeDeffered) this.deferObservers();
}
else {
if (this.observeDeffered)
while (this.observeDeffered > 0)
this.resumeObservers();
}
},
getStore = () => this.store,
getIsFragment = function(pathOrObject) {
if (typeof pathOrObject == "undefined") return 0;
else if (typeof pathOrObject == "object") return this.isFragment(pathOrObject);
else if (typeof pathOrObject == "string") return this.isFragment(pathOrObject);
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
};
// TODO: write parsable comments on functions and purpose of variables - also mark if they are to be used by user or internal only!
// TODO: must have ability to add functions to the store! like ToJSON etc. Esp to areas not recorded ! - WONT work as it will stop recording due to use of JSON in history creation!
// TODO: ObserveAsync is not working - always sync!
// Access to controllers
this.catalyst = {
get accessor() { return getAccessor(); },
get preserveReferences() { return getPreserveReferences(); },
set preserveReferences(value) { setPreserveReferences(value); },
get preserveFragments() { return getPreserveFragments(); },
set preserveFragments(value) { setPreserveFragments(value); },
record: this.record.bind(this),
stopRecord: this.stopRecord.bind(this),
batch: this.batch.bind(this),
stopBatch: this.stopBatch.bind(this),
undo: this.undo.bind(this),
redo: this.redo.bind(this),
commit: this.commit.bind(this),
prune: this.prune.bind(this),
observeHistory: this.observeHistory.bind(this),
stopObserveHistory: this.stopObserveHistory.bind(this),
get history() { return getHistory(); },
get historyCurrent() { return getHistoryCurrent(); },
set historyCurrent(index) { return setHistoryCurrent(index); },
get historyLimit() { return getHistoryLimit(); },
set historyLimit(limit) { setHistoryLimit(limit); },
get historyFeed() { return getHistoryFeed(); },
set historyFeed(fn) { setHistoryFeed(fn); },
get isHistoryDisabled() { return getHistoryDisabled(); },
set isHistoryDisabled(value) { setHistoryDisabled(value); },
get isHistoryBatched() { return getHistoryBatched(); },
set isHistoryBatched(value) { setHistoryBatched(value); },
get historyBatchModes() { return getHistoryBatchModes(); },
parse: this.parse.bind(this),
path: this.path.bind(this),
parent: this.parent.bind(this),
fragment: this.metaProxify(this.fragment, this),
isFragment: this.metaProxify(getIsFragment, this),
get fragmentPath() { return ""; },
augment: this.metaProxify(this.augment, this),
observe: this.metaProxify(function (pathOrObject, fn, children = false, deep = false, init = true)
{ return this.observe(pathOrObject, fn, children, deep, init, this.catalyst); }, this),
stopObserve: this.stopObserve.bind(this),
deferObservers: this.deferObservers.bind(this),
resumeObservers: this.resumeObservers.bind(this),
refresh: this.metaProxify(this.refresh, this),
get isObserveAsync() { return getObserveAsync(); },
set isObserveAsync(value) { setObserveAsync(value); },
get isObserveDeferred() { return getObserveDeffered(); },
set isObserveDeferred(value) { setObserveDeffered(value); },
intercept: this.metaProxify(function (pathOrObject, fn, children = false, deep = false)
{ return this.intercept(pathOrObject, fn, children, deep, this.catalyst); }, this),
stopIntercept: this.stopIntercept.bind(this),
get store() { return getStore(); }
};
// All done - Return the catalyst
return this.catalyst;
}
// ---------------------------
// HISTORY METHODS
// ---------------------------
timestamp() {
let timestamp = Date.now();
if (timestamp == this._timestamp) this._timestampCounter ++;
else {
this._timestamp = timestamp;
this._timestampCounter = 1;
}
return timestamp.toString() + (("00" + this._timestampCounter).slice(-3));
}
/**
* Resumes history recording. Stackable.
*/
record() {
this.historyDisabled --;
if (this.historyDisabled < 0) this.historyDisabled = 0;
}
/**
* Stops history recording. Stackable. WARNING! Can cause side-effects in history recording.
*/
stopRecord() {
this.historyDisabled ++;
}
/**
* Starts combining multiple history records into a single atomic step. Stackable.
* @param {boolean} aggregate - Combine updates to the same property into a single update.
* @param {boolean} preserveOrder - Preserve order of updates to different properties. Effective only when aggregate is true.
*/
batch(aggregate = false, preserveOrder = true) {
// If this is the first batch switch, add a new history array to hold all the batched ops.
if (!this.historyBatched) this.history.push({ timestamp: this.timestamp(), changelog: [] });
// Turn on batch mode!
this.historyBatched ++;
this.historyBatchModes.push({aggregate, preserveOrder, count: 0, map: {}});
}
/**
* Stops batching and marks the beginning of a new history step. Stackable.
*/
stopBatch() {
// Notify flag
let notify = false;
// Prune Flag
let prune = false;
// Are we stopping an ongoing batch op recording?
if (this.historyBatched > 0) {
// Are we stopping a batch op that aggregates but does not preserves order ?
if (this.historyBatchModes[this.historyBatched - 1].aggregate &&
(!this.historyBatchModes[this.historyBatched - 1].preserveOrder)) {
// Prep
let map = this.historyBatchModes[this.historyBatched - 1].map;
// Add the mapped changelogs to the array of changelogs
for(var prop in map) this.history[this.history.length - 1].changelog.push(map[prop]);
}
// Remove active batch recording mode
this.historyBatchModes.splice(-1, 1);
// Have we just stopped all batch ops ? - meaning we have a valid history record!
if (this.historyBatched == 1) {
// Remove previous history if it has empty changelog!
if (this.history[this.history.length - 1].changelog.length == 0) this.history.splice(-1, 1);
// Send notification of completion of history
else notify = true;
// Signal auto prune
prune = true;
}
}
// Decrement counter
this.historyBatched --;
if (this.historyBatched < 0) this.historyBatched = 0;
// Notify?
if (notify) this.notifyHistoryObservers(this.history[this.history.length - 1], "add");
// Prune?
if (prune && this.historyLimit && !this.prunePending) {
this.prunePending = true;
Promise.resolve(true).then(() => this.prune());
}
}
logChange(str) {
// Are we recording
if (!!this.historyDisabled) return false;
// Commit redo steps!
this.commit();
// Record normally
if (!this.historyBatched) {
this.history.push({ timestamp: this.timestamp(), changelog: [str] });
this.notifyHistoryObservers(this.history[this.history.length - 1], "add");
if (this.historyLimit && !this.prunePending) {
this.prunePending = true;
Promise.resolve(true).then(() => this.prune());
}
}
// Record Batched
else {
// Aggregation needed?
if (this.historyBatchModes[this.historyBatched - 1].aggregate) {
// Preserve order
if (this.historyBatchModes[this.historyBatched - 1].preserveOrder) {
// Prep
let tol = this.history[this.history.length - 1].changelog.length;
// Check if we are the first, both all-batched-wise and current-batchmode-wise
if ((tol > 0) && (this.historyBatchModes[this.historyBatched - 1].count > 0)) {
// Split into prop and value
let newProp = str.slice(0, str.indexOf("=")),
lastProp = this.history[this.history.length - 1].changelog[tol - 1]
.slice(0, this.history[this.history.length - 1].changelog[tol - 1].indexOf("="));
// Check if last prop is as same as current - add new changelog if not!
if (newProp != lastProp) {
this.history[this.history.length - 1].changelog.push(str);
this.historyBatchModes[this.historyBatched - 1].count ++;
}
// Same prop - replace last changelog only if nothing has happened on it before - to represent the oldest undo state!
//else this.history[this.history.length - 1].changelog[tol - 1] = str; // WARNING! this is erroneous as undo op should be the initial state before the history begins !
}
// We are the first - direct add!
else {
this.history[this.history.length - 1].changelog.push(str);
this.historyBatchModes[this.historyBatched - 1].count ++;
}
}
// No order - Compress more
else {
// Prep
let prop = str.slice(0, str.indexOf("="));
// Add the op only if nothing has happened on it before - to represent the oldest undo state!
if (typeof this.historyBatchModes[this.historyBatched - 1].map[prop] == "undefined")
this.historyBatchModes[this.historyBatched - 1].map[prop] = str;
//this.historyBatchModes[this.historyBatched - 1].map[prop] = str; // WARNING! this is erroneous as undo op should be the initial state before the history begins !
}
}
// No aggregation - Add to changelog directly
else this.history[this.history.length - 1].changelog.push(str);
}
// All done
return true;
}
/**
* Restores store to previously recorded state. Does not invoke interceptors. Will dissolve fragments and break references where necessary.
* @param {number} steps - The number of history records to undo.
* @param {boolean} defer - If true, notifies observers AFTER undoing the given number of steps. If false, notifies observers WHILE undoing.
* @returns {number} The number of steps that were successfully undone.
*/
undo(steps = 1, defer = true) {
// Prep
let historyTarget = this.historyCurrent + steps;
let stepsCount = 0;
let timestamp = null;
// Initial timestamp
if (this.history.length == this.historyCurrent) {
if (this.history.length > 0) timestamp = this.history[0].timestamp;
else timestamp = this.timestamp();
}
else timestamp = this.history[this.history.length - this.historyCurrent - 1].timestamp;
// Install blank logger - don't mess up the history!
this.historyLogger = () => false;
// Install blank intercept notifier
this.interceptorNotifier = (_, __, ___, newValue) => newValue;
// Install blank batch ops starter & stopper
this.batchStarter = () => false;
this.batchStopper = () => false;
// Nullify fragment preservation
let preserveFragments = this.preserveFragments;
this.preserveFragments = false;
// Start observe defer mode
if (defer) this.deferObservers();
// Undo 'step' number of history, one changelog at a time each.
while (this.historyCurrent < historyTarget) {
// Check if we have the next history
if (this.history.length - this.historyCurrent == 0) {
// Request history feed
let feed = typeof this.historyFeed == "function" ? this.historyFeed(this.historyCurrent + 1, historyTarget, timestamp) : false;
// Check if we got anything
if (!feed) break;
// Add the feed to our history
this.history.unshift(...feed);
}
// Obtain the next history
let history = this.history[this.history.length - this.historyCurrent - 1];
// Create future - for redo
if (!history.oplog) history.oplog = [];
// Loop through the changelog
for (var changeIndex = history.changelog.length - 1; changeIndex >= 0; changeIndex --) {
// Prep
let change = history.changelog[changeIndex];
// Parse
let sepIndex = change.indexOf("=");
let prop = change.slice(0, sepIndex);
let value = change.slice(sepIndex + 1);
// More prep
let pointer = this.store;
let levels = prop.split(this.accessor);
levels.shift();
// Traverse
for (var levelIndex = 0; levelIndex < levels.length - 1; levelIndex ++) pointer = pointer[levels[levelIndex]];
// Install custom log utility
if (history.oplog.length < history.changelog.length - changeIndex) this.historyLogger = historyStr => {
history.oplog.unshift(historyStr) || true;
this.historyLogger = () => false;
return true;
}
// Execute op
if (!value.length) delete pointer[levels[levels.length - 1]];
else pointer[levels[levels.length - 1]] = JSON.parse(value);
}
// Update timestamp
timestamp = history.timestamp;
// Move to next step
stepsCount ++;
this.historyCurrent ++;
// Notify
this.notifyHistoryObservers(history, "update");
}
// Stop Observe defer mode
if (defer) this.resumeObservers();
// Restore fragment preservation
this.preserveFragments = preserveFragments;
// Restore batch Ops starter and stopper
this.batchStarter = this.batch.bind(this);
this.batchStopper = this.stopBatch.bind(this);
// Restore intercept notifier
this.interceptorNotifier = this.notifyInterceptors.bind(this);
// Restore log utility to default
this.historyLogger = this.logChange.bind(this);
// All done - return the number of successful undone steps
return stepsCount;
}
/**
* Restores store to previously updated state. Does not invoke interceptors. Will dissolve fragments and break references where necessary.
* @param {number} steps - The number of history records to redo.
* @param {boolean} defer - If true, notifies observers AFTER redoing the given number of steps. If false, notifies observers WHILE redoing.
* @returns {number} The number of steps that were successfully redone.
*/
redo(steps = 1, defer = true) {
// Sanity Check
if (this.historyCurrent == 0) return 0;
// Prep
let historyTarget = this.historyCurrent - steps;
let stepsCount = 0;
// Validity reset
historyTarget = historyTarget < 0 ? 0 : historyTarget;
// Install blank logger - don't mess up the history!
this.historyLogger = () => false;
// Install blank intercept notifier
this.interceptorNotifier = (_, __, ___, newValue) => newValue;
// Install blank batch ops starter & stopper
this.batchStarter = () => false;
this.batchStopper = () => false;
// Nullify fragment preservation
let preserveFragments = this.preserveFragments;
this.preserveFragments = false;
// Start observe defer mode
if (defer) this.deferObservers();
// Undo 'step' number of history, one changelog at a time each.
while (this.historyCurrent > historyTarget) {
// Obtain the current history
let history = this.history[this.history.length - this.historyCurrent];
// Loop through the oplog
for (var opIndex = 0; opIndex < history.oplog.length; opIndex ++) {
// Prep
let op = history.oplog[opIndex];
// Parse
let sepIndex = op.indexOf("=");
let prop = op.slice(0, sepIndex);
let value = op.slice(sepIndex + 1);
// More prep
let pointer = this.store;
let levels = prop.split(this.accessor);
levels.shift();
// Traverse
for (var levelIndex = 0; levelIndex < levels.length - 1; levelIndex ++) pointer = pointer[levels[levelIndex]];
// Execute op
if (!value.length) delete pointer[levels[levels.length - 1]];
else pointer[levels[levels.length - 1]] = JSON.parse(value);
}
// Delete the oplog - save memory
delete history.oplog;
// Move to next step
stepsCount ++;
this.historyCurrent --;
// Notify
this.notifyHistoryObservers(history, "update");
}
// Stop observe defer mode
if (defer) this.resumeObservers();
// Restore fragment preservation
this.preserveFragments = preserveFragments;
// Restore batch Ops starter and stopper
this.batchStarter = this.batch.bind(this);
this.batchStopper = this.stopBatch.bind(this);
// Restore intercept notifier
this.interceptorNotifier = this.notifyInterceptors.bind(this);
// Restore log utility to default
this.historyLogger = this.logChange.bind(this);
// All done - return the number of successful undone steps
return stepsCount;
}
/**
* Destroys redoable steps from after current state. Also automatically called if updates are made to the store when current state is not the most recent.
*/
commit() {
if (this.historyCurrent > 0) {
for (var count = 0; count < this.historyCurrent; count ++)
this.notifyHistoryObservers(this.history.pop(), "delete");
this.historyCurrent = 0;
}
}
/**
* Removes undoable steps from memory, for optimization purposes.
* @param {number} keep - The number of history records to keep, starting from most recent. If keep is less than currentHistory, currentHistory will be used instead.
* @returns {Object[]} The history records that were removed from memory.
*/
prune(keep) {
// Mark prune pending as over !
if (!keep) this.prunePending = false;
// Prep
keep = keep || this.historyLimit;
// Check sanity
if (!keep) return [];
// Reset to currentHistory
keep = keep > this.historyCurrent ? keep : historyCurrent;
// Prep
let target = this.history.length - keep;
// Check if prune is needed
if (target <= 0) return [];
// Prune
return this.history.splice(0, target);
}
/**
* Registers a callback to be invoked when a history record is created/updated/deleted.
* @param {historyCB} fn - The function to be used as the callback.
* @returns {number} An ID that can be used to unregister the callback.
*/
observeHistory(fn) {
let id = this.timestamp();
this.historyObservers[id] = fn;
return id;
}
/**
* Unregisters observeHistory callback.
* @param {number} id - The ID that was returned on registering the callback.
* @returns {boolean} Whether the callback was successfully unregistered.
*/
stopObserveHistory(id) {
if (this.historyObservers.hasOwnProperty(id)) {
delete this.historyObservers[id];
return true;
}
return false;
}
notifyHistoryObservers(history, notificationType) {
Object.values(this.historyObservers).forEach(fn => {
if (this.observeAsync) Promise.resolve().then(() => fn(notificationType, history, this.store));
else fn(notificationType, history, this.store);
});
}
// ---------------------------
// FRAGMENTATION METHODS
// ---------------------------
/**
* Parses a nested property path string, and returns the part of the store that it represents.
* @param {string} path - The path containing the properties, separated by the accessor character.
* @returns {*} The part of the store represented by the path.
*/
parse(path) {
// Sanitize propertypath
if (!path.length) throw "Path is an empty string.";
// Prep levels
let levels = path.split(this.accessor);
if (path[0] == this.accessor) levels.shift();
// Get the final value, if can..
return levels.reduce((obj, prop) => {
if (typeof obj == "undefined") return obj;
if (prop.length == 0) return obj;
return obj[prop];
}, this.store);
}
/**
* Takes a part of the store and returns the path of the object relative to the base store.
* @param {Object} obj - An object reference to any part of the store.
* @returns {string} The path of the object relative to the base store.
*/
path(obj) {
if (typeof obj != "object") throw ("Expected object, got " + (typeof obj) + ".");
let context = this.resolve(obj, true);
path = context.path;
return path;
}
/**
* Takes a part of the store and returns the parent of that object in the store.
* @param {Object|string} pathOrObject - An object reference or a string path that represents any part of the store.
* @returns {Object} An object reference to the parent of the given path or object.
*/
parent(pathOrObject) {
if (typeof pathOrObject == "string") {
if (pathOrObject.length == 0) throw "Path is an empty string.";
let levels = pathOrObject.split(this.accessor);
if (pathOrObject[0] == this.accessor) levels.shift();
levels.pop();
return levels.reduce((obj, prop) => prop.length > 0 ? obj && obj[prop] : obj, this.store);
}
else if (typeof pathOrObject == "object") {
let path = this.resolve(pathOrObject, true).path;
return this.parent(path);
}
else throw ("Expected string or object, got " + (typeof pathOrObject) + ".");
}
/**
* Takes a part of the store and returns if that part has any fragments.
* @param {Object|string} pathOrObject - An object reference or a string path that represents any part of the store.
* @returns {number} The number of fragments.
*/
isFragment(pathOrObject) {
// Prep path
let path;
if (typeof pathOrObject == "object") path = this.path(pathOrObject);
else if (typeof pathOrObject == "string") path = pathOrObject;
else throw ("Expected string or object, got " + (typeof pathOrObject) + ".");
// Sanitize propertypath
if (!path.length) return 0;
if (path[0] != this.accessor) path = this.accessor + path;
// Return if fragment
return (typeof this.fragmented[path] == "object") ? Object.keys(this.fragmented[path]).length : 0;
}
/**
* Creates a new fragment, which freezes reference and allows relative access to the given part of the state.
* @param {Object|string} pathOrObject - An object reference or a string path that represents any object/array part of the store.
* @param {dissolveCB} onDissolve - Invoked when the fragment is dissolved. Can be used for external clean-up. Do NOT update the store here!
* @returns {Object} A new fragment object.
*/
fragment(pathOrObject, onDissolve) {
// Prep path
let path;
if (typeof pathOrObject == "object") path = this.path(pathOrObject);
else if (typeof pathOrObject == "string") path = pathOrObject;
else throw ("Expected string or object, got " + (typeof pathOrObject) + ".");
// Sanitize propertypath
if (!path.length) throw "Path is an empty string.";
if (path[0] != this.accessor) path = this.accessor + path;
// Check if path exists and is an object
let store = this.parse(path);
if (typeof store != "object") throw "Path must represent an existing valid part of the store.";
// Create ID
this._fragCounter = (this._fragCounter || 1) + 1;
let id = this._fragCounter;
// Populate new fragment
let internal = { observers: [], interceptors: [] };
let fragment = {
catalyst: this.catalyst,
stopObserve: this.stopObserve.bind(this),
stopIntercept: this.stopIntercept.bind(this),
get store() { return store; },
get fragmentPath() { return path; },
get fragmentId() { return id; }
};
// Helper
let normalize = _path => {
if (_path.length > 0) return path + (_path[0] == "." ? "" : ".") + _path;
else return path;
};
// Dissolver
let dissolve = function() {
// Check
if (!this.fragments.hasOwnProperty(id)) return false;
// Dissolution callback
if (typeof onDissolve == "function") onDissolve(fragment);
// Stop observers and interceptors installed through this fragment
internal.observers.forEach(id => this.stopObserve(id));
internal.interceptors.forEach(id => this.stopIntercept(id));
// Delete fragment methods
delete fragment.catalyst;
delete fragment.stopObserve;
delete fragment.stopIntercept;
delete fragment.parent;
delete fragment.parse;
delete fragment.isFragment;
delete fragment.fragment;
delete fragment.dissolve;
delete fragment.augment;
delete fragment.observe;
delete fragment.refresh;
delete fragment.intercept;
// Uninstall the fragment
delete this.fragmented[path][id];
delete this.fragments[id];
// Delete fragment properties
internal = undefined;
store = undefined;
path = undefined;
id = undefined;
onDissolve = undefined;
// All done
return true;
};
// Prep methods that use relative paths
let observe = function(pathOrObject, fn, children = false, deep = false, init = true) {
if (typeof pathOrObject == "undefined") internal.observers.push(this.observe(path, fn, children, deep, init, fragment));
else if (typeof pathOrObject == "object") internal.observers.push(this.observe(pathOrObject, fn, children, deep, init, fragment));
else if (typeof pathOrObject == "string") internal.observers.push(this.observe(normalize(pathOrObject), fn, children, deep, init, fragment));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
return internal.observers[internal.observers.length - 1];
};
let refresh = function(pathOrObject) {
if (typeof pathOrObject == "undefined") return this.refresh(path);
else if (typeof pathOrObject == "object") return this.refresh(pathOrObject);
else if (typeof pathOrObject == "string") return this.refresh(normalize(pathOrObject));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
};
let intercept = function(pathOrObject, fn, children = false, deep = false) {
if (typeof pathOrObject == "undefined") internal.interceptors.push(this.intercept(path, fn, children, deep, fragment));
else if (typeof pathOrObject == "object") internal.interceptors.push(this.intercept(pathOrObject, fn, children, deep, fragment));
else if (typeof pathOrObject == "string") internal.interceptors.push(this.intercept(normalize(pathOrObject), fn, children, deep, fragment));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
return internal.interceptors[internal.interceptors.length - 1];
};
let isFragment = function(pathOrObject) {
if (typeof pathOrObject == "undefined") return this.isFragment(path);
else if (typeof pathOrObject == "object") return this.isFragment(pathOrObject);
else if (typeof pathOrObject == "string") return this.isFragment(normalize(pathOrObject));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
};
let parent = function(pathOrObject) {
if (typeof pathOrObject == "undefined") return this.parent(path);
else if (typeof pathOrObject == "object") return this.parent(pathOrObject);
else if (typeof pathOrObject == "string") return this.parent(normalize(pathOrObject));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
};
let parse = function(_path) { return this.parse(normalize(_path)); };
let fragmentFn = function(pathOrObject, _onDissolve) {
if (typeof pathOrObject == "undefined") return this.fragment(path, _onDissolve);
else if (typeof pathOrObject == "object") return this.fragment(pathOrObject, _onDissolve);
else if (typeof pathOrObject == "string") return this.fragment(normalize(pathOrObject), _onDissolve);
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
};
let augment = function (pathOrObject) {
if (typeof pathOrObject == "undefined") return this.augment(path);
else if (typeof pathOrObject == "object") return this.augment(pathOrObject);
else if (typeof pathOrObject == "string") return this.augment(normalize(pathOrObject));
else throw ("Expected string, object or undefined, got" + (typeof pathOrObject) + ".");
}
// Assign the methods that use relative paths
fragment.isFragment = this.metaProxify(isFragment, this);
fragment.parent = parent.bind(this);
fragment.parse = parse.bind(this);
fragment.fragment = this.metaProxify(fragmentFn, this);
fragment.dissolve = dissolve.bind(this);
fragment.augment = this.metaProxify(augment, this);
fragment.observe = this.metaProxify(observe, this);
fragment.refresh = this.metaProxify(refresh, this);