-
Notifications
You must be signed in to change notification settings - Fork 72
/
firebase-collection.html
656 lines (539 loc) · 20.3 KB
/
firebase-collection.html
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
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="firebase-query-behavior.html">
<!--
* **Note: This element is for the older Firebase 2 API**
For the latest official Firebase 3.0-compatible component from the Firebase team,
see the [polymerfire](https://github.com/firebase/polymerfire) component.
In this new component, the `firebase-collection` element has been replaced
with [`firebase-query`](https://github.com/firebase/polymerfire#firebase-query)
An element wrapper for the Firebase API that provides a view into the provided
Firebase location as an ordered collection.
By default, Firebase yields values as unsorted document objects, where each of
the children are accessible via object keys. The `<firebase-collection>`
element allows Firebase API orderBy*, limitTo* and other query-oriented methods
to be specified declaratively. The element then produces and maintains an Array
of ordered child items of the document that is convenient for iterating over
in other elements such as `<template is="dom-repeat">`.
Example:
<template is="dom-bind">
<firebase-collection
order-by-child="height"
limit-to-first="3"
location="https://dinosaur-facts.firebaseio.com/dinosaurs"
data="{{dinosaurs}}"></firebase-collection>
<template is="dom-repeat" items="[[dinosaurs]]" as="dinosaur">
<h4>[[dinosaur.__firebaseKey__]]</h4>
Height: <span>[[dinosaur.height]]</span>m
</template>
</template>
As you may have noticed above, the original key of each item is available as
the `__firebaseKey__` property on the item.
The element makes special accomodations for documents whose children are
primitive values. A primitive value is wrapped in an object with the form:
```javascript
{
value: /* original primitive value */
__firebaseKey__: /* key of primitive value in parent document */
}
```
Accessor methods such as `add` and `remove` are provided to enable convenient
manipulation of the collection without direct knowledge of Firebase key values.
@demo demo/index.html
-->
<script>
(function() {
'use strict'
var FirebaseCollection = Polymer({
is: 'firebase-collection',
behaviors: [
Polymer.FirebaseQueryBehavior
],
properties: {
/**
* A pointer to the current Firebase Query instance being used to
* populate `data`.
*/
query: {
type: Object,
notify: true,
computed: '_computeQuery(location, limitToFirst, limitToLast, _orderByMethodName, _startAt, _endAt, _equalTo)',
observer: '_queryChanged'
},
/**
* An ordered array of data items produced by the current Firebase Query
* instance.
*/
data: {
type: Array,
readOnly: true,
notify: true,
value: function() {
return [];
}
},
/**
* Specify a child key to order the set of records reflected on the
* client.
*/
orderByChild: {
type: String,
value: null,
reflectToAttribute: true
},
/**
* Specify to order by key the set of records reflected on the client.
*/
orderByKey: {
type: Boolean,
value: false,
reflectToAttribute: true
},
/**
* Specify to order by value the set of records reflected on the client.
*/
orderByValue: {
type: Boolean,
value: false,
reflectToAttribute: true
},
/**
* Specify to order by priority the set of records reflected on the
* client.
*/
orderByPriority: {
type: Boolean,
value: false,
reflectToAttribute: true
},
/**
* Specify a maximum number of records reflected on the client limited to
* the first certain number of children.
*/
limitToFirst: {
type: Number,
value: null,
reflectToAttribute: true,
},
/**
* Specify a maximum number of records reflected on the client limited to
* the last certain number of children.
*/
limitToLast: {
type: Number,
value: null,
reflectToAttribute: true
},
/**
* Specify a start record for the set of records reflected in the
* collection.
*/
startAt: {
type: String,
value: null,
reflectToAttribute: true
},
/**
* Specify an end record for the set of records reflected in the
* collection.
*/
endAt: {
type: String,
value: null,
reflectToAttribute: true
},
/**
* Specify to create a query which includes children which match the
* specified value. The argument type depends on which orderBy*() function
* was used in this query. Specify a value that matches the orderBy*()
* type.
*/
equalTo: {
type: String,
value: null,
reflectToAttribute: true
},
/**
* Specify to override the type used when deserializing the value of
* `start-at`, `end-at` and `equal-to` attributes. By default, these
* values are always deserialized as `String`, but sometimes it is
* preferrable to deserialize these values as e.g., `Number`.
*
* Accepted values for this attribute, and their corresponding
* deserialization types, are as follows:
*
* - `string` => `String` (default)
* - `number` => `Number`
* - `boolean` => `Boolean`
*/
orderValueType: {
type: String,
value: 'string',
reflectToAttribute: true
},
_valueMap: {
type: Object,
value: function() {
return {};
}
},
_orderByMethodName: {
computed: '_computeOrderByMethodName(orderByChild, orderByKey, orderByValue, orderByPriority)'
},
_orderByTypeCast: {
computed: '_computeOrderByTypeCast(orderByChild, orderByKey, orderByValue, orderByPriority, orderValueType)'
},
_startAt: {
computed: '_computeStartAt(startAt, _orderByTypeCast)'
},
_endAt: {
computed: '_computeEndAt(endAt, _orderByTypeCast)'
},
_equalTo: {
computed: '_computeEqualTo(equalTo, _orderByTypeCast)'
}
},
listeners: {
'firebase-child-added': '_onFirebaseChildAdded',
'firebase-child-removed': '_onFirebaseChildRemoved',
'firebase-child-changed': '_onFirebaseChildChanged',
'firebase-child-moved': '_onFirebaseChildMoved',
},
created: function() {
this._pendingSplices = [];
this._lastLocallyAddedIndex = null;
},
/**
* Add an item to the document referenced at `location`. A key associated
* with the item will be created by Firebase, and can be accessed via the
* Firebase Query instance returned by this method.
*
* If the query is not yet properly defined as it can be the case for bound location, the `query-error` event is fired.
*
* @param {Object} data A value to add to the document.
* @return {Object} A Firebase Query instance referring to the added item.
*/
add: function(data) {
var query;
this._log('Adding new item to collection with value:', data);
if (!this.query) {
this._fireQueryError('Query does not exist');
return;
}
query = this.query.ref().push();
query.set(data);
return query;
},
/**
* Remove an item from the document referenced at `location`. The item
* is assumed to be an identical reference to an item already in the
* `data` Array.
*
* @param {Object} data An identical reference to an item in `this.data`.
*/
remove: function(data) {
if (data == null || data.__firebaseKey__ == null) {
// NOTE(cdata): This might be better as an error message in the
// console, but `Polymer.Base._error` throws, which we don't want
// to happen in this case.
this._warn('Refusing to remove unknown value:', data);
return;
}
this._log('Removing collection item "' + data.__firebaseKey__ + '"', data.value);
this.removeByKey(data.__firebaseKey__);
},
/**
* Look up an item in the local `data` Array by key.
*
* @param {String} key The key associated with the item in the parent
* document.
*/
getByKey: function(key) {
return this._valueMap[key];
},
/**
* Remove an item from the document associated with `location` by key.
*
* @param {String} key The key associated with the item in the document
* located at `location`.
*/
removeByKey: function(key) {
if (!this.query) {
this._error('Cannot remove items before query has been initialized.');
return;
}
this.query.ref().child(key).remove();
},
_localDataChanged: function(change) {
var pathParts = change.path.split('.');
// We don't care about self-changes, and we don't respond directly to
// length changes:
if (pathParts.length < 2 || pathParts[1] === 'length') {
return;
}
// Handle splices via the adoption process. `indexSplices` is known to
// sometimes be null, so guard against that.
if (pathParts[1] === 'splices' && change.value.indexSplices != null) {
this._adoptSplices(change.value.indexSplices);
return;
}
// Otherwise, the change is happening to a sub-path of the array.
this._applySubPathChange(change);
},
_applySubPathChange: function(change) {
if (!this.query) {
this._fireQueryError('Query does not exist');
return;
}
var key = change.path.split('.')[1];
var value = Polymer.Collection.get(change.base).getItem(key);
var firebaseKey = value.__firebaseKey__;
// We don't want to accidentally reflect `__firebaseKey__` in the
// remote data, so we remove it temporarily. `null` values will be
// discarded by Firebase, so `delete` is not necessary:
value.__firebaseKey__ = null;
this.query.ref().child(firebaseKey).set(value);
value.__firebaseKey__ = firebaseKey;
},
_adoptSplices: function(splices) {
this._pendingSplices = this._pendingSplices.concat(splices);
// We can afford apply removals synchronously, so we do that first
// and save the `added` operations for the `debounce` below.
this._applyLocalDataChange(function() {
splices.forEach(function(splice) {
splice.removed.forEach(function(removed) {
this.remove(removed);
}, this);
}, this);
});
// We async until the next turn. The reason we want to do this is
// that splicing within a splice handler will break the data binding
// system in some places. This is referred to as the "re-entrancy"
// problem. See polymer/polymer#2491.
this.debounce('_adoptSplices', function() {
this._applyLocalDataChange(function() {
var splices = this._pendingSplices;
this._pendingSplices = [];
splices.forEach(function(splice) {
var added = splice.object.slice(splice.index, splice.index + splice.addedCount);
added.forEach(function(added, index) {
this._lastLocallyAddedIndex = splice.index + index;
this.add(added);
}, this);
}, this);
this._lastLocallyAddedIndex = null;
});
});
},
_computeQuery: function(location, limitToFirst, limitToLast, orderByMethodName, startAt, endAt, equalTo) {
var query;
if (!location) {
return;
}
this._log('Recomputing query.', arguments);
try {
query = new Firebase(location);
if (orderByMethodName) {
if (orderByMethodName === 'orderByChild') {
query = query[orderByMethodName](this.orderByChild);
} else {
query = query[orderByMethodName]();
}
}
if (startAt != null) {
query = query.startAt(startAt);
}
if (endAt != null) {
query = query.endAt(endAt);
}
if (equalTo != null) {
query = query.equalTo(equalTo);
}
if (limitToLast != null) {
query = query.limitToLast(limitToLast);
}
if (limitToFirst != null) {
query = query.limitToFirst(limitToFirst);
}
} catch(e) {
this._fireQueryError('Query cannot be instantiated with location ' + location + ' (' + e.toString() + ')');
} finally {
return query;
}
},
_queryChanged: function() {
this._valueMap = {};
this._setData([]);
Polymer.FirebaseQueryBehavior._queryChanged.apply(this, arguments);
},
_computeOrderByMethodName: function(orderByChild, orderByKey, orderByValue, orderByPriority) {
if (orderByChild) {
return 'orderByChild';
}
if (orderByKey) {
return 'orderByKey';
}
if (orderByValue) {
return 'orderByValue';
}
if (orderByPriority) {
return 'orderByPriority';
}
return null;
},
_computeOrderByTypeCast: function(orderByChild, orderByKey, orderByValue, orderByPriority, orderValueType) {
return function typeCast(value) {
if (!orderByKey &&
value != null &&
FirebaseCollection.ORDER_VALUE_TYPES[orderValueType]) {
return FirebaseCollection.ORDER_VALUE_TYPES[orderValueType](value);
}
return value;
};
},
_computeStartAt: function(startAt, orderByTypeCast) {
return orderByTypeCast(startAt);
},
_computeEndAt: function(endAt, orderByTypeCast) {
return orderByTypeCast(endAt);
},
_computeEqualTo: function(equalTo, orderByTypeCast) {
return orderByTypeCast(equalTo);
},
_valueFromSnapshot: function(snapshot) {
var value = snapshot.val();
if (!(value instanceof Object)) {
value = {
value: value,
__firebasePrimitive__: true
};
}
value.__firebaseKey__ = snapshot.key();
return value;
},
_valueToPersistable: function(value) {
var persistable;
if (value.__firebasePrimitive__) {
return value.value;
}
persistable = {};
for (var property in value) {
if (property === '__firebaseKey__') {
continue;
}
persistable[property] = value[property];
}
return persistable;
},
_onFirebaseChildAdded: function(event) {
this._applyRemoteDataChange(function() {
var value = this._valueFromSnapshot(event.detail.childSnapshot);
var key = value.__firebaseKey__;
var previousValueKey = event.detail.previousChildName;
var index = previousValueKey != null ?
this.data.indexOf(this._valueMap[previousValueKey]) + 1 : 0;
var lastLocallyAddedValue;
this._valueMap[value.__firebaseKey__] = value;
// NOTE(cdata): The rationale for this conditional dance around the
// last locally added index (since you will inevitably be wondering
// why we do it):
// There may be a "locally" added value which was spliced in. If
// there is, it may be in the "wrong" place in the array. This is
// due to the fact that Firebase may be applying a sort to the
// data, so we won't know the correct index for the locally added
// value until the `child_added` event is fired.
// Once we get the `child_added` event, we can check to see if the
// locally added value is in the right place. If it is, we just
// `set` it to the Firebase-provided value. If it is not, then
// we grab the original value, splice in the Firebase-provided
// value in the right place, and then (importantly: at the end)
// find the locally-added value again (since its index may have
// changed by splicing-in Firebase's value) and splice it out of the
// array.
if (this._lastLocallyAddedIndex === index) {
this.set(['data', index], value);
} else {
if (this._lastLocallyAddedIndex != null) {
lastLocallyAddedValue = this.data[this._lastLocallyAddedIndex];
}
this.splice('data', index, 0, value);
if (this._lastLocallyAddedIndex != null) {
this.splice('data', this.data.indexOf(lastLocallyAddedValue), 1);
}
}
});
},
_onFirebaseChildRemoved: function(event) {
if (this._receivingLocalChanges) {
this._valueMap[event.detail.oldChildSnapshot.key()] = null;
// NOTE(cdata): If we are receiving local changes, that means that
// the splices have already been performed and items are already
// removed from the local data representation. No need to remove
// them again.
return;
}
this._applyRemoteDataChange(function() {
var key = event.detail.oldChildSnapshot.key();
var value = this._valueMap[key];
var index;
if (!value) {
this._error('Received firebase-child-removed event for unknown child "' + key + '"');
return;
}
index = this.data.indexOf(value);
this._valueMap[key] = null;
if (index !== -1) {
this.splice('data', index, 1);
}
});
},
_onFirebaseChildChanged: function(event) {
this._applyRemoteDataChange(function() {
var value = this._valueFromSnapshot(event.detail.childSnapshot);
var oldValue = this._valueMap[value.__firebaseKey__];
if (!oldValue) {
this._error('Received firebase-child-changed event for unknown child "' + value.__firebaseKey__ + '"');
return;
}
this._valueMap[oldValue.__firebaseKey__] = null;
this._valueMap[value.__firebaseKey__] = value;
this.set('data.' + this.data.indexOf(oldValue), value);
});
},
_onFirebaseChildMoved: function(event) {
this._applyRemoteDataChange(function() {
var key = event.detail.childSnapshot.key();
var value = this._valueMap[key];
var previousChild;
var newIndex;
var currentIndex;
var previousIndex;
if (!value) {
this._error('Received firebase-child-moved event for unknown child "' + key + '"');
return;
}
previousChild = event.detail.previousChildName != null ?
this._valueMap[event.detail.previousChildName] : null;
currentIndex = this.data.indexOf(value);
previousIndex = previousChild ? this.data.indexOf(previousChild) : -1;
newIndex = currentIndex > previousIndex ? previousIndex + 1 : previousIndex;
this.splice('data', currentIndex, 1);
this.splice('data', newIndex, 0, value);
});
}
});
FirebaseCollection.ORDER_VALUE_TYPES = {
string: String,
number: Number,
boolean: Boolean
};
})();
</script>