|
1 | | -$(() => { |
| 1 | +document.addEventListener('DOMContentLoaded', () => { |
| 2 | + /** |
| 3 | + * Extracts qualifier type from the field's dataset |
| 4 | + * @returns {string | null} |
| 5 | + */ |
| 6 | + const getQualifierType = () => { |
| 7 | + const field = document.querySelector('.js-sub-type-select'); |
| 8 | + return field instanceof HTMLSelectElement ? field.value : null; |
| 9 | + }; |
| 10 | + |
| 11 | + /** |
| 12 | + * Is a given subscription type qualifiable? |
| 13 | + * @param {string} type subscription type |
| 14 | + * @returns {boolean} |
| 15 | + */ |
| 16 | + const isQualifiable = (type) => { |
| 17 | + return ['category', 'tag', 'user'].includes(type); |
| 18 | + }; |
| 19 | + |
| 20 | + /** |
| 21 | + * Synchronizes qualifier field with the given type |
| 22 | + * @param {string} type subscription type |
| 23 | + * @param {boolean} [clear] whether to clear qualifier value |
| 24 | + */ |
| 25 | + const syncQualifier = (type, clear = true) => { |
| 26 | + const field = document.querySelector('.js-sub-qualifier-select'); |
| 27 | + const label = document.querySelector('.js-sub-qualifier-label'); |
| 28 | + |
| 29 | + if (field instanceof HTMLElement) { |
| 30 | + if (clear) { |
| 31 | + $(field).val(null).trigger('change'); |
| 32 | + } |
| 33 | + |
| 34 | + field.closest('.form-group')?.classList.toggle('hide', !isQualifiable(type)); |
| 35 | + } |
| 36 | + |
| 37 | + if (label instanceof HTMLElement) { |
| 38 | + label.textContent = type.slice(0, 1).toUpperCase() + type.slice(1).toLowerCase(); |
| 39 | + } |
| 40 | + }; |
| 41 | + |
| 42 | + /** |
| 43 | + * Is a given element a subscription type select? |
| 44 | + * @param {Element} element |
| 45 | + * @returns {element is HTMLSelectElement} |
| 46 | + */ |
| 47 | + const isTypeSelect = (element) => { |
| 48 | + return element.matches('.js-sub-type-select'); |
| 49 | + }; |
| 50 | + |
| 51 | + document.querySelectorAll('.js-sub-type-select, .js-sub-frequency-select').forEach((el) => { |
| 52 | + $(el).select2().on('change', ($event) => { |
| 53 | + if (isTypeSelect($event.target)) { |
| 54 | + syncQualifier($event.target.value); |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + if (isTypeSelect(el)) { |
| 59 | + syncQualifier(el.value, false); |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + $('.js-sub-qualifier-select').select2({ |
| 64 | + ajax: { |
| 65 | + url: () => { |
| 66 | + const type = getQualifierType(); |
| 67 | + return `/subscriptions/qualifiers?type=${type}` |
| 68 | + }, |
| 69 | + headers: { 'Accept': 'application/json' }, |
| 70 | + delay: 100, |
| 71 | + processResults: (results) => { |
| 72 | + return { results } |
| 73 | + }, |
| 74 | + } |
| 75 | + }); |
| 76 | + |
2 | 77 | $('.js-enable-subscription').on('change', async (evt) => { |
3 | 78 | const $tgt = $(evt.target); |
4 | 79 | const $sub = $tgt.parents('details'); |
|
0 commit comments