forked from rafaelw/mutation-summary
/
MutationSummary.ts
190 lines (163 loc) · 6.35 KB
/
MutationSummary.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
import {Selector} from "./Selector";
import {IQuery} from "./IQuery";
import {IMutationSummaryOptions} from "./IMutationSummaryOptions";
import {Summary} from "./Summary";
import {MutationProjection} from "./MutationProjection";
import {IQueryValidator} from "./IQueryValidator";
import {MutationSummaryOptionProcessor} from "./MutationSummaryOptionProcessor";
/**
* This is the main entry point class for the Mutation Summary library. When
* created, a MutationSummary takes care of the details of observing the DOM
* for changes, computing the "net-effect" of what's changed and then delivers
* these changes to the provided callback.
*
* @example
* ```
* const ms = new MutationSummary({
* callback(summaries => {
* summaries.forEach(summary => console.log(summary)),
* queries: [
* { all: true }
* ]
* })
* })
* ```
*/
export class MutationSummary {
// TODO move this to a configuration option.
public static createQueryValidator: (root: Node, query: IQuery) => IQueryValidator;
private _connected: boolean;
private _options: IMutationSummaryOptions;
private _observer: MutationObserver;
private readonly _observerOptions: MutationObserverInit;
private readonly _root: Node;
private readonly _callback: (summaries: Summary[]) => any;
private readonly _elementFilter: Selector[];
private readonly _calcReordered: boolean;
private _queryValidators: IQueryValidator[];
/**
* Creates a new MutationSummary class using the specified options.
*
* @param opts The options that configure how the MutationSummary
* instance will observe and report changes.
*/
constructor(opts: IMutationSummaryOptions) {
this._connected = false;
this._options = MutationSummaryOptionProcessor.validateOptions(opts);
this._observerOptions = MutationSummaryOptionProcessor.createObserverOptions(this._options.queries);
this._root = this._options.rootNode;
this._callback = this._options.callback;
this._elementFilter = Array.prototype.concat.apply([], this._options.queries.map((query) => {
return query.elementFilter ? query.elementFilter : [];
}));
if (!this._elementFilter.length)
this._elementFilter = undefined;
this._calcReordered = this._options.queries.some((query) => {
return query.all;
});
this._queryValidators = []; // TODO(rafaelw): Shouldn't always define this.
if (MutationSummary.createQueryValidator) {
this._queryValidators = this._options.queries.map((query) => {
return MutationSummary.createQueryValidator(this._root, query);
});
}
this._observer = new MutationObserver((mutations: MutationRecord[]) => {
this._observerCallback(mutations);
});
this.reconnect();
}
/**
* Starts observation using an existing `MutationSummary` which has been
* disconnected. Note that this function is just a convenience method for
* creating a new `MutationSummary` with the same options. The next time
* changes are reported, they will relative to the state of the observed
* DOM at the point that `reconnect` was called.
*/
public reconnect(): void {
if (this._connected)
throw Error('Already connected');
this._observer.observe(this._root, this._observerOptions);
this._connected = true;
this._checkpointQueryValidators();
}
/**
* Immediately calculates changes and returns them as an array of summaries.
* If there are no changes to report, returns undefined.
*/
public takeSummaries(): Summary[] | undefined {
if (!this._connected)
throw Error('Not connected');
const summaries = this._createSummaries(this._observer.takeRecords());
return this._changesToReport(summaries) ? summaries : undefined;
}
/**
* Discontinues observation immediately. If DOM changes are pending delivery,
* they will be fetched and reported as the same array of summaries which
* are handed into the callback. If there is nothing to report,
* this function returns undefined.
*
* @returns A list of changes that have not yet been delivered to a callback.
*/
public disconnect(): Summary[] | undefined {
const summaries = this.takeSummaries();
this._observer.disconnect();
this._connected = false;
return summaries;
}
private _observerCallback(mutations: MutationRecord[]): void {
if (!this._options.observeOwnChanges)
this._observer.disconnect();
const summaries = this._createSummaries(mutations);
this._runQueryValidators(summaries);
if (this._options.observeOwnChanges)
this._checkpointQueryValidators();
if (this._changesToReport(summaries))
this._callback(summaries);
// disconnect() may have been called during the callback.
if (!this._options.observeOwnChanges && this._connected) {
this._checkpointQueryValidators();
this._observer.observe(this._root, this._observerOptions);
}
}
private _createSummaries(mutations: MutationRecord[]): Summary[] {
if (!mutations || !mutations.length)
return [];
const projection = new MutationProjection(this._root, mutations, this._elementFilter, this._calcReordered, this._options.oldPreviousSibling);
const summaries: Summary[] = [];
for (let i = 0; i < this._options.queries.length; i++) {
summaries.push(new Summary(projection, this._options.queries[i]));
}
return summaries;
}
private _checkpointQueryValidators() {
this._queryValidators.forEach((validator) => {
if (validator)
validator.recordPreviousState();
});
}
private _runQueryValidators(summaries: Summary[]) {
this._queryValidators.forEach((validator: IQueryValidator, index) => {
if (validator)
validator.validate(summaries[index]);
});
}
private _changesToReport(summaries: Summary[]): boolean {
return summaries.some((summary) => {
const summaryProps = ['added', 'removed', 'reordered', 'reparented',
'valueChanged', 'characterDataChanged'];
if (summaryProps.some(function (prop) {
return summary[prop] && summary[prop].length;
}))
return true;
if (summary.attributeChanged) {
const attrNames = Object.keys(summary.attributeChanged);
const attrsChanged = attrNames.some((attrName) => {
return !!summary.attributeChanged[attrName].length
});
if (attrsChanged)
return true;
}
return false;
});
}
}