summaryrefslogtreecommitdiff
path: root/xstatic/pkg/angular_smart_table/data/smart-table.js
blob: d5cd473725a6cafb987d8ea0c1e5b18c72fc3daa (plain)
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
/** 
* @version 1.4.5
* @license MIT
*/
(function (ng, undefined){
    'use strict';

ng.module('smart-table', []).run(['$templateCache', function ($templateCache) {
    $templateCache.put('template/smart-table/pagination.html',
        '<div class="pagination" ng-if="pages.length >= 2"><ul class="pagination">' +
        '<li ng-repeat="page in pages" ng-class="{active: page==currentPage}"><a ng-click="selectPage(page)">{{page}}</a></li>' +
        '</ul></div>');
}]);


ng.module('smart-table')
    .controller('stTableController', ['$scope', '$parse', '$filter', '$attrs', function StTableController($scope, $parse, $filter, $attrs) {
        var propertyName = $attrs.stTable;
        var displayGetter = $parse(propertyName);
        var displaySetter = displayGetter.assign;
        var safeGetter;
        var orderBy = $filter('orderBy');
        var filter = $filter('filter');
        var safeCopy = copyRefs(displayGetter($scope));
        var tableState = {
            sort: {},
            search: {},
            pagination: {
                start: 0
            }
        };
        var pipeAfterSafeCopy = true;
        var ctrl = this;
        var lastSelected;

        function copyRefs(src) {
            return [].concat(src);
        }

        function updateSafeCopy() {
            safeCopy = copyRefs(safeGetter($scope));
            if (pipeAfterSafeCopy === true) {
                ctrl.pipe();
            }
        }

        if ($attrs.stSafeSrc) {
            safeGetter = $parse($attrs.stSafeSrc);
            $scope.$watch(function () {
                var safeSrc = safeGetter($scope);
                return safeSrc ? safeSrc.length : 0;

            }, function (newValue, oldValue) {
                if (newValue !== safeCopy.length) {
                    updateSafeCopy();
                }
            });
            $scope.$watch(function () {
                return safeGetter($scope);
            }, function (newValue, oldValue) {
                if (newValue !== oldValue) {
                    updateSafeCopy();
                }
            });
        }

        /**
         * sort the rows
         * @param {Function | String} predicate - function or string which will be used as predicate for the sorting
         * @param [reverse] - if you want to reverse the order
         */
        this.sortBy = function sortBy(predicate, reverse) {
            tableState.sort.predicate = predicate;
            tableState.sort.reverse = reverse === true;
            tableState.pagination.start = 0;
            return this.pipe();
        };

        /**
         * search matching rows
         * @param {String} input - the input string
         * @param {String} [predicate] - the property name against you want to check the match, otherwise it will search on all properties
         */
        this.search = function search(input, predicate) {
            var predicateObject = tableState.search.predicateObject || {};
            var prop = predicate ? predicate : '$';
            predicateObject[prop] = input;
            // to avoid to filter out null value
            if (!input) {
                delete predicateObject[prop];
            }
            tableState.search.predicateObject = predicateObject;
            tableState.pagination.start = 0;
            return this.pipe();
        };

        /**
         * this will chain the operations of sorting and filtering based on the current table state (sort options, filtering, ect)
         */
        this.pipe = function pipe() {
            var pagination = tableState.pagination;
            var filtered = tableState.search.predicateObject ? filter(safeCopy, tableState.search.predicateObject) : safeCopy;
            if (tableState.sort.predicate) {
                filtered = orderBy(filtered, tableState.sort.predicate, tableState.sort.reverse);
            }
            if (pagination.number !== undefined) {
                pagination.numberOfPages = filtered.length > 0 ? Math.ceil(filtered.length / pagination.number) : 1;
                pagination.start = pagination.start >= filtered.length ? (pagination.numberOfPages - 1) * pagination.number : pagination.start;
                filtered = filtered.slice(pagination.start, pagination.start + pagination.number);
            }
            displaySetter($scope, filtered);
        };

        /**
         * select a dataRow (it will add the attribute isSelected to the row object)
         * @param {Object} row - the row to select
         * @param {String} [mode] - "single" or "multiple" (multiple by default)
         */
        this.select = function select(row, mode) {
            var rows = safeCopy;
            var index = rows.indexOf(row);
            if (index !== -1) {
                if (mode === 'single') {
                    row.isSelected = row.isSelected !== true;
                    if (lastSelected) {
                        lastSelected.isSelected = false;
                    }
                    lastSelected = row.isSelected === true ? row : undefined;
                } else {
                    rows[index].isSelected = !rows[index].isSelected;
                }
            }
        };

        /**
         * take a slice of the current sorted/filtered collection (pagination)
         *
         * @param {Number} start - start index of the slice
         * @param {Number} number - the number of item in the slice
         */
        this.slice = function splice(start, number) {
            tableState.pagination.start = start;
            tableState.pagination.number = number;
            return this.pipe();
        };

        /**
         * return the current state of the table
         * @returns {{sort: {}, search: {}, pagination: {start: number}}}
         */
        this.tableState = function getTableState() {
            return tableState;
        };

        /**
         * Use a different filter function than the angular FilterFilter
         * @param filterName the name under which the custom filter is registered
         */
        this.setFilterFunction = function setFilterFunction(filterName) {
            filter = $filter(filterName);
        };

        /**
         *User a different function than the angular orderBy
         * @param sortFunctionName the name under which the custom order function is registered
         */
        this.setSortFunction = function setSortFunction(sortFunctionName) {
            orderBy = $filter(sortFunctionName);
        };

        /**
         * Usually when the safe copy is updated the pipe function is called.
         * Calling this method will prevent it, which is something required when using a custom pipe function
         */
        this.preventPipeOnWatch = function preventPipe() {
            pipeAfterSafeCopy = false;
        };
    }])
    .directive('stTable', function () {
        return {
            restrict: 'A',
            controller: 'stTableController',
            link: function (scope, element, attr, ctrl) {

                if (attr.stSetFilter) {
                    ctrl.setFilterFunction(attr.stSetFilter);
                }

                if (attr.stSetSort) {
                    ctrl.setSortFunction(attr.stSetSort);
                }
            }
        };
    });

ng.module('smart-table')
    .directive('stSearch', ['$timeout', function ($timeout) {
        return {
            require: '^stTable',
            scope: {
                predicate: '=?stSearch'
            },
            link: function (scope, element, attr, ctrl) {
                var tableCtrl = ctrl;
                var promise = null;
                var throttle = attr.stDelay || 400;

                scope.$watch('predicate', function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        ctrl.tableState().search = {};
                        tableCtrl.search(element[0].value || '', newValue);
                    }
                });

                //table state -> view
                scope.$watch(function () {
                    return ctrl.tableState().search;
                }, function (newValue, oldValue) {
                    var predicateExpression = scope.predicate || '$';
                    if (newValue.predicateObject && newValue.predicateObject[predicateExpression] !== element[0].value) {
                        element[0].value = newValue.predicateObject[predicateExpression] || '';
                    }
                }, true);

                // view -> table state
                element.bind('input', function (evt) {
                    evt = evt.originalEvent || evt;
                    if (promise !== null) {
                        $timeout.cancel(promise);
                    }
                    promise = $timeout(function () {
                        tableCtrl.search(evt.target.value, scope.predicate || '');
                        promise = null;
                    }, throttle);
                });
            }
        };
    }]);

