Merge branch 'master' into 5720-ajax-loading-error
[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             });
134      }
135 }
136
137 function ping_all_scrollers() {
138     // Send a scroll event to all scroll listeners that might need
139     // updating. Adding infinite-scroller class to the window element
140     // doesn't work, so we add it explicitly here.
141     $('.infinite-scroller').add(window).trigger('scroll');
142 }
143
144 function mergeInfiniteContentParams($container) {
145     var params = {};
146     // Combine infiniteContentParams from multiple sources. This
147     // mechanism allows each of several components to set and
148     // update its own set of filters, without having to worry
149     // about stomping on some other component's filters.
150     //
151     // For example, filterable.js writes filters in
152     // infiniteContentParamsFilterable ("search for text foo")
153     // without worrying about clobbering the filters set up by the
154     // tab pane ("only show jobs and pipelines in this tab").
155     $.each($container.data(), function(datakey, datavalue) {
156         // Note: We attach these data to DOM elements using
157         // <element data-foo-bar="baz">. We store/retrieve them
158         // using $('element').data('foo-bar'), although
159         // .data('fooBar') would also work. The "all data" hash
160         // returned by $('element').data(), however, always has
161         // keys like 'fooBar'. In other words, where we have a
162         // choice, we stick with the 'foo-bar' style to be
163         // consistent with HTML. Here, our only option is
164         // 'fooBar'.
165         if (/^infiniteContentParams/.exec(datakey)) {
166             if (datavalue instanceof Object) {
167                 $.each(datavalue, function(hkey, hvalue) {
168                     if (hvalue instanceof Array) {
169                         params[hkey] = (params[hkey] || []).
170                             concat(hvalue);
171                     } else if (hvalue instanceof Object) {
172                         $.extend(params[hkey], hvalue);
173                     } else {
174                         params[hkey] = hvalue;
175                     }
176                 });
177             }
178         }
179     });
180     return params;
181 }
182
183 function setColumnSort( $container, $header, direction ) {
184     // $container should be the tbody or whatever has all the infinite table data attributes
185     // $header should be the th with a preset data-sort-order attribute
186     // direction should be "asc" or "desc"
187     // This function returns the order by clause for this column header as a string
188
189     // First reset all sort directions
190     $('th[data-sort-order]').removeData('sort-order-direction');
191     // set the current one
192     $header.data('sort-order-direction', direction);
193     // change the ordering parameter
194     var paramsAttr = 'infinite-content-params-' + $container.data('infinite-content-params-attr');
195     var params = $container.data(paramsAttr) || {};
196     params.order = $header.data('sort-order').split(",").join( ' ' + direction + ', ' ) + ' ' + direction;
197     $container.data(paramsAttr, params);
198     // show the correct icon next to the column header
199     $container.trigger('sort-icons');
200
201     return params.order;
202 }
203
204 $(document).
205     on('click', 'div.infinite-retry button', function() {
206         var $retry_div = $(this).closest('.infinite-retry');
207         var $container = $(this).closest('.infinite-scroller-ready')
208         $container.attr('data-infinite-content-href',
209                         $retry_div.attr('data-infinite-content-href'));
210         $retry_div.
211             replaceWith('<div class="spinner spinner-32px spinner-h-center" />');
212         ping_all_scrollers();
213     }).
214     on('refresh-content', '[data-infinite-scroller]', function() {
215         // Clear all rows, reset source href to initial state, and
216         // (if the container is visible) start loading content.
217         var first_page_href = $(this).attr('data-infinite-content-href0');
218         if (!first_page_href)
219             first_page_href = $(this).attr('data-infinite-content-href');
220         $(this).
221             html('').
222             attr('data-infinite-content-href', first_page_href);
223         ping_all_scrollers();
224     }).
225     on('ready ajax:complete', function() {
226         $('[data-infinite-scroller]').each(function() {
227             if ($(this).hasClass('infinite-scroller-ready'))
228                 return;
229             $(this).addClass('infinite-scroller-ready');
230
231             // deal with sorting if there is any, and if it was set on this page for this tab already
232             if( $('th[data-sort-order]').length ) {
233                 var tabId = $(this).closest('div.tab-pane').attr('id');
234                 if( hasHTML5History() && history.state !== undefined && history.state !== null && history.state.order !== undefined && history.state.order[tabId] !== undefined ) {
235                     // we will use the list of one or more table columns associated with this header to find the right element
236                     // see sortable_columns as it is passed to render_pane in the various tab .erbs (e.g. _show_jobs_and_pipelines.html.erb)
237                     var strippedColumns = history.state.order[tabId].replace(/\s|\basc\b|\bdesc\b/g,'');
238                     var sortDirection = history.state.order[tabId].split(" ")[1].replace(/,/,'');
239                     $columnHeader = $(this).closest('table').find('[data-sort-order="'+ strippedColumns +'"]');
240                     setColumnSort( $(this), $columnHeader, sortDirection );
241                 } else {
242                     // otherwise just reset the sort icons
243                     $(this).trigger('sort-icons');
244                 }
245             }
246
247             // $scroller is the DOM element that hears "scroll"
248             // events: sometimes it's a div, sometimes it's
249             // window. Here, "this" is the DOM element containing the
250             // result rows. We pass it to maybe_load_more_content in
251             // event.data.
252             var $scroller = $($(this).attr('data-infinite-scroller'));
253             if (!$scroller.hasClass('smart-scroll') &&
254                 'scroll' != $scroller.css('overflow-y'))
255                 $scroller = $(window);
256             $scroller.
257                 addClass('infinite-scroller').
258                 on('scroll resize', { container: this }, maybe_load_more_content).
259                 trigger('scroll');
260         });
261     }).
262     on('shown.bs.tab', 'a[data-toggle="tab"]', function(event) {
263         $(event.target.getAttribute('href') + ' [data-infinite-scroller]').
264             trigger('scroll');
265     }).
266     on('click', 'th[data-sort-order]', function() {
267         var direction = $(this).data('sort-order-direction');
268         // reverse the current direction, or do ascending if none
269         if( direction === undefined || direction === 'desc' ) {
270             direction = 'asc';
271         } else {
272             direction = 'desc';
273         }
274
275         var $container = $(this).closest('table').find('[data-infinite-content-params-attr]');
276
277         var order = setColumnSort( $container, $(this), direction );
278
279         // put it in the browser history state if browser allows it
280         if( hasHTML5History() ) {
281             var tabId = $(this).closest('div.tab-pane').attr('id');
282             var state =  history.state || {};
283             if( state.order === undefined ) {
284                 state.order = {};
285             }
286             state.order[tabId] = order;
287             history.replaceState( state, null, null );
288         }
289
290         $container.trigger('refresh-content');
291     }).
292     on('sort-icons', function() {
293         // set or reset the icon next to each sortable column header according to the current direction attribute
294         $('th[data-sort-order]').each(function() {
295             $(this).find('i').remove();
296             var direction = $(this).data('sort-order-direction');
297             if( direction !== undefined ) {
298                 $(this).append('<i class="fa fa-sort-' + direction + '"/>');
299             } else {
300                 $(this).append('<i class="fa fa-sort"/>');
301             }
302         });
303     });