3618: store in the browser history state the current sort settings for each tab
[arvados.git] / apps / workbench / app / assets / javascripts / infinite_scroll.js
1 function maybe_load_more_content(event) {
2     var scroller = this;        // element with scroll bars
3     var $container;             // element that receives new content
4     var src;                    // url for retrieving content
5     var scrollHeight;
6     var spinner, colspan;
7     var serial = Date.now();
8     var params;
9     scrollHeight = scroller.scrollHeight || $('body')[0].scrollHeight;
10     if ($(scroller).scrollTop() + $(scroller).height()
11         >
12         scrollHeight - 50)
13     {
14         $container = $(event.data.container);
15         if (!$container.attr('data-infinite-content-href0')) {
16             // Remember the first page source url, so we can refresh
17             // from page 1 later.
18             $container.attr('data-infinite-content-href0',
19                             $container.attr('data-infinite-content-href'));
20         }
21         src = $container.attr('data-infinite-content-href');
22         if (!src || !$container.is(':visible'))
23             // Finished
24             return;
25
26         // Don't start another request until this one finishes
27         $container.attr('data-infinite-content-href', null);
28         spinner = '<div class="spinner spinner-32px spinner-h-center"></div>';
29         if ($container.is('table,tbody,thead,tfoot')) {
30             // Hack to determine how many columns a new tr should have
31             // in order to reach full width.
32             colspan = $container.closest('table').
33                 find('tr').eq(0).find('td,th').length;
34             if (colspan == 0)
35                 colspan = '*';
36             spinner = ('<tr class="spinner"><td colspan="' + colspan + '">' +
37                        spinner +
38                        '</td></tr>');
39         }
40         $container.find(".spinner").detach();
41         $container.append(spinner);
42         $container.attr('data-infinite-serial', serial);
43
44         if (src == $container.attr('data-infinite-content-href0')) {
45             // If we're loading the first page, collect filters from
46             // various sources.
47             params = mergeInfiniteContentParams($container);
48             $.each(params, function(k,v) {
49                 if (v instanceof Object) {
50                     params[k] = JSON.stringify(v);
51                 }
52             });
53         } else {
54             // If we're loading page >1, ignore other filtering
55             // mechanisms and just use the "next page" URI from the
56             // previous page's response. Aside from avoiding race
57             // conditions (where page 2 could have different filters
58             // than page 1), this allows the server to use filters in
59             // the "next page" URI to achieve paging. (To apply any
60             // new filters effectively, we need to load page 1 again
61             // anyway.)
62             params = {};
63         }
64
65         $.ajax(src,
66                {dataType: 'json',
67                 type: 'GET',
68                 data: params,
69                 context: {container: $container, src: src, serial: serial}}).
70             fail(function(jqxhr, status, error) {
71                 var $faildiv;
72                 var $container = this.container;
73                 if ($container.attr('data-infinite-serial') != this.serial) {
74                     // A newer request is already in progress.
75                     return;
76                 }
77                 if (jqxhr.readyState == 0 || jqxhr.status == 0) {
78                     message = "Cancelled."
79                 } else if (jqxhr.responseJSON && jqxhr.responseJSON.errors) {
80                     message = jqxhr.responseJSON.errors.join("; ");
81                 } else {
82                     message = "Request failed.";
83                 }
84                 // TODO: report the message to the user.
85                 console.log(message);
86                 $faildiv = $('<div />').
87                     attr('data-infinite-content-href', this.src).
88                     addClass('infinite-retry').
89                     append('<span class="fa fa-warning" /> Oops, request failed. <button class="btn btn-xs btn-primary">Retry</button>');
90                 $container.find('div.spinner').replaceWith($faildiv);
91             }).
92             done(function(data, status, jqxhr) {
93                 if ($container.attr('data-infinite-serial') != this.serial) {
94                     // A newer request is already in progress.
95                     return;
96                 }
97                 $container.find(".spinner").detach();
98                 $container.append(data.content);
99                 $container.attr('data-infinite-content-href', data.next_page_href);
100             });
101      }
102 }
103
104 function ping_all_scrollers() {
105     // Send a scroll event to all scroll listeners that might need
106     // updating. Adding infinite-scroller class to the window element
107     // doesn't work, so we add it explicitly here.
108     $('.infinite-scroller').add(window).trigger('scroll');
109 }
110
111 function mergeInfiniteContentParams($container) {
112     var params = {};
113     // Combine infiniteContentParams from multiple sources. This
114     // mechanism allows each of several components to set and
115     // update its own set of filters, without having to worry
116     // about stomping on some other component's filters.
117     //
118     // For example, filterable.js writes filters in
119     // infiniteContentParamsFilterable ("search for text foo")
120     // without worrying about clobbering the filters set up by the
121     // tab pane ("only show jobs and pipelines in this tab").
122     $.each($container.data(), function(datakey, datavalue) {
123         // Note: We attach these data to DOM elements using
124         // <element data-foo-bar="baz">. We store/retrieve them
125         // using $('element').data('foo-bar'), although
126         // .data('fooBar') would also work. The "all data" hash
127         // returned by $('element').data(), however, always has
128         // keys like 'fooBar'. In other words, where we have a
129         // choice, we stick with the 'foo-bar' style to be
130         // consistent with HTML. Here, our only option is
131         // 'fooBar'.
132         if (/^infiniteContentParams/.exec(datakey)) {
133             if (datavalue instanceof Object) {
134                 $.each(datavalue, function(hkey, hvalue) {
135                     if (hvalue instanceof Array) {
136                         params[hkey] = (params[hkey] || []).
137                             concat(hvalue);
138                     } else if (hvalue instanceof Object) {
139                         $.extend(params[hkey], hvalue);
140                     } else {
141                         params[hkey] = hvalue;
142                     }
143                 });
144             }
145         }
146     });
147     return params;
148 }
149
150 function setColumnSort( $container, $header, direction ) {
151     // $container should be the tbody or whatever has all the infinite table data attributes
152     // $header should be the th with a preset data-sort-order attribute
153     // direction should be "asc" or "desc"
154     // This function returns the order by clause for this column header as a string
155
156     // First reset all sort directions
157     $('th[data-sort-order]').removeData('sort-order-direction');
158     // set the current one
159     $header.data('sort-order-direction', direction);
160     // change the ordering parameter
161     var paramsAttr = 'infinite-content-params-' + $container.data('infinite-content-params-attr');
162     var params = $container.data(paramsAttr) || {};
163     params.order = $header.data('sort-order').split(",").join( ' ' + direction + ', ' ) + ' ' + direction;
164     $container.data(paramsAttr, params);
165     // show the right icon next to the column header
166     $container.trigger('sortIcons');
167
168     return params.order;
169 }
170
171 $(document).
172     on('click', 'div.infinite-retry button', function() {
173         var $retry_div = $(this).closest('.infinite-retry');
174         var $container = $(this).closest('.infinite-scroller-ready')
175         $container.attr('data-infinite-content-href',
176                         $retry_div.attr('data-infinite-content-href'));
177         $retry_div.
178             replaceWith('<div class="spinner spinner-32px spinner-h-center" />');
179         ping_all_scrollers();
180     }).
181     on('refresh-content', '[data-infinite-scroller]', function() {
182         // Clear all rows, reset source href to initial state, and
183         // (if the container is visible) start loading content.
184         var first_page_href = $(this).attr('data-infinite-content-href0');
185         if (!first_page_href)
186             first_page_href = $(this).attr('data-infinite-content-href');
187         $(this).
188             html('').
189             attr('data-infinite-content-href', first_page_href);
190         ping_all_scrollers();
191     }).
192     on('ready ajax:complete', function() {
193         $('[data-infinite-scroller]').each(function() {
194             if ($(this).hasClass('infinite-scroller-ready'))
195                 return;
196             $(this).addClass('infinite-scroller-ready');
197
198             // deal with sorting if was set on this page for this tab already
199             var tabId = $(this).closest('div.tab-pane').attr('id');
200             if( typeof(history.state.order) !== 'undefined' && typeof(history.state.order[tabId]) !== 'undefined' ) {
201                 // we will use the list of one or more table columns associated with this header to find the right element
202                 // see sortable_columns as it is passed to render_pane in the various tab .erbs (e.g. _show_jobs_and_pipelines.html.erb)
203                 var strippedColumns = history.state.order[tabId].replace(/\s|asc|desc/g,'');
204                 var sortDirection = history.state.order[tabId].split(" ")[1].replace(/,/,'');
205                 $columnHeader = $(this).closest('table').find('[data-sort-order="'+ strippedColumns +'"]');
206                 setColumnSort( $(this), $columnHeader, sortDirection );
207             } else {
208                 // otherwise just reset the sort icons
209                 $(this).trigger('sortIcons');
210             }
211
212             // $scroller is the DOM element that hears "scroll"
213             // events: sometimes it's a div, sometimes it's
214             // window. Here, "this" is the DOM element containing the
215             // result rows. We pass it to maybe_load_more_content in
216             // event.data.
217             var $scroller = $($(this).attr('data-infinite-scroller'));
218             if (!$scroller.hasClass('smart-scroll') &&
219                 'scroll' != $scroller.css('overflow-y'))
220                 $scroller = $(window);
221             $scroller.
222                 addClass('infinite-scroller').
223                 on('scroll resize', { container: this }, maybe_load_more_content).
224                 trigger('scroll');
225         });
226     }).
227     on('click', 'th[data-sort-order]', function() {
228         var direction = $(this).data('sort-order-direction');
229         // reverse the current direction, or do ascending if none
230         if( typeof(direction) === 'undefined' || direction === 'desc' ) {
231             direction = 'asc';
232         } else {
233             direction = 'desc';
234         }
235
236         var $container = $(this).closest('table').find('[data-infinite-content-params-attr]');
237
238         var order = setColumnSort( $container, $(this), direction );
239
240         // put it in the browser history state
241         var tabId = $(this).closest('div.tab-pane').attr('id');
242         var state =  history.state;
243         if( typeof(state.order) === 'undefined') {
244             state.order = {};
245         }
246         state.order[tabId] = order;
247         history.replaceState( state, null, null );
248
249         $container.trigger('refresh-content');
250     }).
251     on('sortIcons', function() {
252         // set or reset the icon next to each sortable column header according to the current direction attribute
253         $('th[data-sort-order]').each(function() {
254             $(this).find('i').remove();
255             var direction = $(this).data('sort-order-direction');
256             if( typeof(direction) !== 'undefined' ) {
257                 $(this).append('<i class="fa fa-sort-' + direction + '"/>');
258             } else {
259                 $(this).append('<i class="fa fa-sort"/>');
260             }
261         });
262     });