ng.module('smart-table')
    .directive('stSelectRow', function () {
        return {
            restrict: 'A',
            require: '^stTable',
            scope: {
                row: '=stSelectRow'
            },
            link: function (scope, element, attr, ctrl) {
                var mode = attr.stSelectMode || 'single';
                element.bind('click', function () {
                    scope.$apply(function () {
                        ctrl.select(scope.row, mode);
                    });
                });

                scope.$watch('row.isSelected', function (newValue, oldValue) {
                    if (newValue === true) {
                        element.addClass('st-selected');
                    } else {
                        element.removeClass('st-selected');
                    }
                });
            }
        };
    });

ng.module('smart-table')
    .directive('stSort', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            require: '^stTable',
            link: function (scope, element, attr, ctrl) {

                var predicate = attr.stSort;
                var getter = $parse(predicate);
                var index = 0;
                var classAscent = attr.stClassAscent || 'st-sort-ascent';
                var classDescent = attr.stClassDescent || 'st-sort-descent';
                var stateClasses = [classAscent, classDescent];

                //view --> table state
                function sort() {
                    index++;
                    if (index % 3 === 0 && attr.stSkipNatural === undefined) {
                        //manual reset
                        index = 0;
                        ctrl.tableState().sort = {};
                        ctrl.tableState().pagination.start = 0;
                        ctrl.pipe();
                    } else {
                        ctrl.sortBy(predicate, index % 2 === 0);
                    }
                }

                if (ng.isFunction(getter(scope))) {
                    predicate = getter(scope);
                }

                element.bind('click', function sortClick() {
                    if (predicate) {
                        scope.$apply(sort);
                    }
                });

                if (attr.stSortDefault !== undefined) {
                    index = attr.stSortDefault === 'reverse' ? 1 : 0;
                    sort();
                }

                //table state --> view
                scope.$watch(function () {
                    return ctrl.tableState().sort;
                }, function (newValue) {
                    if (newValue.predicate !== predicate) {
                        index = 0;
                        element
                            .removeClass(classAscent)
                            .removeClass(classDescent);
                    } else {
                        index = newValue.reverse === true ? 2 : 1;
                        element
                            .removeClass(stateClasses[index % 2])
                            .addClass(stateClasses[index - 1]);
                    }
                }, true);
            }
        };
    }]);

