Merge branch 'master' into 2756-eventbus-in-workbench
[arvados.git] / apps / workbench / app / assets / javascripts / collections.js
1 jQuery(function($){
2     $(document).on('click', '.toggle-persist button', function() {
3         var toggle_group = $(this).parents('[data-remote-href]').first();
4         var want_persist = !toggle_group.find('button').hasClass('active');
5         var want_state = want_persist ? 'persistent' : 'cache';
6         toggle_group.find('button').
7             toggleClass('active', want_persist).
8             html(want_persist ? 'Persistent' : 'Cache');
9         $.ajax(toggle_group.attr('data-remote-href'),
10                {dataType: 'json',
11                 type: 'POST',
12                 data: {
13                     value: want_state
14                 },
15                 context: {
16                     toggle_group: toggle_group,
17                     want_state: want_state,
18                     button: this
19                 }
20                }).
21             done(function(data, status, jqxhr) {
22                 var context = this;
23                 $(document).trigger('ajax:complete');
24                 // Remove "danger" status in case a previous action failed
25                 $('.btn-danger', context.toggle_group).
26                     addClass('btn-info').
27                     removeClass('btn-danger');
28                 // Update last-saved-state
29                 context.toggle_group.
30                     attr('data-persistent-state', context.want_state);
31             }).
32             fail(function(jqxhr, status, error) {
33                 var context = this;
34                 var saved_state;
35                 $(document).trigger('ajax:complete');
36                 // Add a visual indication that something failed
37                 $(context.button).
38                     addClass('btn-danger').
39                     removeClass('btn-info');
40                 // Change to the last-saved-state
41                 saved_state = context.toggle_group.attr('data-persistent-state');
42                 $(context.button).
43                     toggleClass('active', saved_state == 'persistent').
44                     html(saved_state == 'persistent' ? 'Persistent' : 'Cache');
45
46                 if (jqxhr.readyState == 0 || jqxhr.status == 0) {
47                     // Request cancelled due to page reload.
48                     // Displaying an alert would be rather annoying.
49                 } else if (jqxhr.responseJSON && jqxhr.responseJSON.errors) {
50                     window.alert("Request failed: " +
51                                  jqxhr.responseJSON.errors.join("; "));
52                 } else {
53                     window.alert("Request failed.");
54                 }
55             });
56         $(document).trigger('ajax:send');
57     });
58 });