blacklight-frontend 8.0.0-pre.3 → 8.0.0

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.
@@ -4,59 +4,6 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Blacklight = factory());
5
5
  })(this, (function () { 'use strict';
6
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');
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
- }
32
- } else {
33
- listeners.push('DOMContentLoaded');
34
- }
35
-
36
- return listeners;
37
- }
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();
46
- });
47
- });
48
-
49
- Blacklight.onLoad(function () {
50
- const elem = document.querySelector('.no-js');
51
-
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;
55
-
56
- elem.classList.remove('no-js');
57
- elem.classList.add('js');
58
- });
59
-
60
7
  /* Converts a "toggle" form, with single submit button to add/remove
61
8
  something, like used for Bookmarks, into an AJAXy checkbox instead.
62
9
  Apply to a form. Does require certain assumption about the form:
@@ -75,134 +22,88 @@
75
22
  class CheckboxSubmit {
76
23
  constructor(form) {
77
24
  this.form = form;
78
- this.cssClass = 'toggle-bookmark';
79
-
80
- //View needs to set data-doc-id so we know a unique value
81
- //for making DOM id
82
- const uniqueId = this.form.getAttribute('data-doc-id') || Math.random();
83
- const id = `${this.cssClass}_${uniqueId}`;
84
- this.checkbox = this._buildCheckbox(this.cssClass, id);
85
- this.span = this._buildSpan();
86
- this.label = this._buildLabel(id, this.cssClass, this.checkbox, this.span);
87
-
88
- // if form is currently using method delete to change state,
89
- // then checkbox is currently checked
90
- this.checked = (this.form.querySelectorAll('input[name=_method][value=delete]').length != 0);
91
- }
92
-
93
- _buildCheckbox(cssClass, id) {
94
- const checkbox = document.createElement('input');
95
- checkbox.setAttribute('type', 'checkbox');
96
- checkbox.classList.add(cssClass);
97
- checkbox.id = id;
98
- return checkbox
99
- }
100
-
101
- _buildLabel(id, cssClass, checkbox, span) {
102
- const label = document.createElement('label');
103
- label.classList.add(cssClass);
104
- label.for = id;
105
-
106
- label.appendChild(checkbox);
107
- label.appendChild(document.createTextNode(' '));
108
- label.appendChild(span);
109
- return label
110
25
  }
111
26
 
112
- _buildSpan() {
113
- return document.createElement('span')
114
- }
115
-
116
- _buildCheckboxDiv() {
117
- const checkboxDiv = document.createElement('div');
118
- checkboxDiv.classList.add('checkbox');
119
- checkboxDiv.classList.add(this.cssClass);
120
- checkboxDiv.appendChild(this.label);
121
- return checkboxDiv
122
- }
123
-
124
- render() {
125
- const children = this.form.children;
126
- Array.from(children).forEach((child) => child.classList.add('hidden'));
127
-
128
- //We're going to use the existing form to actually send our add/removes
129
- //This works conveneintly because the exact same action href is used
130
- //for both bookmarks/$doc_id. But let's take out the irrelevant parts
131
- //of the form to avoid any future confusion.
132
- this.form.querySelectorAll('input[type=submit]').forEach((el) => this.form.removeChild(el));
133
- this.form.appendChild(this._buildCheckboxDiv());
134
- this.updateStateFor(this.checked);
135
-
136
- this.checkbox.onclick = this._clicked.bind(this);
137
- }
138
-
139
- async _clicked(evt) {
140
- this.span.innerHTML = this.form.getAttribute('data-inprogress');
141
- this.label.setAttribute('disabled', 'disabled');
142
- this.checkbox.setAttribute('disabled', 'disabled');
143
- const response = await fetch(this.form.getAttribute('action'), {
144
- body: new FormData(this.form),
145
- method: this.form.getAttribute('method').toUpperCase(),
27
+ async clicked(evt) {
28
+ this.spanTarget.innerHTML = this.form.getAttribute('data-inprogress');
29
+ this.labelTarget.setAttribute('disabled', 'disabled');
30
+ this.checkboxTarget.setAttribute('disabled', 'disabled');
31
+ const response = await fetch(this.formTarget.getAttribute('action'), {
32
+ body: new FormData(this.formTarget),
33
+ method: this.formTarget.getAttribute('method').toUpperCase(),
146
34
  headers: {
147
35
  'Accept': 'application/json',
148
- 'X-Requested-With': 'XMLHttpRequest'
36
+ 'X-Requested-With': 'XMLHttpRequest',
37
+ 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]')?.content
149
38
  }
150
39
  });
151
- this.label.removeAttribute('disabled');
152
- this.checkbox.removeAttribute('disabled');
40
+ this.labelTarget.removeAttribute('disabled');
41
+ this.checkboxTarget.removeAttribute('disabled');
153
42
  if (response.ok) {
154
43
  const json = await response.json();
155
- this.checked = !this.checked;
156
- this.updateStateFor(this.checked);
44
+ this.updateStateFor(!this.checked);
157
45
  document.querySelector('[data-role=bookmark-counter]').innerHTML = json.bookmarks.count;
158
46
  } else {
159
47
  alert('Error');
160
48
  }
161
49
  }
162
50
 
51
+ get checked() {
52
+ return (this.form.querySelectorAll('input[name=_method][value=delete]').length != 0)
53
+ }
54
+
55
+ get formTarget() {
56
+ return this.form
57
+ }
58
+
59
+ get labelTarget() {
60
+ return this.form.querySelector('[data-checkboxsubmit-target="label"]')
61
+ }
62
+
63
+ get checkboxTarget() {
64
+ return this.form.querySelector('[data-checkboxsubmit-target="checkbox"]')
65
+ }
66
+
67
+ get spanTarget() {
68
+ return this.form.querySelector('[data-checkboxsubmit-target="span"]')
69
+ }
70
+
163
71
  updateStateFor(state) {
164
- this.checkbox.checked = state;
72
+ this.checkboxTarget.checked = state;
165
73
 
166
74
  if (state) {
167
- this.label.classList.add('checked');
75
+ this.labelTarget.classList.add('checked');
168
76
  //Set the Rails hidden field that fakes an HTTP verb
169
77
  //properly for current state action.
170
- this.form.querySelector('input[name=_method]').value = 'delete';
171
- this.span.innerHTML = this.form.getAttribute('data-present');
78
+ this.formTarget.querySelector('input[name=_method]').value = 'delete';
79
+ this.spanTarget.innerHTML = this.form.getAttribute('data-present');
172
80
  } else {
173
- this.label.classList.remove('checked');
174
- this.form.querySelector('input[name=_method]').value = 'put';
175
- this.span.innerHTML = this.form.getAttribute('data-absent');
81
+ this.labelTarget.classList.remove('checked');
82
+ this.formTarget.querySelector('input[name=_method]').value = 'put';
83
+ this.spanTarget.innerHTML = this.form.getAttribute('data-absent');
176
84
  }
177
85
  }
178
86
  }
179
87
 
180
- const BookmarkToggle = (() => {
181
- // change form submit toggle to checkbox
182
- Blacklight.doBookmarkToggleBehavior = function() {
183
- document.querySelectorAll(Blacklight.doBookmarkToggleBehavior.selector).forEach((el) => {
184
- new CheckboxSubmit(el).render();
185
- });
186
- };
187
- Blacklight.doBookmarkToggleBehavior.selector = 'form.bookmark-toggle';
188
-
189
- Blacklight.onLoad(function() {
190
- Blacklight.doBookmarkToggleBehavior();
191
- });
192
- })();
88
+ const BookmarkToggle = (e) => {
89
+ if (e.target.matches('[data-checkboxsubmit-target="checkbox"]')) {
90
+ const form = e.target.closest('form');
91
+ if (form) new CheckboxSubmit(form).clicked(e);
92
+ }
93
+ };
193
94
 
194
- const ButtonFocus = (() => {
195
- Blacklight.onLoad(function() {
196
- // Button clicks should change focus. As of 10/3/19, Firefox for Mac and
197
- // Safari both do not set focus to a button on button click.
198
- // See https://zellwk.com/blog/inconsistent-button-behavior/ for background information
199
- document.querySelectorAll('button.collapse-toggle').forEach((button) => {
200
- button.addEventListener('click', () => {
201
- event.target.focus();
202
- });
203
- });
204
- });
205
- })();
95
+ document.addEventListener('click', BookmarkToggle);
96
+
97
+ const ButtonFocus = (e) => {
98
+ // Button clicks should change focus. As of 10/3/19, Firefox for Mac and
99
+ // Safari both do not set focus to a button on button click.
100
+ // See https://zellwk.com/blog/inconsistent-button-behavior/ for background information
101
+ if (e.target.matches('[data-toggle="collapse"]') || e.target.matches('[data-bs-toggle="collapse"]')) {
102
+ e.target.focus();
103
+ }
104
+ };
105
+
106
+ document.addEventListener('click', ButtonFocus);
206
107
 
207
108
  /*
208
109
  The blacklight modal plugin can display some interactions inside a Bootstrap
@@ -238,7 +139,7 @@
238
139
 
239
140
  <div data-blacklight-modal="container">
240
141
  <div class="modal-header">
241
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
142
+ <button type="button" class="close" data-bl-dismiss="modal" aria-hidden="true">×</button>
242
143
  <h3 class="modal-title">Request Placed</h3>
243
144
  </div>
244
145
 
@@ -249,7 +150,7 @@
249
150
 
250
151
 
251
152
  <div class="modal-footer">
252
- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
153
+ <button type="button" class="btn btn-secondary" data-bl-dismiss="modal">Close</button>
253
154
  </div>
254
155
  </div>
255
156
 
@@ -260,13 +161,7 @@
260
161
  */