ng.module('smart-table')
    .directive('stPagination', function () {
        return {
            restrict: 'EA',
            require: '^stTable',
            scope: {
                stItemsByPage: '=?',
                stDisplayedPages: '=?'
            },
            templateUrl: function(element, attrs) {
              if (attrs.stTemplate) {
                return attrs.stTemplate;
              }
              return 'template/smart-table/pagination.html';
            },
            link: function (scope, element, attrs, ctrl) {

                scope.stItemsByPage = scope.stItemsByPage ? +(scope.stItemsByPage) : 10;
                scope.stDisplayedPages = scope.stDisplayedPages ? +(scope.stDisplayedPages) : 5;

                scope.currentPage = 1;
                scope.pages = [];

                function redraw() {
                    var paginationState = ctrl.tableState().pagination;
                    var start = 1;
                    var end;
                    var i;
                    scope.currentPage = Math.floor(paginationState.start / paginationState.number) + 1;

                    start = Math.max(start, scope.currentPage - Math.abs(Math.floor(scope.stDisplayedPages / 2)));
                    end = start + scope.stDisplayedPages;

                    if (end > paginationState.numberOfPages) {
                        end = paginationState.numberOfPages + 1;
                        start = Math.max(1, end - scope.stDisplayedPages);
                    }

                    scope.pages = [];
                    scope.numPages = paginationState.numberOfPages;

                    for (i = start; i < end; i++) {
                        scope.pages.push(i);
                    }
                }

                //table state --> view
                scope.$watch(function () {
                    return ctrl.tableState().pagination;
                }, redraw, true);

                //scope --> table state  (--> view)
                scope.$watch('stItemsByPage', function () {
                    scope.selectPage(1);
                });

                scope.$watch('stDisplayedPages', redraw);

                //view -> table state
                scope.selectPage = function (page) {
                    if (page > 0 && page <= scope.numPages) {
                        ctrl.slice((page - 1) * scope.stItemsByPage, scope.stItemsByPage);
                    }
                };

                //select the first page
                ctrl.slice(0, scope.stItemsByPage);
            }
        };
    });

ng.module('smart-table')
    .directive('stPipe', function () {
        return {
            require: 'stTable',
            scope: {
                stPipe: '='
            },
            link: {
                pre: function (scope, element, attrs, ctrl) {

                    if (ng.isFunction(scope.stPipe)) {
                        ctrl.preventPipeOnWatch();
                        ctrl.pipe = function () {
                            return scope.stPipe(ctrl.tableState(), ctrl);
                        }
                    }
                }
            }
        };
    });

})(angular);