blacklight-frontend 7.25.0 → 8.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +12 -4
  2. package/app/assets/javascripts/blacklight/blacklight.esm.js +384 -0
  3. package/app/assets/javascripts/blacklight/blacklight.esm.js.map +1 -0
  4. package/app/assets/javascripts/blacklight/blacklight.js +351 -496
  5. package/app/assets/javascripts/blacklight/blacklight.js.map +1 -0
  6. package/app/assets/stylesheets/blacklight/_autocomplete.scss +25 -0
  7. package/app/assets/stylesheets/blacklight/_blacklight_base.scss +1 -1
  8. package/app/assets/stylesheets/blacklight/_bookmark.scss +16 -0
  9. package/app/assets/stylesheets/blacklight/_bootstrap_overrides.scss +8 -0
  10. package/app/assets/stylesheets/blacklight/_controls.scss +5 -12
  11. package/app/assets/stylesheets/blacklight/_facets.scss +100 -33
  12. package/app/assets/stylesheets/blacklight/_group.scss +2 -2
  13. package/app/assets/stylesheets/blacklight/_header.scss +3 -21
  14. package/app/assets/stylesheets/blacklight/_icons.scss +0 -14
  15. package/app/assets/stylesheets/blacklight/_mixins.scss +20 -0
  16. package/app/assets/stylesheets/blacklight/_modal.scss +8 -2
  17. package/app/assets/stylesheets/blacklight/_search_form.scss +30 -3
  18. package/app/assets/stylesheets/blacklight/_search_history.scss +10 -1
  19. package/app/assets/stylesheets/blacklight/_search_results.scss +6 -2
  20. package/app/assets/stylesheets/blacklight/blacklight_defaults.scss +6 -1
  21. package/package.json +9 -13
  22. package/app/assets/images/blacklight/list.svg +0 -1
  23. package/app/assets/images/blacklight/search.svg +0 -1
  24. package/app/assets/stylesheets/blacklight/_twitter_typeahead.scss +0 -30
  25. package/app/javascript/blacklight/autocomplete.js +0 -36
  26. package/app/javascript/blacklight/bookmark_toggle.js +0 -25
  27. package/app/javascript/blacklight/button_focus.js +0 -10
  28. package/app/javascript/blacklight/checkbox_submit.js +0 -134
  29. package/app/javascript/blacklight/core.js +0 -54
  30. package/app/javascript/blacklight/facet_load.js +0 -22
  31. package/app/javascript/blacklight/modal.js +0 -226
  32. package/app/javascript/blacklight/search_context.js +0 -69
