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);
133 ping_all_scrollers();
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');
145 function mergeInfiniteContentParams($container) {
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.
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
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
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] || []).
173 } else if (hvalue instanceof Object) {
174 $.extend(params[hkey], hvalue);
176 params[hkey] = hvalue;
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
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');
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'));
213 replaceWith('<div class="spinner spinner-32px spinner-h-center" />');
214 ping_all_scrollers();
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');
224 attr('data-infinite-content-href', first_page_href);
225 ping_all_scrollers();
227 on('ready ajax:complete', function() {
228 $('[data-infinite-scroller]').each(function() {
229 if ($(this).hasClass('infinite-scroller-ready'))
231 $(this).addClass('infinite-scroller-ready');
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 );
244 // otherwise just reset the sort icons
245 $(this).trigger('sort-icons');
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
254 var $scroller = $($(this).attr('data-infinite-scroller'));
255 if (!$scroller.hasClass('smart-scroll') &&
256 'scroll' != $scroller.css('overflow-y'))
257 $scroller = $(window);
259 addClass('infinite-scroller').
260 on('scroll resize', { container: this }, maybe_load_more_content).
264 on('shown.bs.tab', 'a[data-toggle="tab"]', function(event) {
265 $(event.target.getAttribute('href') + ' [data-infinite-scroller]').
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' ) {
277 var $container = $(this).closest('table').find('[data-infinite-content-params-attr]');
279 var order = setColumnSort( $container, $(this), direction );
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 ) {
288 state.order[tabId] = order;
289 history.replaceState( state, null, null );
292 $container.trigger('refresh-content');
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 + '"/>');
302 $(this).append('<i class="fa fa-sort"/>');