-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.ts
280 lines (233 loc) · 9.4 KB
/
index.ts
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
import copy from "../utils/copy";
import diffpatch from "../utils/diffpatch";
import createDiff, { Patch } from "../utils/createDiff";
import { getTypeOf } from "json-schema-library";
import gp from "gson-pointer";
import isRootPointer from "../utils/isRootPointer";
import Store from "../../store";
import { JSONData, JSONPointer } from "../../types";
import { UpdateDataEvent } from "../../editors/Editor";
import { Change, SimpleChange, changesFromPatchResult, changesWithChildPointers } from "./change";
const ID = "data";
/** Called before a single change in value will be notified */
type BeforeUpdateEvent = {
type: "data:update:before";
value: { pointer: JSONPointer; action: string; };
}
/** Called when a single change in value was notified */
type AfterUpdateEvent = {
type: "data:update:after";
value: { pointer: JSONPointer; patch: Patch };
}
/** Additional event called when for single array or object change */
type ContainerUpdateEvent = {
type: "data:update:container";
value: { pointer: JSONPointer; changes: Array<Change> };
}
/** Called when all updates have been notified */
type UpdateDoneEvent = {
type: "data:update:done";
value: Array<SimpleChange>;
}
export type Event = BeforeUpdateEvent|ContainerUpdateEvent|AfterUpdateEvent|UpdateDoneEvent;
export type Watcher = (event: Event) => void;
export type Observer = {
(event: UpdateDataEvent): void;
bubbleEvents?: boolean;
}
export default class DataService {
/** current state */
store: Store;
/** current observers on json-pointer changes */
observers: { [pointer: string]: Array<Observer> } = {};
/** internal value to track previous data */
lastUpdate = {};
/** list of active watchers on update-lifecycle events */
watcher = [];
/**
* Read and modify form data and notify observers
* @param state - current state/store of application
* @param data - current application data (form)
*/
constructor(store: Store, data?: JSONData) {
if (!(store instanceof Store)) {
throw new Error("Given state in DataService must be of instance 'State'");
}
this.store = store;
this.onStateChanged = this.onStateChanged.bind(this);
this.store.subscribe(ID, this.onStateChanged);
if (data !== undefined) {
this.set("#", data);
this.resetUndoRedo();
}
}
// improved version - supporting multiple patches
onStateChanged() {
const { present: data } = this.store.get(ID);
const patches = createDiff(this.lastUpdate, data);
if (patches.length === 0) {
return;
}
const allChanges = [];
// @todo simplify event-arguments: we have patches, changes and simplechanges
for (let i = 0, l = patches.length; i < l; i += 1) {
const eventLocation = patches[i].pointer;
const parentData = this.getDataByReference(eventLocation);
const parentDataType = getTypeOf(parentData);
// build simple patch-information and notify about changes in pointer for move-instance support
// this is a major performance improvement for array-item movements
const changes = changesFromPatchResult(patches[i], parentDataType, this.lastUpdate);
if (parentDataType === "array" || parentDataType === "object") {
this.notifyWatcher({ type: "data:update:container", value: { pointer: eventLocation, changes }});
}
// collect all changes fo change-stream
allChanges.push(...changes);
const payload = { pointer: eventLocation, patch: patches[i].patch };
this.notifyWatcher({ type: "data:update:after", value: payload });
this.bubbleObservers(eventLocation, { type: "data:update", value: payload });
}
const changeStream = changesWithChildPointers(allChanges, this.lastUpdate, data);
this.notifyWatcher(<UpdateDoneEvent>{ type: "data:update:done", value: changeStream });
this.lastUpdate = data;
}
/** clear undo/redo stack */
resetUndoRedo() {
this.store.dispatch.data.clearHistory();
this.store.previousState?.errors.pop();
}
/**
* Get a copy of current data from the requested `pointer`
* @param [pointer] - data to fetch. Defaults to _root_
* @returns data, associated with `pointer`
*/
get(pointer: JSONPointer = "#") {
const value = this.getDataByReference(pointer);
return copy(value);
}
/** returns a reference to data from the requested `pointer` (cheaper)
* @param [pointer="#"] - data to fetch. Defaults to _root_
* @returns data, associated with `pointer`
*/
getDataByReference(pointer: JSONPointer = "#") {
const state = this.store.store.getState();
return gp.get(state.data.present, pointer);
}
/**
* Change data at the given `pointer`
* @param pointer - data location to modify
* @param value - new value at pointer
* @param [options]
*/
set(pointer: JSONPointer, value: any, options?: { addToHistory?: boolean }) {
if (this.isValid(pointer) === false) {
throw new Error(`Pointer ${pointer} does not exist in data`);
}
const currentValue = this.getDataByReference(pointer);
if (diffpatch.diff(currentValue, value) == null) {
return;
}
if (pointer === "#") {
// do not add root changes to undo (for sync, skip this)
options = { ...options, addToHistory: false};
}
this.notifyWatcher({ type: "data:update:before", value: { pointer, action: "data" }});
// this.store.dispatch(ActionCreators.setData(pointer, value, currentValue, isSynched));
this.store.dispatch.data.set({ pointer, value, addToHistory: options?.addToHistory });
}
/**
* Delete data at the given `pointer`
* @param pointer - data location to delete
*/
delete(pointer: JSONPointer) {
if (isRootPointer(pointer)) {
throw new Error("Can not remove root data via delete. Use set(\"#/\", {}) instead.");
}
const frags = gp.split(pointer);
const key = frags.pop();
const parentPointer = gp.join(frags);
const data = this.get(parentPointer);
gp.remove(data, key);
this.set(parentPointer, data);
}
/** get valid undo count */
undoCount(): number {
return this.store.get(ID).past.length;
}
/** get valid redo count */
redoCount(): number {
return this.store.get(ID).future.length;
}
/** undo last change */
undo() {
this.notifyWatcher({ type: "data:update:before", value: { pointer: "#", action: "undo" }});
this.store.dispatch.data.undo();
// this.store.dispatch(ActionCreators.undo());
}
/** redo last undo */
redo() {
this.notifyWatcher({ type: "data:update:before", value: { pointer: "#", action: "redo" }});
// this.store.dispatch(ActionCreators.redo());
this.store.dispatch.data.redo();
}
notifyWatcher(event: Event) {
this.watcher.forEach(watcher => watcher(event));
}
/** watch DataService lifecycle events */
watch(callback: Watcher) {
if (this.watcher.includes(callback) === false) {
this.watcher.push(callback);
}
return callback;
}
removeWatcher(callback: Watcher) {
this.watcher = this.watcher.filter(watcher => watcher !== callback);
}
/**
* observes changes in data at the specified json-pointer
* @param pointer - json-pointer to watch
* @param callback - called on a change
* @param bubbleEvents - set to true to receive notifications changes in children of pointer
* @returns callback
*/
observe<T extends Observer>(pointer: JSONPointer, callback: T, bubbleEvents = false): T {
callback.bubbleEvents = bubbleEvents;
this.observers[pointer] = this.observers[pointer] || [];
this.observers[pointer].push(callback);
return callback;
}
/** stop an observer from watching changes on pointer */
removeObserver(pointer: JSONPointer, callback: Observer) {
if (this.observers[pointer] && this.observers[pointer].length > 0) {
this.observers[pointer] = this.observers[pointer].filter(cb => cb !== callback);
}
return this;
}
/** send an event to all json-pointer observers */
notify(pointer: JSONPointer, event: UpdateDataEvent) {
if (this.observers[pointer] == null || this.observers[pointer].length === 0) {
return;
}
const observers = this.observers[pointer];
for (let i = 0, l = observers.length; i < l; i += 1) {
if (observers[i].bubbleEvents === true || event.value.pointer === pointer) {
observers[i](event);
}
}
}
bubbleObservers(pointer: JSONPointer, event: UpdateDataEvent) {
const frags = gp.split(pointer);
while (frags.length) {
this.notify(gp.join(frags, true), event);
frags.length -= 1;
}
this.notify("#", event);
}
/** Test the pointer for existing data */
isValid(pointer: JSONPointer): boolean {
return isRootPointer(pointer) || gp.get(this.getDataByReference(), pointer) !== undefined;
}
/** destroy service */
destroy() {
this.store.unsubscribe(ID, this.onStateChanged);
}
}