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.
6 // 1. Adding infinite scrolling to a tab pane using "show" method
8 // The steps below describe adding scrolling to the project#show action.
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.
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).
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.
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.
29 // a. In the "app/views/pipeline_instances/_show_recent.html.erb/" file
30 // add a div or tbody with data-infinite-scroller.
32 // b. Add the partial "_show_recent_rows.html.erb" that displays the
33 // page contents on scroll using the @objects
35 function maybe_load_more_content(event) {
37 var $container = $(event.data.container);
38 var src; // url for retrieving content
41 var serial = Date.now();
43 scrollHeight = scroller.scrollHeight || $('body')[0].scrollHeight;
44 if ($(scroller).scrollTop() + $(scroller).height()
48 if (!$container.attr('data-infinite-content-href0')) {
49 // Remember the first page source url, so we can refresh
51 $container.attr('data-infinite-content-href0',
52 $container.attr('data-infinite-content-href'));
54 src = $container.attr('data-infinite-content-href');
55 if (!src || !$container.is(':visible'))
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;
69 spinner = ('<tr class="spinner"><td colspan="' + colspan + '">' +
73 $container.find(".spinner").detach();
74 $container.append(spinner);
75 $container.data('data-infinite-serial', serial);
77 if (src == $container.attr('data-infinite-content-href0')) {
78 // If we're loading the first page, collect filters from
80 params = mergeInfiniteContentParams($container);
81 $.each(params, function(k,v) {
82 if (v instanceof Object) {
83 params[k] = JSON.stringify(v);
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
102 context: {container: $container, src: src, serial: serial}}).
103 fail(function(jqxhr, status, error) {
105 var $container = this.container;
106 if ($container.data('data-infinite-serial') != this.serial) {
107 // A newer request is already in progress.
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("; ");
115 message = "Request failed.";
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);
125 done(function(data, status, jqxhr) {
126 if ($container.data('data-infinite-serial') != this.serial) {
127 // A newer request is already in progress.
130 $container.find(".spinner").detach();
131 $container.append(data.content);
132 $container.attr('data-infinite-content-href', data.next_page_href);
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');
144 function mergeInfiniteContentParams($container) {
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.
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
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] || []).
171 } else if (hvalue instanceof Object) {
172 $.extend(params[hkey], hvalue);
174 params[hkey] = hvalue;
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
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');
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'));
211 replaceWith('<div class="spinner spinner-32px spinner-h-center" />');
212 ping_all_scrollers();
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');
222 attr('data-infinite-content-href', first_page_href);
223 ping_all_scrollers();
225 on('ready ajax:complete', function() {
226 $('[data-infinite-scroller]').each(function() {
227 if ($(this).hasClass('infinite-scroller-ready'))
229 $(this).addClass('infinite-scroller-ready');
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 );
242 // otherwise just reset the sort icons
243 $(this).trigger('sort-icons');
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
252 var $scroller = $($(this).attr('data-infinite-scroller'));
253 if (!$scroller.hasClass('smart-scroll') &&
254 'scroll' != $scroller.css('overflow-y'))
255 $scroller = $(window);
257 addClass('infinite-scroller').
258 on('scroll resize', { container: this }, maybe_load_more_content).
262 on('shown.bs.tab', 'a[data-toggle="tab"]', function(event) {
263 $(event.target.getAttribute('href') + ' [data-infinite-scroller]').
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' ) {
275 var $container = $(this).closest('table').find('[data-infinite-content-params-attr]');
277 var order = setColumnSort( $container, $(this), direction );
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 ) {
286 state.order[tabId] = order;
287 history.replaceState( state, null, null );
290 $container.trigger('refresh-content');
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 + '"/>');
300 $(this).append('<i class="fa fa-sort"/>');