-
Notifications
You must be signed in to change notification settings - Fork 0
/
biggus.ts
2100 lines (1796 loc) · 65.1 KB
/
biggus.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
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
/**
* @author Drew Noakes https://drewnoakes.com
*/
function dereferencePath(obj: Object, pathParts: string[]): any
{
var i = 0;
while (obj && i < pathParts.length)
obj = obj[pathParts[i++]];
return obj;
}
function toFixedFix(n: number, prec: number): number
{
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
var k = Math.pow(10, prec);
return Math.round(n * k) / k;
}
function formatNumber(num: number, decimals: number)
{
var n = !isFinite(+num) ? 0 : +num,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
if (s[0].length > 3)
{
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
}
if ((s[1] || '').length < prec)
{
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join('.');
}
export interface IColumn<TRow>
{
/** Populate and style the column's header element. */
styleHeader(th: HTMLTableHeaderCellElement): void;
/** Populate and style a column cell element. */
styleCell(td: HTMLTableCellElement, row: TRow): void;
/** Indicates whether this column may be sorted using getSortValue. */
isSortable: boolean;
/** Returns a value for a given row that can be used when sorting this column. */
getSortValue(row: TRow): any;
/** Indicates whether this column supports filtering, and if so, via what means. */
isFilterable: boolean;
isFiltering: boolean;
/** Fires when <code>filterPredicate</code> changes, and when <code>isFiltering</code> changes. */
filterChanged: Event<IColumn<TRow>>;
filterPredicate: (item: TRow)=>boolean;
getDefaultSortDirection(): SortDirection;
}
export interface IColumnOptions<TRow>
{
/** Text to show in the column's header. */
title?: string;
/** A CSS class name to apply to all th/td elements in the column. */
className?: string;
/** A function that styles the header (th) of the column. */
thStyle?: (th: HTMLTableHeaderCellElement)=>void;
/** A function that styles the data cells (td) of the column. */
tdStyle?: (td: HTMLTableCellElement, row: TRow)=>void;
/** Whether the column should sort ascending or descending by default. Optional. */
defaultSortDirection?: SortDirection;
}
export interface ITextColumnOptions<TRow> extends IColumnOptions<TRow>
{
/** A dot-separated path to the value on the row object. */
path?: string;
/** A function that returns the text to display for this column/row. */
value?: (row: TRow)=>any;
}
export class ColumnBase<TRow> implements IColumn<TRow>
{
public isSortable: boolean;
public isFilterable: boolean = false;
public isFiltering: boolean = false;
public filterChanged: Event<IColumn<TRow>> = new Event<IColumn<TRow>>();
public filterPredicate: (item: TRow)=>boolean;
constructor(private optionsBase: IColumnOptions<TRow>)
{
this.isSortable = true;
}
public styleHeader(th: HTMLTableHeaderCellElement)
{
if (this.optionsBase.title)
th.textContent = this.optionsBase.title;
if (this.optionsBase.className)
th.className = this.optionsBase.className;
if (this.optionsBase.thStyle)
this.optionsBase.thStyle(th);
}
/**
* Sets the class name (if specified) and calls the styling callback (if specified.)
* Subclasses should set text content or add child nodes as required, then call this base implementation.
*/
public styleCell(td: HTMLTableCellElement, row: TRow)
{
if (this.optionsBase.className)
td.className = this.optionsBase.className;
if (this.optionsBase.tdStyle)
this.optionsBase.tdStyle(td, row);
}
public getSortValue(row: TRow): any { return 0; }
public getDefaultSortDirection()
{
if (this.optionsBase.defaultSortDirection)
return this.optionsBase.defaultSortDirection;
else
return SortDirection.Descending;
}
}
export class TextColumn<TRow> extends ColumnBase<TRow>
{
public pathParts: string[];
constructor(private options: ITextColumnOptions<TRow>)
{
super(options);
if (!options.path == !options.value)
throw new Error("Must provide one of path or value properties.");
if (options.path)
this.pathParts = options.path.split('.');
this.isFilterable = true;
}
public getText(row: TRow): string
{
try
{
if (this.pathParts)
{
var value = dereferencePath(row, this.pathParts);
if (value != null)
return value.toString();
}
else
{
console.assert(!!this.options.value);
var value = this.options.value(row);
return value ? value.toString() : '';
}
}
catch (err)
{
return 'ERROR';
}
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
var text = this.getText(row);
if (text != null)
td.textContent = text;
super.styleCell(td, row);
}
public getSortValue(row: TRow): any
{
try
{
return this.pathParts
? dereferencePath(row, this.pathParts)
: this.options.value(row);
}
catch (err)
{
return undefined;
}
}
public setFilterText(text: string)
{
if (!!text)
{
// TODO do we want to try and escape the regex here? some users will like regex, others will find it surprising
this.isFiltering = true;
try
{
var regex = new RegExp(text, "i");
this.filterPredicate = (item: TRow) => regex.test(this.getText(item));
}
catch (err)
{
// Unable to parse the expression as a regex, so treat it as plain text
this.filterPredicate = (item: TRow) => this.getText(item).indexOf(text) !== -1;
}
}
else
{
this.isFiltering = false;
this.filterPredicate = null;
}
this.filterChanged.raise(this);
}
public getDefaultSortDirection()
{
if (this.options.defaultSortDirection)
return this.options.defaultSortDirection;
else
return SortDirection.Ascending;
}
}
/** A column that presents its contents in a solid tile positioned within the cell and not necessarily flush to its edges. */
export class TextTileColumn<TRow> extends TextColumn<TRow>
{
constructor(options: ITextColumnOptions<TRow>)
{
super(options);
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
super.styleCell(td, row);
var text = td.textContent;
td.textContent = null;
var div = document.createElement('div');
div.textContent = text;
div.className = 'tile';
td.appendChild(div);
}
}
export interface INumericColumnOptions<TRow> extends IColumnOptions<TRow>
{
/** A dot-separated path to the value on the row object. */
path?: string;
/** A function that returns the text to display for this column/row. */
value?: (row: TRow)=>number;
/** The number of decimal places after the zero to display. */
precision?: number;
/** Whether to hide zero valued cells. Default to false. */
hideZero?: boolean;
/** Whether to hide NaN valued cells. Default to false. */
hideNaN?: boolean;
/** Whether to sort on absolute numeric values. Defaults to false. */
sortAbsolute?: boolean;
}
export class NumericColumn<TRow> extends TextColumn<TRow>
{
constructor(private numericOptions: INumericColumnOptions<TRow>)
{
super(numericOptions);
// TODO implement filtering for numeric columns
this.isFilterable = false;
if (this.numericOptions.precision == null) this.numericOptions.precision = 0;
if (this.numericOptions.hideZero == null) this.numericOptions.hideZero = false;
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
super.styleCell(td, row);
td.classList.add('numeric');
}
public styleHeader(th: HTMLTableHeaderCellElement)
{
super.styleHeader(th);
th.classList.add('numeric');
}
public getText(row: TRow): string
{
var value: any;
try
{
value = this.pathParts
? dereferencePath(row, this.pathParts)
: this.numericOptions.value(row);
}
catch (err)
{
value = 'ERROR';
}
if (value == null)
return '';
console.assert(typeof(value) === 'number');
if (value === 0 && this.numericOptions.hideZero)
return '';
if (isNaN(value) && this.numericOptions.hideNaN)
return '';
return formatNumber(value, this.numericOptions.precision);
}
public getSortValue(row: TRow): any
{
var value;
try
{
value = super.getSortValue(row);
}
catch (err)
{
return undefined;
}
if (isNaN(value) || value == null)
return undefined;
return this.numericOptions.sortAbsolute
? Math.abs(value)
: value;
}
public getDefaultSortDirection()
{
if (this.numericOptions.defaultSortDirection)
return this.numericOptions.defaultSortDirection;
else
return SortDirection.Descending;
}
}
export interface IImageColumnOptions<TRow> extends IColumnOptions<TRow>
{
/** A dot-separated path to the value on the row object. */
url?: string;
lowerCase?: boolean;
/** Indicates whether this column may be sorted. Defaults to false. */
isSortable?: boolean;
}
var imagePathRegExp = new RegExp('^(.*)\\{(.*)\\}(.*)$');
export class ImageColumn<TRow> extends ColumnBase<TRow>
{
private pathParts: string[];
private urlPrefix: string;
private urlSuffix: string;
constructor(private options: IImageColumnOptions<TRow>)
{
super(options);
this.isSortable = !!options.isSortable;
if (!options.url)
throw new Error("Must provide a url.");
var groups = imagePathRegExp.exec(options.url);
this.urlPrefix = groups[1];
this.pathParts = groups[2].split('.');
this.urlSuffix = groups[3];
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
var data = dereferencePath(row, this.pathParts);
if (data)
{
var img = new Image();
var src = this.urlPrefix + data + this.urlSuffix;
if (this.options.lowerCase)
src = src.toLowerCase();
img.src = src;
td.appendChild(img);
}
super.styleCell(td, row);
}
}
export interface ISpriteImageColumn<TRow> extends IColumnOptions<TRow>
{
value: (row:TRow) => string;
spriteClassPrefix: string;
}
export class SpriteImageColumn<TRow> extends ColumnBase<TRow>
{
constructor(private options: ISpriteImageColumn<TRow>)
{
super(options);
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
try
{
var d = document.createElement('div');
var val = this.options.value(row);
if (val)
{
d.className = this.options.spriteClassPrefix;
d.classList.add(val);
}
td.appendChild(d);
}
catch (err)
{}
super.styleCell(td, row);
}
public getSortValue(row: TRow): any { return this.options.value(row); }
}
export interface IBarChartColumnOptions<TRow> extends IColumnOptions<TRow>
{
ratio: (row: TRow)=>number;
color: (ratio: number)=>string;
}
export class BarChartColumn<TRow> extends ColumnBase<TRow>
{
constructor(private options: IBarChartColumnOptions<TRow>)
{
super(options);
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
try
{
var ratio = this.options.ratio(row);
var bar = document.createElement('div');
bar.className = 'bar';
bar.style.width = (100* ratio) + '%';
bar.style.backgroundColor = this.options.color(ratio);
td.appendChild(bar);
}
catch (err)
{}
super.styleCell(td, row);
}
public getSortValue(row: TRow): any { return this.options.ratio(row); }
}
export enum ActionPresentationType
{
Hyperlink,
Button
}
export interface IActionColumnOptions<TRow> extends IColumnOptions<TRow>
{
text: string;
action: (row: TRow)=>void;
type?: ActionPresentationType;
/** Indicates whether this column may be sorted. Defaults to false. */
isSortable?: boolean;
}
export class ActionColumn<TRow> extends ColumnBase<TRow>
{
constructor(private options: IActionColumnOptions<TRow>)
{
super(options);
this.isSortable = !!options.isSortable;
}
public styleCell(td: HTMLTableCellElement, row: TRow)
{
td.classList.add('action');
if (this.options.type === ActionPresentationType.Button)
{
var button = document.createElement('button');
button.className = 'action';
button.textContent = this.options.text;
button.addEventListener('click', e => { e.preventDefault(); this.options.action(row); });
td.classList.add('button');
td.appendChild(button);
}
else
{
var a = document.createElement('a');
a.className = 'action';
a.href = '#';
a.textContent = this.options.text;
a.addEventListener('click', e => { e.preventDefault(); this.options.action(row); });
td.classList.add('link');
td.appendChild(a);
}
super.styleCell(td, row);
}
public styleHeader(th: HTMLTableHeaderCellElement)
{
th.classList.add('action');
th.classList.add(this.options.type === ActionPresentationType.Button ? 'button' : 'link');
if (this.options.className)
th.classList.add(this.options.className);
}
}
export interface IGridOptions<TRow>
{
columns: IColumn<TRow>[];
rowClassName?: (rowData: TRow) => string;
}
interface IRowModel<TRow>
{
row: TRow;
tr: HTMLTableRowElement;
}
export class Event<T>
{
private callbacks: {(item:T):void}[] = [];
public subscribe(callback: (item: T)=>void): ()=>void
{
this.callbacks.push(callback);
return () =>
{
var index = this.callbacks.indexOf(callback);
if (index === -1)
console.warn("Attempt to unsubscribe unknown subscriber");
else
this.callbacks.splice(index, 1);
};
}
public raise(item: T)
{
for (var i = 0; i < this.callbacks.length; i++)
this.callbacks[i](item);
}
public getSubscriberCount() { return this.callbacks.length; }
public collect(handler: (args:T[])=>void)
{
var args: T[] = [];
var cancelSubscription = this.subscribe(a => args.push(a));
handler(args);
cancelSubscription();
}
}
export function clearChildren(el: Element)
{
while (el.hasChildNodes()) {
el.removeChild(el.lastChild);
}
}
export enum SortDirection
{
Ascending,
Descending
}
export interface INotifyChange<T>
{
subscribeChange(callback: (item:T)=>void): ()=>void;
notifyChange(): void;
}
class NotifyChange
{
private callbacks: {(item:any):void}[];
public subscribeChange(callback: (item:any)=>void): ()=>void
{
if (!this.callbacks)
this.callbacks = [];
this.callbacks.push(callback);
return () =>
{
var index = this.callbacks.indexOf(callback);
if (index === -1)
console.warn("Attempt to unsubscribe unknown subscriber");
else
this.callbacks.splice(index, 1);
};
}
public notifyChange(): void
{
if (this.callbacks)
{
for (var i = 0; i < this.callbacks.length; i++)
this.callbacks[i](this);
}
}
}
var notifyChangePrototype = Object.create(NotifyChange.prototype);
export function mixinNotifyChange(obj: any)
{
obj.__proto__ = notifyChangePrototype;
}
export enum CollectionChangeType
{
/** An item is to be inserted at the specified position. */
Insert = 0,
/** An item's value has changed, and it should be updated in place. Neither position nor ID change. */
Update = 1,
/** An item is to be removed at the specified position. */
Remove = 2,
/** An item is to be moved to a new position. It should also be refreshed as its value has changed. */
Move = 3,
/** Considerable changes to the collection have occurred and clients should rebuild their views. */
Reset = 4,
/** An item in the collection is being replaced with another. ID changes and position may as well. */
Replace = 5,
/** The collection has changed outside the viewable window in a way that effects scroll position. */
Scroll = 6
}
export class CollectionChange<T>
{
public type: CollectionChangeType;
public item: T;
public itemId: string;
public newIndex: number;
public oldItem: T;
public oldItemId: string;
public oldIndex: number;
public isNewlyAdded: boolean;
public static insert<U>(item: U, itemId: string, index: number, isNewlyAdded: boolean): CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Insert;
chg.item = item;
chg.itemId = itemId;
chg.newIndex = index;
chg.oldIndex = -1;
chg.isNewlyAdded = isNewlyAdded;
return chg;
}
public static remove<U>(item: U, itemId: string, index: number): CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Remove;
chg.item = item;
chg.itemId = itemId;
chg.newIndex = -1;
chg.oldIndex = index;
return chg;
}
public static replace<U>(oldItem: U, oldItemId: string, oldIndex: number, newItem: U, newItemId: string, newIndex: number, isNewlyAdded: boolean): CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Replace;
chg.item = newItem;
chg.itemId = newItemId;
chg.newIndex = newIndex;
chg.oldItem = oldItem;
chg.oldItemId = oldItemId;
chg.oldIndex = oldIndex;
return chg;
}
public static update<U>(item: U, itemId: string, index: number): CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Update;
chg.item = item;
chg.itemId = itemId;
chg.newIndex = index;
chg.oldIndex = -1;
return chg;
}
public static move<U>(item: U, itemId: string, oldIndex: number, newIndex: number): CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Move;
chg.item = item;
chg.itemId = itemId;
chg.oldIndex = oldIndex;
chg.newIndex = newIndex;
return chg;
}
public static reset<U>() : CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Reset;
chg.item = null;
chg.itemId = null;
chg.newIndex = -1;
chg.oldIndex = -1;
return chg;
}
public static scroll<U>() : CollectionChange<U>
{
var chg = new CollectionChange<U>();
chg.type = CollectionChangeType.Scroll;
chg.item = null;
chg.itemId = null;
chg.newIndex = -1;
chg.oldIndex = -1;
return chg;
}
}
export interface IObservableCollection<T>
{
changed: Event<CollectionChange<T>>;
}
export interface IDataSource<T> extends IObservableCollection<T>
{
getAllItems(): T[];
getItemId(item: T): string;
}
/**
* A basic, observable, append-only data source.
*/
export class DataSource<T> implements IDataSource<T>
{
public changed: Event<CollectionChange<T>> = new Event<CollectionChange<T>>();
private items: T[] = [];
private itemById: {[id: string]: T} = {};
constructor(itemIdAccessor: (item: T)=>string, items?: T[])
{
this.getItemId = itemIdAccessor.bind(this);
for (var i = 0; items && i < items.length; i++) {
this.add(items[i]);
}
}
public add(item: T)
{
var itemId = this.getItemId(item);
if (!!this.itemById[itemId])
throw new Error("Attempting to add item with ID '" + itemId + "', but that ID already exists.");
this.subscribeItemUpdates(item);
// Append new item
this.items.push(item);
this.changed.raise(CollectionChange.insert(item, itemId, this.items.length - 1, true));
this.itemById[itemId] = item;
}
public addRange(items: T[])
{
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var itemId = this.getItemId(item);
if (!!this.itemById[itemId])
throw new Error("Attempting to add item with ID '" + itemId + "', but that ID already exists.");
this.subscribeItemUpdates(item);
// Append new item
this.items.push(item);
this.itemById[itemId] = item;
}
// TODO should we always reset? what if only one item is added? what's a good heuristic here?
this.changed.raise(CollectionChange.reset<T>());
this.changed.raise(CollectionChange.scroll<T>());
}
private subscribeItemUpdates(item: T)
{
var itemId = this.getItemId(item);
var notifyItem: INotifyChange<T> = <any>item;
if (notifyItem.subscribeChange && typeof(notifyItem.subscribeChange) === 'function') {
notifyItem.subscribeChange(changedItem => {
// TODO is this O(N) scan a problem?
var index = this.items.indexOf(changedItem);
this.changed.raise(CollectionChange.update(changedItem, itemId, index));
});
}
}
public removeAt(index: number)
{
var removed = this.items.splice(index, 1)[0];
var itemId = this.getItemId(removed);
delete this.itemById[itemId];
this.changed.raise(CollectionChange.remove(removed, this.getItemId(removed), index));
}
public move(oldIndex: number, newIndex: number)
{
console.assert(oldIndex >= 0);
console.assert(newIndex >= 0);
var item = this.items.splice(oldIndex, 1)[0];
this.items.splice(newIndex, 0, item);
this.changed.raise(CollectionChange.move(item, this.getItemId(item), oldIndex, newIndex));
}
public get(index: number)
{
return this.items[index];
}
public getAllItems(): T[]
{
return this.items;
}
public getById(id: string): T
{
return this.itemById[id];
}
public getItemId(item: T): string
{
throw new Error("Should be rebound in constructor.");
}
public reset()
{
this.changed.raise(CollectionChange.reset<T>());
}
public clear()
{
this.items = [];
this.itemById = {};
this.reset();
}
}
export class FilterView<T> implements IDataSource<T>
{
public changed: Event<CollectionChange<T>> = new Event<CollectionChange<T>>();
private items: T[] = [];
private itemFilterState: {[itemId: string]:boolean} = {};
private predicate: (item: T)=>boolean;
constructor(private source: IDataSource<T>,
predicate?: (item: T)=>boolean)
{
this.getItemId = source.getItemId;
source.changed.subscribe(this.onSourceChanged.bind(this));
this.setPredicate(predicate);
}
private onSourceChanged(event: CollectionChange<T>)
{
var passesFilter = event.item && (!this.predicate || this.predicate(event.item));
switch (event.type)
{
case CollectionChangeType.Insert:
{
console.assert(typeof(this.itemFilterState[event.itemId]) === 'undefined');
this.itemFilterState[event.itemId] = passesFilter;
if (passesFilter)
this.append(event.item, event.itemId, event.isNewlyAdded);
break;
}
case CollectionChangeType.Remove:
{
if (!passesFilter)
return;
delete this.itemFilterState[event.itemId];
this.remove(event.item, event.itemId);
break;
}
case CollectionChangeType.Update:
{
var priorState = this.itemFilterState[event.itemId];
console.assert(typeof(priorState) !== 'undefined');
if (priorState === passesFilter)
{
if (priorState)
{
// TODO this is an O(N) scan -- do consumers of the event even need index here?
var index = this.items.indexOf(event.item);
console.assert(index !== -1);
this.changed.raise(CollectionChange.update(event.item, event.itemId, index));
}
return;
}
this.itemFilterState[event.itemId] = passesFilter;
if (!priorState) {
// Newly passes the filter -- add
this.append(event.item, event.itemId, false);
} else {
// Newly fails the filter -- remove
this.remove(event.item, event.itemId);
}
break;
}
case CollectionChangeType.Move:
{
console.error("Move not supported");
break;
}
case CollectionChangeType.Reset:
{
this.items = [];
this.itemFilterState = {};
var sourceItems = this.source.getAllItems();
if (this.predicate)
{
for (var i = 0; i < sourceItems.length; i++)
{
var item = sourceItems[i];
var matches = this.predicate(item);
this.itemFilterState[this.getItemId(item)] = matches;
if (matches)
this.items.push(item);
}
}
else
{
this.items = this.items.concat(sourceItems);
for (var i = 0; i < sourceItems.length; i++)
this.itemFilterState[this.getItemId(sourceItems[i])] = true;
}
this.changed.raise(event);
break;
}
case CollectionChangeType.Scroll:
{
this.changed.raise(event);
break;
}
}
}
public setPredicate(predicate: (item: T)=>boolean)
{
this.predicate = predicate;
var items = this.source.getAllItems(),
filteredItems: T[] = [],
hasChange = false;
for (var i = 0; i < items.length; i++)
{
var item = items[i],
itemId = this.source.getItemId(item),
passesFilter = !predicate || predicate(item),
priorState = this.itemFilterState[itemId];
if (priorState !== passesFilter)
{
this.itemFilterState[itemId] = passesFilter;
hasChange = true;
}
if (passesFilter)
filteredItems.push(item);
}
if (hasChange)
{
this.items = filteredItems;