261
162
 
262
163
  const Modal = (() => {
263
- // We keep all our data in Blacklight.modal object.
264
- // Create lazily if someone else created first.
265
- if (Blacklight.modal === undefined) {
266
- Blacklight.modal = {};
267
- }
268
-
269
- const modal = Blacklight.modal;
164
+ const modal = {};
270
165
 
271
166
  // a Bootstrap modal div that should be already on the page hidden
272
167
  modal.modalSelector = '#blacklight-modal';
@@ -287,20 +182,19 @@
287
182
  modal.containerSelector = '[data-blacklight-modal~=container]';
288
183
 
289
184
  // Called on fatal failure of ajax load, function returns content
290
- // to show to user in modal. Right now called only for extreme
291
- // network errors.
292
- modal.onFailure = function (jqXHR, textStatus, errorThrown) {
293
- console.error('Server error:', this.url, jqXHR.status, errorThrown);
185
+ // to show to user in modal. Right now called only for network errors.
186
+ modal.onFailure = function (error) {
187
+ console.error('Server error:', this.url, error);
294
188
 
295
189
  const contents = `<div class="modal-header">
296
190
  <div class="modal-title">There was a problem with your request.</div>
297
- <button type="button" class="blacklight-modal-close btn-close close" data-dismiss="modal" data-bs-dismiss="modal" aria-label="Close">
298
- <span aria-hidden="true">&times;</span>
191
+ <button type="button" class="blacklight-modal-close btn-close close" data-bl-dismiss="modal" aria-label="Close">
192
+ <span aria-hidden="true" class="visually-hidden">&times;</span>
299
193
  </button>
300
194
  </div>
301
195
  <div class="modal-body">
302
196
  <p>Expected a successful response from the server, but got an error</p>
303
- <pre>${this.type} ${this.url}\n${jqXHR.status}: ${errorThrown}</pre>
197
+ <pre>${this.url}\n${error}</pre>
304
198
  </div>`;
305
199
 
306
200
  document.querySelector(`${modal.modalSelector} .modal-content`).innerHTML = contents;
@@ -309,10 +203,16 @@
309
203
  };
310
204
 
311
205
  // Add the passed in contents to the modal and display it.
312
- modal.receiveAjax = function (contents) {
206
+ modal.receiveAjax = function (contents) {
313
207
  const domparser = new DOMParser();
314
208
  const dom = domparser.parseFromString(contents, "text/html");
315
- const elements = dom.querySelectorAll(`${modal.containerSelector} > *`);
209
+ // If there is a containerSelector on the document, use its children.
210
+ let elements = dom.querySelectorAll(`${modal.containerSelector} > *`);
211
+ if (elements.length == 0) {
212
+ // If the containerSelector wasn't found, use the whole document
213
+ elements = dom.body.childNodes;
214
+ }
215
+
316
216
  document.querySelector(`${modal.modalSelector} .modal-content`).replaceChildren(...elements);
317
217
 
318
218
  modal.show();
@@ -338,99 +238,143 @@
338
238
  // into one selector with a comma, so if something matches BOTH selectors, it
339
239
  // still only gets the event handler called once.
340
240
  document.addEventListener('click', (e) => {
341
- if (e.target.matches(`${modal.triggerLinkSelector}, ${modal.preserveLinkSelector}`))
241
+ if (e.target.closest(`${modal.triggerLinkSelector}, ${modal.preserveLinkSelector}`))
342
242
  modal.modalAjaxLinkClick(e);
343
- else if (e.target.matches('[data-bl-dismiss="modal"]'))
243
+ else if (e.target.closest('[data-bl-dismiss="modal"]'))
344
244
  modal.hide();
345
245
  });
346
246
  };
347
247
 
348
248
  modal.hide = function (el) {
349
- const dom = document.querySelector(Blacklight.modal.modalSelector);
249
+ const dom = document.querySelector(modal.modalSelector);
350
250
 
351
251
  if (!dom.open) return
352
252
  dom.close();
353
253
  };
354
254
 
355
255
  modal.show = function(el) {
356
- const dom = document.querySelector(Blacklight.modal.modalSelector);
256
+ const dom = document.querySelector(modal.modalSelector);
357
257
 
358
258
  if (dom.open) return
359
259
  dom.showModal();
360
260
  };
361
261
 
362
- Blacklight.onLoad(function() {
363
- modal.setupModal();
364
- });
262
+ modal.setupModal();
263
+
264
+ return modal;
365
265
  })();
366
266
 
367
- const SearchContext = (() => {
368
- Blacklight.doSearchContextBehavior = function() {
369
- const elements = document.querySelectorAll('a[data-context-href]');
370
- const nodes = Array.from(elements);
267
+ const SearchContext = (e) => {
268
+ if (e.target.matches('[data-context-href]')) {
269
+ SearchContext.handleSearchContextMethod.call(e.target, e);
270
+ }
271
+ };
371
272
 
372
- nodes.forEach(function(element) {
373
- element.addEventListener('click', function(e) {
374
- Blacklight.handleSearchContextMethod.call(e.currentTarget, e);
375
- });
376
- });
377
- };
273
+ SearchContext.csrfToken = () => document.querySelector('meta[name=csrf-token]')?.content;
274
+ SearchContext.csrfParam = () => document.querySelector('meta[name=csrf-param]')?.content;
378
275
 
379
- Blacklight.csrfToken = () => document.querySelector('meta[name=csrf-token]')?.content;
380
- Blacklight.csrfParam = () => document.querySelector('meta[name=csrf-param]')?.content;
276
+ // this is the Rails.handleMethod with a couple adjustments, described inline:
277
+ // first, we're attaching this directly to the event handler, so we can check for meta-keys
278
+ SearchContext.handleSearchContextMethod = function(event) {
279
+ const link = this;
381
280
 
382
- // this is the Rails.handleMethod with a couple adjustments, described inline:
383
- // first, we're attaching this directly to the event handler, so we can check for meta-keys
384
- Blacklight.handleSearchContextMethod = function(event) {
385
- const link = this;
281
+ // instead of using the normal href, we need to use the context href instead
282
+ let href = link.getAttribute('data-context-href');
283
+ let target = link.getAttribute('target');
284
+ let csrfToken = SearchContext.csrfToken();
285
+ let csrfParam = SearchContext.csrfParam();
286
+ let form = document.createElement('form');
287
+ form.method = 'post';
288
+ form.action = href;
386
289
 
387
- // instead of using the normal href, we need to use the context href instead
388
- let href = link.getAttribute('data-context-href');
389
- let target = link.getAttribute('target');
390
- let csrfToken = Blacklight.csrfToken();
391
- let csrfParam = Blacklight.csrfParam();
392
- let form = document.createElement('form');
393
- form.method = 'post';
394
- form.action = href;
395
290
 
291
+ let formContent = `<input name="_method" value="post" type="hidden" />
292
+ <input name="redirect" value="${link.getAttribute('href')}" type="hidden" />`;
396
293
 
397
- let formContent = `<input name="_method" value="post" type="hidden" />
398
- <input name="redirect" value="${link.getAttribute('href')}" type="hidden" />`;
294
+ // check for meta keys.. if set, we should open in a new tab
295
+ if(event.metaKey || event.ctrlKey) {
296
+ target = '_blank';
297
+ }
399
298
 
400
- // check for meta keys.. if set, we should open in a new tab
401
- if(event.metaKey || event.ctrlKey) {
402
- target = '_blank';
403
- }
299
+ if (csrfParam !== undefined && csrfToken !== undefined) {
300
+ formContent += `<input name="${csrfParam}" value="${csrfToken}" type="hidden" />`;
301
+ }
404
302
 
405
- if (csrfParam !== undefined && csrfToken !== undefined) {
406
- formContent += `<input name="${csrfParam}" value="${csrfToken}" type="hidden" />`;
407
- }
303
+ // Must trigger submit by click on a button, else "submit" event handler won't work!
304
+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
305
+ formContent += '<input type="submit" />';
408
306
 
409
- // Must trigger submit by click on a button, else "submit" event handler won't work!
410
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
411
- formContent += '<input type="submit" />';
307
+ if (target) { form.setAttribute('target', target); }
412
308
 
413
- if (target) { form.setAttribute('target', target); }
309
+ form.style.display = 'none';
310
+ form.innerHTML = formContent;
311
+ document.body.appendChild(form);
312
+ form.querySelector('[type="submit"]').click();
414
313
 
415
- form.style.display = 'none';
416
- form.innerHTML = formContent;
417
- document.body.appendChild(form);
418
- form.querySelector('[type="submit"]').click();
314
+ event.preventDefault();
315
+ };
316
+
317
+ document.addEventListener('click', SearchContext);
419
318
 
420
- event.preventDefault();
421
- event.stopPropagation();
319
+ const Blacklight = function() {
320
+ const buffer = new Array;
321
+ return {
322
+ onLoad: function(func) {
323
+ buffer.push(func);
324
+ },
325
+
326
+ activate: function() {
327
+ for(let i = 0; i < buffer.length; i++) {
328
+ buffer[i].call();
329
+ }
330
+ },
331
+
332
+ listeners: function () {
333
+ const listeners = [];
334
+ if (typeof Turbo !== 'undefined') {
335
+ listeners.push('turbo:load', 'turbo:frame-load');
336
+ } else if (typeof Turbolinks !== 'undefined' && Turbolinks.supported) {
337
+ // Turbolinks 5
338
+ if (Turbolinks.BrowserAdapter) {
339
+ listeners.push('turbolinks:load');
340
+ } else {
341
+ // Turbolinks < 5
342
+ listeners.push('page:load', 'DOMContentLoaded');
343
+ }
344
+ } else {
345
+ listeners.push('DOMContentLoaded');
346
+ }
347
+
348
+ return listeners;
349
+ }
422
350
  };
351
+ }();
423
352
 
424
- Blacklight.onLoad(function() {
425
- Blacklight.doSearchContextBehavior();
353
+ // turbolinks triggers page:load events on page transition
354
+ // If app isn't using turbolinks, this event will never be triggered, no prob.
355
+ Blacklight.listeners().forEach(function(listener) {
356
+ document.addEventListener(listener, function() {
357
+ Blacklight.activate();
426
358
  });
427
- })();
359
+ });
360
+
361
+ Blacklight.onLoad(function () {
362
+ const elem = document.querySelector('.no-js');
363
+
364
+ // The "no-js" class may already have been removed because this function is
365
+ // run on every turbo:load event, in that case, it won't find an element.
366
+ if (!elem) return;
367
+
368
+ elem.classList.remove('no-js');
369
+ elem.classList.add('js');
370
+ });
428
371
 
429
372
  const index = {
430
373
  BookmarkToggle,
431
374
  ButtonFocus,
432
375
  Modal,
433
376
  SearchContext,
377
+ Core: Blacklight,
434
378
  onLoad: Blacklight.onLoad
435
379
  };
436
380