Merge branch '8784-dir-listings'
[arvados.git] / apps / workbench / app / assets / javascripts / filterable.js
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 // filterable.js shows/hides content when the user operates
6 // search/select widgets. For "infinite scroll" content, it passes the
7 // filters to the server and retrieves new content. For other content,
8 // it filters the existing DOM elements using jQuery show/hide.
9 //
10 // Usage:
11 //
12 // 1. Add the "filterable" class to each filterable content item.
13 // Typically, each item is a 'tr' or a 'div class="row"'.
14 //
15 // <div id="results">
16 //   <div class="filterable row">First row</div>
17 //   <div class="filterable row">Second row</div>
18 // </div>
19 //
20 // 2. Add the "filterable-control" class to each search/select widget.
21 // Also add a data-filterable-target attribute with a jQuery selector
22 // for an ancestor of the filterable items, i.e., the container in
23 // which this widget should apply filtering.
24 //
25 // <input class="filterable-control" data-filterable-target="#results"
26 //        type="text" />
27 //
28 // Supported widgets:
29 //
30 // <input type="text" ... />
31 //
32 // The input value is used as a regular expression. Rows with content
33 // matching the regular expression are shown.
34 //
35 // <select ... data-filterable-attribute="data-example-attr">
36 //  <option value="foo">Foo</option>
37 //  <option value="">Show all</option>
38 // </select>
39 //
40 // When the user selects the "Foo" option, rows with
41 // data-example-attr="foo" are shown, and all others are hidden. When
42 // the user selects the "Show all" option, all rows are shown.
43 //
44 // Notes:
45 //
46 // When multiple filterable-control widgets operate on the same
47 // data-filterable-target, items must pass _all_ filters in order to
48 // be shown.
49 //
50 // If one data-filterable-target is the parent of another
51 // data-filterable-target, results are undefined. Don't do this.
52 //
53 // Combining "select" filterable-controls with infinite-scroll is not
54 // yet supported.
55
56 function updateFilterableQueryNow($target) {
57     var newquery = $target.data('filterable-query-new');
58     var params = $target.data('infinite-content-params-filterable') || {};
59     if (newquery == null || newquery == '') {
60       params.filters = [];
61     } else {
62       params.filters = [['any', '@@', newquery.trim().concat(':*')]];
63     }
64     $(".modal-dialog-preview-pane").html("");
65     $target.data('infinite-content-params-filterable', params);
66     $target.data('filterable-query', newquery);
67 }
68
69 $(document).
70     on('ready ajax:success', function() {
71         // Copy any initial input values into
72         // data-filterable-query[-new].
73         $('input[type=text].filterable-control').each(function() {
74             var $this = $(this);
75             var $target = $($this.attr('data-filterable-target'));
76             if ($target.data('filterable-query-new') === undefined) {
77                 $target.data('filterable-query', $this.val());
78                 $target.data('filterable-query-new', $this.val());
79                 updateFilterableQueryNow($target);
80             }
81         });
82         $('[data-infinite-scroller]').on('refresh-content', '[data-filterable-query]', function(e) {
83             // If some other event causes a refresh-content event while there
84             // is a new query waiting to cooloff, we should use the new query
85             // right away -- otherwise we'd launch an extra ajax request that
86             // would have to be reloaded as soon as the cooloff period ends.
87             if (this != e.target)
88                 return;
89             if ($(this).data('filterable-query') == $(this).data('filterable-query-new'))
90                 return;
91             updateFilterableQueryNow($(this));
92         });
93     }).
94     on('paste keyup input', 'input[type=text].filterable-control', function(e) {
95         var regexp;
96         if (this != e.target) return;
97         var $target = $($(this).attr('data-filterable-target'));
98         var currentquery = $target.data('filterable-query');
99         if (currentquery === undefined) currentquery = '';
100         if ($target.is('[data-infinite-scroller]')) {
101             // We already know how to load content dynamically, so we
102             // can do all filtering on the server side.
103
104             if ($target.data('infinite-cooloff-timer') > 0) {
105                 // Clear a stale refresh-after-delay timer.
106                 clearTimeout($target.data('infinite-cooloff-timer'));
107             }
108             // Stash the new query string in the filterable container.
109             $target.data('filterable-query-new', $(this).val());
110             if (currentquery == $(this).val()) {
111                 // Don't mess with existing results or queries in
112                 // progress.
113                 return;
114             }
115             $target.data('infinite-cooloff-timer', setTimeout(function() {
116                 // If the user doesn't do any query-changing actions
117                 // in the next 1/4 second (like type or erase
118                 // characters in the search box), hide the stale
119                 // content and ask the server for new results.
120                 updateFilterableQueryNow($target);
121                 $target.trigger('refresh-content');
122             }, 250));
123         } else {
124             // Target does not have infinite-scroll capability. Just
125             // filter the rows in the browser using a RegExp.
126             regexp = undefined;
127             try {
128                 regexp = new RegExp($(this).val(), 'i');
129             } catch(e) {
130                 if (e instanceof SyntaxError) {
131                     // Invalid/partial regexp. See 'has-error' below.
132                 } else {
133                     throw e;
134                 }
135             }
136             $target.
137                 toggleClass('has-error', regexp === undefined).
138                 addClass('filterable-container').
139                 data('q', regexp).
140                 trigger('refresh');
141         }
142     }).on('refresh', '.filterable-container', function() {
143         var $container = $(this);
144         var q = $(this).data('q');
145         var filters = $(this).data('filters');
146         $('.filterable', this).hide().filter(function() {
147             var $row = $(this);
148             var pass = true;
149             if (q && !$row.text().match(q))
150                 return false;
151             if (filters) {
152                 $.each(filters, function(filterby, val) {
153                     if (!val) return;
154                     if (!pass) return;
155                     pass = false;
156                     $.each(val.split(" "), function(i, e) {
157                         if ($row.attr(filterby) == e)
158                             pass = true;
159                     });
160                 });
161             }
162             return pass;
163         }).show();
164
165         // Show/hide each section heading depending on whether any
166         // content rows are visible in that section.
167         $('.row[data-section-heading]', this).each(function(){
168             $(this).toggle($('.row.filterable[data-section-name="' +
169                              $(this).attr('data-section-name') +
170                              '"]:visible').length > 0);
171         });
172
173         // Load more content if the last result is showing.
174         $('.infinite-scroller').add(window).trigger('scroll');
175     }).on('change', 'select.filterable-control', function() {
176         var val = $(this).val();
177         var filterby = $(this).attr('data-filterable-attribute');
178         var $target = $($(this).attr('data-filterable-target')).
179             addClass('filterable-container');
180         var filters = $target.data('filters') || {};
181         filters[filterby] = val;
182         $target.
183             data('filters', filters).
184             trigger('refresh');
185     }).on('ajax:complete', function() {
186         $('.filterable-control').trigger('input');
187     });