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