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