@@ -1,537 +1,392 @@
1
- "use strict";
2
-
3
- var Blacklight = function () {
4
- var buffer = new Array();
5
- return {
6
- onLoad: function onLoad(func) {
7
- buffer.push(func);
8
- },
9
- activate: function activate() {
10
- for (var i = 0; i < buffer.length; i++) {
11
- buffer[i].call();
12
- }
13
- },
14
- listeners: function listeners() {
15
- var listeners = [];
16
-
17
- if (typeof Turbo !== 'undefined') {
18
- listeners.push('turbo:load');
19
- } else if (typeof Turbolinks !== 'undefined' && Turbolinks.supported) {
20
- // Turbolinks 5
21
- if (Turbolinks.BrowserAdapter) {
22
- listeners.push('turbolinks:load');
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Blacklight = factory());
5
+ })(this, (function () { 'use strict';
6
+
7
+ const Blacklight = function() {
8
+ const buffer = new Array;
9
+ return {
10
+ onLoad: function(func) {
11
+ buffer.push(func);
12
+ },
13
+
14
+ activate: function() {
15
+ for(let i = 0; i < buffer.length; i++) {
16
+ buffer[i].call();
17
+ }
18
+ },
19
+
20
+ listeners: function () {
21
+ const listeners = [];
22
+ if (typeof Turbo !== 'undefined') {
23
+ listeners.push('turbo:load', 'turbo:frame-load');
24
+ } else if (typeof Turbolinks !== 'undefined' && Turbolinks.supported) {
25
+ // Turbolinks 5
26
+ if (Turbolinks.BrowserAdapter) {
27
+ listeners.push('turbolinks:load');
28
+ } else {
29
+ // Turbolinks < 5
30
+ listeners.push('page:load', 'DOMContentLoaded');
31
+ }
23
32
  } else {
24
- // Turbolinks < 5
25
- listeners.push('page:load', 'DOMContentLoaded');
33
+ listeners.push('DOMContentLoaded');
26
34
  }
27
- } else {
28
- listeners.push('DOMContentLoaded');
29
- }
30
35
 
31
- return listeners;
32
- }
33
- };
34
- }(); // turbolinks triggers page:load events on page transition
35
- // If app isn't using turbolinks, this event will never be triggered, no prob.
36
-
37
-
38
- Blacklight.listeners().forEach(function (listener) {
39
- document.addEventListener(listener, function () {
40
- Blacklight.activate();
41
- });
42
- });
43
- Blacklight.onLoad(function () {
44
- var elem = document.querySelector('.no-js'); // The "no-js" class may already have been removed because this function is
45
- // run on every turbo:load event, in that case, it won't find an element.
46
-
47
- if (!elem) return;
48
- elem.classList.remove('no-js');
49
- elem.classList.add('js');
50
- });
51
- window.Blacklight = Blacklight;
52
- /*global Bloodhound */
53
-
54
- Blacklight.onLoad(function () {
55
- 'use strict';
56
-
57
- $('[data-autocomplete-enabled="true"]').each(function () {
58
- var $el = $(this);
59
-
60
- if ($el.hasClass('tt-hint')) {
61
- return;
62
- }
63
-
64
- var suggestUrl = $el.data().autocompletePath;
65
- var terms = new Bloodhound({
66
- datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
67
- queryTokenizer: Bloodhound.tokenizers.whitespace,
68
- remote: {
69
- url: suggestUrl + '?q=%QUERY',
70
- wildcard: '%QUERY'
36
+ return listeners;
71
37
  }
72
- });
73
- terms.initialize();
74
- $el.typeahead({
75
- hint: true,
76
- highlight: true,
77
- minLength: 2
78
- }, {
79
- name: 'terms',
80
- displayKey: 'term',
81
- source: terms.ttAdapter()
38
+ };
39
+ }();
40
+
41
+ // turbolinks triggers page:load events on page transition
42
+ // If app isn't using turbolinks, this event will never be triggered, no prob.
43
+ Blacklight.listeners().forEach(function(listener) {
44
+ document.addEventListener(listener, function() {
45
+ Blacklight.activate();
82
46
  });
83
47
  });
84
- });
85
-
86
- (function ($) {
87
- //change form submit toggle to checkbox
88
- Blacklight.doBookmarkToggleBehavior = function () {
89
- if (typeof Blacklight.do_bookmark_toggle_behavior == 'function') {
90
- console.warn("do_bookmark_toggle_behavior is deprecated. Use doBookmarkToggleBehavior instead.");
91
- return Blacklight.do_bookmark_toggle_behavior();
92
- }
93
-
94
- $(Blacklight.doBookmarkToggleBehavior.selector).blCheckboxSubmit({
95
- // cssClass is added to elements added, plus used for id base
96
- cssClass: 'toggle-bookmark',
97
- success: function success(checked, response) {
98
- if (response.bookmarks) {
99
- $('[data-role=bookmark-counter]').text(response.bookmarks.count);
100
- }
101
- }
102
- });
103
- };
104
48
 
105
- Blacklight.doBookmarkToggleBehavior.selector = 'form.bookmark-toggle';
106
49
  Blacklight.onLoad(function () {
107
- Blacklight.doBookmarkToggleBehavior();
108
- });
109
- })(jQuery);
110
-
111
- Blacklight.onLoad(function () {
112
- // Button clicks should change focus. As of 10/3/19, Firefox for Mac and
113
- // Safari both do not set focus to a button on button click.
114
- // See https://zellwk.com/blog/inconsistent-button-behavior/ for background information
115
- document.querySelectorAll('button.collapse-toggle').forEach(function (button) {
116
- button.addEventListener('click', function () {
117
- event.target.focus();
118
- });
119
- });
120
- });
121
- /* A JQuery plugin (should this be implemented as a widget instead? not sure)
122
- that will convert a "toggle" form, with single submit button to add/remove
123
- something, like used for Bookmarks, into an AJAXy checkbox instead.
124
-
125
- Apply to a form. Does require certain assumption about the form:
126
- 1) The same form 'action' href must be used for both ADD and REMOVE
127
- actions, with the different being the hidden input name="_method"
128
- being set to "put" or "delete" -- that's the Rails method to pretend
129
- to be doing a certain HTTP verb. So same URL, PUT to add, DELETE
130
- to remove. This plugin assumes that.
131
-
132
- Plus, the form this is applied to should provide a data-doc-id
133
- attribute (HTML5-style doc-*) that contains the id/primary key
134
- of the object in question -- used by plugin for a unique value for
135
- DOM id's.
136
-
137
- Uses HTML for a checkbox compatible with Bootstrap 3.
138
-
139
- Pass in options for your class name and labels:
140
- $("form.something").blCheckboxSubmit({
141
- //cssClass is added to elements added, plus used for id base
142
- cssClass: "toggle_my_kinda_form",
143
- error: function() {
144
- #optional callback
145
- },
146
- success: function(after_success_check_state) {
147
- #optional callback
148
- }
149
- });
150
- */
151
-
152
- (function ($) {
153
- $.fn.blCheckboxSubmit = function (argOpts) {
154
- this.each(function () {
155
- var options = $.extend({}, $.fn.blCheckboxSubmit.defaults, argOpts);
156
- var form = $(this);
157
- form.children().hide(); //We're going to use the existing form to actually send our add/removes
158
- //This works conveneintly because the exact same action href is used
159
- //for both bookmarks/$doc_id. But let's take out the irrelevant parts
160
- //of the form to avoid any future confusion.
161
-
162
- form.find('input[type=submit]').remove(); //View needs to set data-doc-id so we know a unique value
163
- //for making DOM id
164
-
165
- var uniqueId = form.attr('data-doc-id') || Math.random(); // if form is currently using method delete to change state,
166
- // then checkbox is currently checked
167
-
168
- var checked = form.find('input[name=_method][value=delete]').length != 0;
169
- var checkbox = $('<input type="checkbox">').addClass(options.cssClass).attr('id', options.cssClass + '_' + uniqueId);
170
- var label = $('<label>').addClass(options.cssClass).attr('for', options.cssClass + '_' + uniqueId).attr('title', form.attr('title') || '');
171
- var span = $('<span>');
172
- label.append(checkbox);
173
- label.append(' ');
174
- label.append(span);
175
- var checkboxDiv = $('<div class="checkbox" />').addClass(options.cssClass).append(label);
176
-
177
- function updateStateFor(state) {
178
- checkbox.prop('checked', state);
179
- label.toggleClass('checked', state);
180
-
181
- if (state) {
182
- //Set the Rails hidden field that fakes an HTTP verb
183
- //properly for current state action.
184
- form.find('input[name=_method]').val('delete');
185
- span.html(form.attr('data-present'));
186
- } else {
187
- form.find('input[name=_method]').val('put');
188
- span.html(form.attr('data-absent'));
189
- }
190
- }
191
-
192
- form.append(checkboxDiv);
193
- updateStateFor(checked);
194
- checkbox.click(function () {
195
- span.html(form.attr('data-inprogress'));
196
- label.attr('disabled', 'disabled');
197
- checkbox.attr('disabled', 'disabled');
198
- $.ajax({
199
- url: form.attr('action'),
200
- dataType: 'json',
201
- type: form.attr('method').toUpperCase(),
202
- data: form.serialize(),
203
- error: function error() {
204
- label.removeAttr('disabled');
205
- checkbox.removeAttr('disabled');
206
- options.error.call();
207
- },
208
- success: function success(data, status, xhr) {
209
- //if app isn't running at all, xhr annoyingly
210
- //reports success with status 0.
211
- if (xhr.status != 0) {
212
- checked = !checked;
213
- updateStateFor(checked);
214
- label.removeAttr('disabled');
215
- checkbox.removeAttr('disabled');
216
- options.success.call(form, checked, xhr.responseJSON);
217
- } else {
218
- label.removeAttr('disabled');
219
- checkbox.removeAttr('disabled');
220
- options.error.call();
221
- }
222
- }
223
- });
224
- return false;
225
- }); //checkbox.click
226
- }); //this.each
227
-
228
- return this;
229
- };
50
+ const elem = document.querySelector('.no-js');
230
51
 
231
- $.fn.blCheckboxSubmit.defaults = {
232
- //cssClass is added to elements added, plus used for id base
233
- cssClass: 'blCheckboxSubmit',
234
- error: function error() {
235
- alert("Error");
236
- },
237
- success: function success() {} //callback
238
-
239
- };
240
- })(jQuery);
241
- /*global Blacklight */
52
+ // The "no-js" class may already have been removed because this function is
53
+ // run on every turbo:load event, in that case, it won't find an element.
54
+ if (!elem) return;
242
55
 
56
+ elem.classList.remove('no-js');
57
+ elem.classList.add('js');
58
+ });
243
59
 
244
- 'use strict';
245
-
246
- Blacklight.doResizeFacetLabelsAndCounts = function () {
247
- // adjust width of facet columns to fit their contents
248
- function longer(a, b) {
249
- return b.textContent.length - a.textContent.length;
250
- }
251
-
252
- document.querySelectorAll('.facet-values, .pivot-facet').forEach(function (elem) {
253
- var nodes = elem.querySelectorAll('.facet-count'); // TODO: when we drop ie11 support, this can become the spread operator:
60
+ /* Converts a "toggle" form, with single submit button to add/remove
61
+ something, like used for Bookmarks, into an AJAXy checkbox instead.
62
+ Apply to a form. Does require certain assumption about the form:
63
+ 1) The same form 'action' href must be used for both ADD and REMOVE
64
+ actions, with the different being the hidden input name="_method"
65
+ being set to "put" or "delete" -- that's the Rails method to pretend
66
+ to be doing a certain HTTP verb. So same URL, PUT to add, DELETE
67
+ to remove. This plugin assumes that.
68
+ Plus, the form this is applied to should provide a data-doc-id
69
+ attribute (HTML5-style doc-*) that contains the id/primary key
70
+ of the object in question -- used by plugin for a unique value for
71
+ DOM id's.
72
+ Uses HTML for a checkbox compatible with Bootstrap 4.
73
+ new CheckboxSubmit(document.querySelector('form.something')).render()
74
+ */
75
+ class CheckboxSubmit {
76
+ constructor(form) {
77
+ this.form = form;
78
+ }
254
79
 
255
- var longest = Array.from(nodes).sort(longer)[0];
80
+ async clicked(evt) {
81
+ this.spanTarget.innerHTML = this.form.getAttribute('data-inprogress');
82
+ this.labelTarget.setAttribute('disabled', 'disabled');
83
+ this.checkboxTarget.setAttribute('disabled', 'disabled');
84
+ const response = await fetch(this.formTarget.getAttribute('action'), {
85
+ body: new FormData(this.formTarget),
86
+ method: this.formTarget.getAttribute('method').toUpperCase(),
87
+ headers: {
88
+ 'Accept': 'application/json',
89
+ 'X-Requested-With': 'XMLHttpRequest',
90
+ 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]')?.content
91
+ }
92
+ });
93
+ this.labelTarget.removeAttribute('disabled');
94
+ this.checkboxTarget.removeAttribute('disabled');
95
+ if (response.ok) {
96
+ const json = await response.json();
97
+ this.updateStateFor(!this.checked);
98
+ document.querySelector('[data-role=bookmark-counter]').innerHTML = json.bookmarks.count;
99
+ } else {
100
+ alert('Error');
101
+ }
102
+ }
256
103
 
257
- if (longest && longest.textContent) {
258
- var width = longest.textContent.length + 1 + 'ch';
259
- elem.querySelector('.facet-count').style.width = width;
104
+ get checked() {
105
+ return (this.form.querySelectorAll('input[name=_method][value=delete]').length != 0)
260
106
  }
261
- });
262
- };
263
-
264
- Blacklight.onLoad(function () {
265
- Blacklight.doResizeFacetLabelsAndCounts();
266
- });
267
- /*
268
- The blacklight modal plugin can display some interactions inside a Bootstrap
269
- modal window, including some multi-page interactions.
270
-
271
- It supports unobtrusive Javascript, where a link or form that would have caused
272
- a new page load is changed to display it's results inside a modal dialog,
273
- by this plugin. The plugin assumes there is a Bootstrap modal div
274
- on the page with id #blacklight-modal to use as the modal -- the standard Blacklight
275
- layout provides this.
276
-
277
- To make a link or form have their results display inside a modal, add
278
- `data-blacklight-modal="trigger"` to the link or form. (Note, form itself not submit input)
279
- With Rails link_to helper, you'd do that like:
280
-
281
- link_to something, link, data: { blacklight_modal: "trigger" }
282
-
283
- The results of the link href or form submit will be displayed inside
284
- a modal -- they should include the proper HTML markup for a bootstrap modal's
285
- contents. Also, you ordinarily won't want the Rails template with wrapping
286
- navigational elements to be used. The Rails controller could suppress
287
- the layout when a JS AJAX request is detected, OR the response
288
- can include a `<div data-blacklight-modal="container">` -- only the contents
289
- of the container will be placed inside the modal, the rest of the
290
- page will be ignored.
291
-
292
- If you'd like to have a link or button that closes the modal,
293
- you can just add a `data-dismiss="modal"` to the link,
294
- standard Bootstrap convention. But you can also have
295
- an href on this link for non-JS contexts, we'll make sure
296
- inside the modal it closes the modal and the link is NOT followed.
297
-
298
- Link or forms inside the modal will ordinarily cause page loads
299
- when they are triggered. However, if you'd like their results
300
- to stay within the modal, just add `data-blacklight-modal="preserve"`
301
- to the link or form.
302
-
303
- Here's an example of what might be returned, demonstrating most of the devices available:
304
-
305
- <div data-blacklight-modal="container">
306
- <div class="modal-header">
307
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
308
- <h3 class="modal-title">Request Placed</h3>
309
- </div>
310
107
 
311
- <div class="modal-body">
312
- <p>Some message</p>
313
- <%= link_to "This result will still be within modal", some_link, data: { blacklight_modal: "preserve" } %>
314
- </div>
108
+ get formTarget() {
109
+ return this.form
110
+ }
315
111
 
112
+ get labelTarget() {
113
+ return this.form.querySelector('[data-checkboxsubmit-target="label"]')
114
+ }
316
115
 
317
- <div class="modal-footer">
318
- <%= link_to "Close the modal", request_done_path, class: "submit button dialog-close", data: { dismiss: "modal" } %>
319
- </div>
320
- </div>
321
-
322
-
323
- One additional feature. If the content returned from the AJAX modal load
324
- has an element with `data-blacklight-modal=close`, that will trigger the modal
325
- to be closed. And if this element includes a node with class "flash_messages",
326
- the flash-messages node will be added to the main page inside #main-flahses.
327
-
328
- == Events
329
-
330
- We'll send out an event 'loaded.blacklight.blacklight-modal' with the #blacklight-modal
331
- dialog as the target, right after content is loaded into the modal but before
332
- it is shown (if not already a shown modal). In an event handler, you can
333
- inspect loaded content by looking inside $(this). If you call event.preventDefault(),
334
- we won't 'show' the dialog (although it may already have been shown, you may want to
335
- $(this).modal("hide") if you want to ensure hidden/closed.
336
-
337
- The data-blacklight-modal=close behavior is implemented with this event, see for example.
338
- */
339
- // We keep all our data in Blacklight.modal object.
340
- // Create lazily if someone else created first.
341
-
342
- if (Blacklight.modal === undefined) {
343
- Blacklight.modal = {};
344
- } // a Bootstrap modal div that should be already on the page hidden
345
-
346
-
347
- Blacklight.modal.modalSelector = '#blacklight-modal'; // Trigger selectors identify forms or hyperlinks that should open
348
- // inside a modal dialog.
349
-
350
- Blacklight.modal.triggerLinkSelector = 'a[data-blacklight-modal~=trigger]';
351
- Blacklight.modal.triggerFormSelector = 'form[data-blacklight-modal~=trigger]'; // preserve selectors identify forms or hyperlinks that, if activated already
352
- // inside a modal dialog, should have destinations remain inside the modal -- but
353
- // won't trigger a modal if not already in one.
354
- //
355
- // No need to repeat selectors from trigger selectors, those will already
356
- // be preserved. MUST be manually prefixed with the modal selector,
357
- // so they only apply to things inside a modal.
358
-
359
- Blacklight.modal.preserveLinkSelector = Blacklight.modal.modalSelector + ' a[data-blacklight-modal~=preserve]';
360
- Blacklight.modal.containerSelector = '[data-blacklight-modal~=container]';
361
- Blacklight.modal.modalCloseSelector = '[data-blacklight-modal~=close]'; // Called on fatal failure of ajax load, function returns content
362
- // to show to user in modal. Right now called only for extreme
363
- // network errors.
364
-
365
- Blacklight.modal.onFailure = function (jqXHR, textStatus, errorThrown) {
366
- console.error('Server error:', this.url, jqXHR.status, errorThrown);
367
- var contents = '<div class="modal-header">' + '<div class="modal-title">There was a problem with your request.</div>' + '<button type="button" class="blacklight-modal-close btn-close close" data-dismiss="modal" aria-label="Close">' + ' <span aria-hidden="true">&times;</span>' + '</button></div>' + ' <div class="modal-body"><p>Expected a successful response from the server, but got an error</p>' + '<pre>' + this.type + ' ' + this.url + "\n" + jqXHR.status + ': ' + errorThrown + '</pre></div>';
368
- $(Blacklight.modal.modalSelector).find('.modal-content').html(contents);
369
- Blacklight.modal.show();
370
- };
371
-
372
- Blacklight.modal.receiveAjax = function (contents) {
373
- // does it have a data- selector for container?
374
- // important we don't execute script tags, we shouldn't.
375
- // code modelled off of JQuery ajax.load. https://github.com/jquery/jquery/blob/main/src/ajax/load.js?source=c#L62
376
- var container = $('<div>').append(jQuery.parseHTML(contents)).find(Blacklight.modal.containerSelector).first();
377
-
378
- if (container.length !== 0) {
379
- contents = container.html();
380
- }
116
+ get checkboxTarget() {
117
+ return this.form.querySelector('[data-checkboxsubmit-target="checkbox"]')
118
+ }
381
119
 
382
- $(Blacklight.modal.modalSelector).find('.modal-content').html(contents); // send custom event with the modal dialog div as the target
383
-
384
- var e = $.Event('loaded.blacklight.blacklight-modal');
385
- $(Blacklight.modal.modalSelector).trigger(e); // if they did preventDefault, don't show the dialog
386
-
387
- if (e.isDefaultPrevented()) return;
388
- Blacklight.modal.show();
389
- };
390
-
391
- Blacklight.modal.modalAjaxLinkClick = function (e) {
392
- e.preventDefault();
393
- $.ajax({
394
- url: $(this).attr('href')
395
- }).fail(Blacklight.modal.onFailure).done(Blacklight.modal.receiveAjax);
396
- };
397
-
398
- Blacklight.modal.modalAjaxFormSubmit = function (e) {
399
- e.preventDefault();
400
- $.ajax({
401
- url: $(this).attr('action'),
402
- data: $(this).serialize(),
403
- type: $(this).attr('method') // POST
404
-
405
- }).fail(Blacklight.modal.onFailure).done(Blacklight.modal.receiveAjax);
406
- };
407
-
408
- Blacklight.modal.setupModal = function () {
409
- // Event indicating blacklight is setting up a modal link,
410
- // you can catch it and call e.preventDefault() to abort
411
- // setup.
412
- var e = $.Event('setup.blacklight.blacklight-modal');
413
- $('body').trigger(e);
414
- if (e.isDefaultPrevented()) return; // Register both trigger and preserve selectors in ONE event handler, combining
415
- // into one selector with a comma, so if something matches BOTH selectors, it
416
- // still only gets the event handler called once.
417
-
418
- $('body').on('click', Blacklight.modal.triggerLinkSelector + ', ' + Blacklight.modal.preserveLinkSelector, Blacklight.modal.modalAjaxLinkClick);
419
- $('body').on('submit', Blacklight.modal.triggerFormSelector + ', ' + Blacklight.modal.preserveFormSelector, Blacklight.modal.modalAjaxFormSubmit); // Catch our own custom loaded event to implement data-blacklight-modal=closed
420
-
421
- $('body').on('loaded.blacklight.blacklight-modal', Blacklight.modal.checkCloseModal); // we support doing data-dismiss=modal on a <a> with a href for non-ajax
422
- // use, we need to suppress following the a's href that's there for
423
- // non-JS contexts.
424
-
425
- $('body').on('click', Blacklight.modal.modalSelector + ' a[data-dismiss~=modal]', function (e) {
426
- e.preventDefault();
427
- });
428
- }; // A function used as an event handler on loaded.blacklight.blacklight-modal
429
- // to catch contained data-blacklight-modal=closed directions
430
-
431
-
432
- Blacklight.modal.checkCloseModal = function (event) {
433
- if ($(event.target).find(Blacklight.modal.modalCloseSelector).length) {
434
- var modalFlashes = $(this).find('.flash_messages');
435
- Blacklight.modal.hide(event.target);
436
- event.preventDefault();
437
- var mainFlashes = $('#main-flashes');
438
- mainFlashes.append(modalFlashes);
439
- modalFlashes.fadeIn(500);
440
- }
441
- };
120
+ get spanTarget() {
121
+ return this.form.querySelector('[data-checkboxsubmit-target="span"]')
122
+ }
442
123
 
443
- Blacklight.modal.hide = function (el) {
444
- if (typeof bootstrap !== 'undefined' && typeof bootstrap.Modal !== 'undefined' && bootstrap.Modal.VERSION >= "5") {
445
- bootstrap.Modal.getOrCreateInstance(el || document.querySelector(Blacklight.modal.modalSelector)).hide();
446
- } else {
447
- $(el || Blacklight.modal.modalSelector).modal('hide');
448
- }
449
- };
124
+ updateStateFor(state) {
125
+ this.checkboxTarget.checked = state;
450
126
 
451
- Blacklight.modal.show = function (el) {
452
- if (typeof bootstrap !== 'undefined' && typeof bootstrap.Modal !== 'undefined' && bootstrap.Modal.VERSION >= "5") {
453
- bootstrap.Modal.getOrCreateInstance(el || document.querySelector(Blacklight.modal.modalSelector)).show();
454
- } else {
455
- $(el || Blacklight.modal.modalSelector).modal('show');
127
+ if (state) {
128
+ this.labelTarget.classList.add('checked');
129
+ //Set the Rails hidden field that fakes an HTTP verb
130
+ //properly for current state action.
131
+ this.formTarget.querySelector('input[name=_method]').value = 'delete';
132
+ this.spanTarget.innerHTML = this.form.getAttribute('data-present');
133
+ } else {
134
+ this.labelTarget.classList.remove('checked');
135
+ this.formTarget.querySelector('input[name=_method]').value = 'put';
136
+ this.spanTarget.innerHTML = this.form.getAttribute('data-absent');
137
+ }
138
+ }
456
139
  }
457
- };
458
140
 
459
- Blacklight.onLoad(function () {
460
- Blacklight.modal.setupModal();
461
- });
141
+ const BookmarkToggle = (() => {
142
+ // change form submit toggle to checkbox
143
+ Blacklight.doBookmarkToggleBehavior = function() {
144
+ document.addEventListener('click', (e) => {
145
+ if (e.target.matches('[data-checkboxsubmit-target="checkbox"]')) {
146
+ const form = e.target.closest('form');
147
+ if (form) new CheckboxSubmit(form).clicked(e);
148
+ }
149
+ });
150
+ };
151
+ Blacklight.doBookmarkToggleBehavior.selector = 'form.bookmark-toggle';
152
+
153
+ Blacklight.doBookmarkToggleBehavior();
154
+ })();
155
+
156
+ const ButtonFocus = (() => {
157
+ document.addEventListener('click', (e) => {
158
+ // Button clicks should change focus. As of 10/3/19, Firefox for Mac and
159
+ // Safari both do not set focus to a button on button click.
160
+ // See https://zellwk.com/blog/inconsistent-button-behavior/ for background information
161
+ if (e.target.matches('[data-toggle="collapse"]') || e.target.matches('[data-bs-toggle="collapse"]')) {
162
+ e.target.focus();
163
+ }
164
+ });
165
+ })();
166
+
167
+ /*
168
+ The blacklight modal plugin can display some interactions inside a Bootstrap
169
+ modal window, including some multi-page interactions.
170
+
171
+ It supports unobtrusive Javascript, where a link or form that would have caused
172
+ a new page load is changed to display it's results inside a modal dialog,
173
+ by this plugin. The plugin assumes there is a Bootstrap modal div
174
+ on the page with id #blacklight-modal to use as the modal -- the standard Blacklight
175
+ layout provides this.
176
+
177
+ To make a link or form have their results display inside a modal, add
178
+ `data-blacklight-modal="trigger"` to the link or form. (Note, form itself not submit input)
179
+ With Rails link_to helper, you'd do that like:
180
+
181
+ link_to something, link, data: { blacklight_modal: "trigger" }
182
+
183
+ The results of the link href or form submit will be displayed inside
184
+ a modal -- they should include the proper HTML markup for a bootstrap modal's
185
+ contents. Also, you ordinarily won't want the Rails template with wrapping
186
+ navigational elements to be used. The Rails controller could suppress
187
+ the layout when a JS AJAX request is detected, OR the response
188
+ can include a `<div data-blacklight-modal="container">` -- only the contents
189
+ of the container will be placed inside the modal, the rest of the
190
+ page will be ignored.
191
+
192
+ Link or forms inside the modal will ordinarily cause page loads
193
+ when they are triggered. However, if you'd like their results
194
+ to stay within the modal, just add `data-blacklight-modal="preserve"`
195
+ to the link or form.
196
+
197
+ Here's an example of what might be returned, demonstrating most of the devices available:
198
+
199
+ <div data-blacklight-modal="container">
200
+ <div class="modal-header">
201
+ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
202
+ <h3 class="modal-title">Request Placed</h3>
203
+ </div>
204
+
205
+ <div class="modal-body">
206
+ <p>Some message</p>
207
+ <%= link_to "This result will still be within modal", some_link, data: { blacklight_modal: "preserve" } %>
208
+ </div>
209
+
210
+
211
+ <div class="modal-footer">
212
+ <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
213
+ </div>
214
+ </div>
462
215
 
463
- Blacklight.doSearchContextBehavior = function () {
464
- if (typeof Blacklight.do_search_context_behavior == 'function') {
465
- console.warn("do_search_context_behavior is deprecated. Use doSearchContextBehavior instead.");
466
- return Blacklight.do_search_context_behavior();
467
- }
468
216
 
469
- var elements = document.querySelectorAll('a[data-context-href]'); // Equivalent to Array.from(), but supports ie11
217
+ One additional feature. If the content returned from the AJAX form submission
218
+ can be a turbo-stream that defines some HTML fragementsand where on the page to put them:
219
+ https://turbo.hotwired.dev/handbook/streams
220
+ */
470
221
 
471
- var nodes = Array.prototype.slice.call(elements);
472
- nodes.forEach(function (element) {
473
- element.addEventListener('click', function (e) {
474
- Blacklight.handleSearchContextMethod.call(e.currentTarget, e);
475
- });
476
- });
477
- };
222
+ const Modal = (() => {
223
+ // We keep all our data in Blacklight.modal object.
224
+ // Create lazily if someone else created first.
225
+ if (Blacklight.modal === undefined) {
226
+ Blacklight.modal = {};
227
+ }
478
228
 
479
- Blacklight.csrfToken = function () {
480
- var _document$querySelect;
229
+ const modal = Blacklight.modal;
230
+
231
+ // a Bootstrap modal div that should be already on the page hidden
232
+ modal.modalSelector = '#blacklight-modal';
233
+
234
+ // Trigger selectors identify forms or hyperlinks that should open
235
+ // inside a modal dialog.
236
+ modal.triggerLinkSelector = 'a[data-blacklight-modal~=trigger]';
237
+
238
+ // preserve selectors identify forms or hyperlinks that, if activated already
239
+ // inside a modal dialog, should have destinations remain inside the modal -- but
240
+ // won't trigger a modal if not already in one.
241
+ //
242
+ // No need to repeat selectors from trigger selectors, those will already
243
+ // be preserved. MUST be manually prefixed with the modal selector,
244
+ // so they only apply to things inside a modal.
245
+ modal.preserveLinkSelector = modal.modalSelector + ' a[data-blacklight-modal~=preserve]';
246
+
247
+ modal.containerSelector = '[data-blacklight-modal~=container]';
248
+
249
+ // Called on fatal failure of ajax load, function returns content
250
+ // to show to user in modal. Right now called only for extreme
251
+ // network errors.
252
+ modal.onFailure = function (jqXHR, textStatus, errorThrown) {
253
+ console.error('Server error:', this.url, jqXHR.status, errorThrown);
254
+
255
+ const contents = `<div class="modal-header">
256
+ <div class="modal-title">There was a problem with your request.</div>
257
+ <button type="button" class="blacklight-modal-close btn-close close" data-dismiss="modal" data-bs-dismiss="modal" aria-label="Close">
258
+ <span aria-hidden="true">&times;</span>
259
+ </button>
260
+ </div>
261
+ <div class="modal-body">
262
+ <p>Expected a successful response from the server, but got an error</p>
263
+ <pre>${this.type} ${this.url}\n${jqXHR.status}: ${errorThrown}</pre>
264
+ </div>`;
265
+
266
+ document.querySelector(`${modal.modalSelector} .modal-content`).innerHTML = contents;
267
+
268
+ modal.show();
269
+ };
270
+
271
+ // Add the passed in contents to the modal and display it.
272
+ modal.receiveAjax = function (contents) {
273
+ const domparser = new DOMParser();
274
+ const dom = domparser.parseFromString(contents, "text/html");
275
+ const elements = dom.querySelectorAll(`${modal.containerSelector} > *`);
276
+ document.querySelector(`${modal.modalSelector} .modal-content`).replaceChildren(...elements);
277
+
278
+ modal.show();
279
+ };
280
+
281
+
282
+ modal.modalAjaxLinkClick = function(e) {
283
+ e.preventDefault();
284
+ const href = e.target.getAttribute('href');
285
+ fetch(href)
286
+ .then(response => {
287
+ if (!response.ok) {
288
+ throw new TypeError("Request failed");
289
+ }
290
+ return response.text();
291
+ })
292
+ .then(data => modal.receiveAjax(data))
293
+ .catch(error => modal.onFailure(error));
294
+ };
295
+
296
+ modal.setupModal = function() {
297
+ // Register both trigger and preserve selectors in ONE event handler, combining
298
+ // into one selector with a comma, so if something matches BOTH selectors, it
299
+ // still only gets the event handler called once.
300
+ document.addEventListener('click', (e) => {
301
+ if (e.target.matches(`${modal.triggerLinkSelector}, ${modal.preserveLinkSelector}`))
302
+ modal.modalAjaxLinkClick(e);
303
+ else if (e.target.matches('[data-bl-dismiss="modal"]'))
304
+ modal.hide();
305
+ });
306
+ };
307
+
308
+ modal.hide = function (el) {
309
+ const dom = document.querySelector(Blacklight.modal.modalSelector);
310
+
311
+ if (!dom.open) return
312
+ dom.close();
313
+ };
314
+
315
+ modal.show = function(el) {
316
+ const dom = document.querySelector(Blacklight.modal.modalSelector);
317
+
318
+ if (dom.open) return
319
+ dom.showModal();
320
+ };
321
+
322
+ modal.setupModal();
323
+ })();
324
+
325
+ const SearchContext = (() => {
326
+ Blacklight.doSearchContextBehavior = function() {
327
+ document.addEventListener('click', (e) => {
328
+ if (e.target.matches('[data-context-href]')) {
329
+ Blacklight.handleSearchContextMethod.call(e.target, e);
330
+ }
331
+ });
332
+ };
481
333
 
482
- return (_document$querySelect = document.querySelector('meta[name=csrf-token]')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.content;
483
- };
334
+ Blacklight.csrfToken = () => document.querySelector('meta[name=csrf-token]')?.content;
335
+ Blacklight.csrfParam = () => document.querySelector('meta[name=csrf-param]')?.content;
484
336
 
485
- Blacklight.csrfParam = function () {
486
- var _document$querySelect2;
337
+ // this is the Rails.handleMethod with a couple adjustments, described inline:
338
+ // first, we're attaching this directly to the event handler, so we can check for meta-keys
339
+ Blacklight.handleSearchContextMethod = function(event) {
340
+ const link = this;
487
341
 
488
- return (_document$querySelect2 = document.querySelector('meta[name=csrf-param]')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.content;
489
- }; // this is the Rails.handleMethod with a couple adjustments, described inline:
490
- // first, we're attaching this directly to the event handler, so we can check for meta-keys
342
+ // instead of using the normal href, we need to use the context href instead
343
+ let href = link.getAttribute('data-context-href');
344
+ let target = link.getAttribute('target');
345
+ let csrfToken = Blacklight.csrfToken();
346
+ let csrfParam = Blacklight.csrfParam();
347
+ let form = document.createElement('form');
348
+ form.method = 'post';
349
+ form.action = href;
491
350
 
492
351
 
493
- Blacklight.handleSearchContextMethod = function (event) {
494
- if (typeof Blacklight.handle_search_context_method == 'function') {
495
- console.warn("handle_search_context_method is deprecated. Use handleSearchContextMethod instead.");
496
- return Blacklight.handle_search_context_method(event);
497
- }
352
+ let formContent = `<input name="_method" value="post" type="hidden" />
353
+ <input name="redirect" value="${link.getAttribute('href')}" type="hidden" />`;
498
354
 
499
- var link = this; // instead of using the normal href, we need to use the context href instead
355
+ // check for meta keys.. if set, we should open in a new tab
356
+ if(event.metaKey || event.ctrlKey) {
357
+ target = '_blank';
358
+ }
500
359
 
501
- var href = link.getAttribute('data-context-href');
502
- var target = link.getAttribute('target');
503
- var csrfToken = Blacklight.csrfToken();
504
- var csrfParam = Blacklight.csrfParam();
505
- var form = document.createElement('form');
506
- form.method = 'post';
507
- form.action = href;
508
- var formContent = "<input name=\"_method\" value=\"post\" type=\"hidden\" />\n <input name=\"redirect\" value=\"".concat(link.getAttribute('href'), "\" type=\"hidden\" />"); // check for meta keys.. if set, we should open in a new tab
360
+ if (csrfParam !== undefined && csrfToken !== undefined) {
361
+ formContent += `<input name="${csrfParam}" value="${csrfToken}" type="hidden" />`;
362
+ }
509
363
 
510
- if (event.metaKey || event.ctrlKey) {
511
- target = '_blank';
512
- }
364
+ // Must trigger submit by click on a button, else "submit" event handler won't work!
365
+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
366
+ formContent += '<input type="submit" />';
513
367
 
514
- if (csrfParam !== undefined && csrfToken !== undefined) {
515
- formContent += "<input name=\"".concat(csrfParam, "\" value=\"").concat(csrfToken, "\" type=\"hidden\" />");
516
- } // Must trigger submit by click on a button, else "submit" event handler won't work!
517
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
368
+ if (target) { form.setAttribute('target', target); }
518
369
 
370
+ form.style.display = 'none';
371
+ form.innerHTML = formContent;
372
+ document.body.appendChild(form);
373
+ form.querySelector('[type="submit"]').click();
519
374
 
520
- formContent += '<input type="submit" />';
375
+ event.preventDefault();
376
+ };
521
377
 
522
- if (target) {
523
- form.setAttribute('target', target);
524
- }
378
+ Blacklight.doSearchContextBehavior();
379
+ })();
525
380
 
526
- form.style.display = 'none';
527
- form.innerHTML = formContent;
528
- document.body.appendChild(form);
529
- form.querySelector('[type="submit"]').click();
530
- event.preventDefault();
531
- event.stopPropagation();
532
- };
381
+ const index = {
382
+ BookmarkToggle,
383
+ ButtonFocus,
384
+ Modal,
385
+ SearchContext,
386
+ onLoad: Blacklight.onLoad
387
+ };
533
388
 
534
- Blacklight.onLoad(function () {
535
- Blacklight.doSearchContextBehavior();
536
- });
389
+ return index;
537
390
 
391
+ }));
392
+ //# sourceMappingURL=blacklight.js.map