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