/
showon.es6.js
229 lines (198 loc) · 8.14 KB
/
showon.es6.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/**
* @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
((document) => {
'use strict';
/*
* JField 'showon' class
*/
class Showon {
/*
* Constructor
*
* @param {HTMLElement} cont Container element
*/
constructor(cont) {
const self = this;
this.container = cont || document;
this.fields = {
// origin-field-name: {
// origin: ['collection of all the trigger nodes'],
// targets: ['collection of nodes to be controlled control']
// }
};
this.showonFields = [].slice.call(this.container.querySelectorAll('[data-showon]'));
// Populate the fields data
if (this.showonFields.length) {
// @todo refactor this, dry
this.showonFields.forEach((field) => {
const jsondata = field.getAttribute('data-showon') || '';
const showonData = JSON.parse(jsondata);
let localFields;
if (showonData.length) {
localFields = [].slice.call(self.container.querySelectorAll(`[name="${showonData[0].field}"], [name="${showonData[0].field}[]"]`));
if (!this.fields[showonData[0].field]) {
this.fields[showonData[0].field] = {
origin: [],
targets: [],
};
}
// Add trigger elements
localFields.forEach((cField) => {
if (this.fields[showonData[0].field].origin.indexOf(cField) === -1) {
this.fields[showonData[0].field].origin.push(cField);
}
});
// Add target elements
this.fields[showonData[0].field].targets.push(field);
// Data showon can have multiple values
if (showonData.length > 1) {
showonData.forEach((value, index) => {
if (index === 0) {
return;
}
localFields = [].slice.call(self.container.querySelectorAll(`[name="${value.field}"], [name="${value.field}[]"]`));
if (!this.fields[showonData[0].field]) {
this.fields[showonData[0].field] = {
origin: [],
targets: [],
};
}
// Add trigger elements
localFields.forEach((cField) => {
if (this.fields[showonData[0].field].origin.indexOf(cField) === -1) {
this.fields[showonData[0].field].origin.push(cField);
}
});
// Add target elements
if (this.fields[showonData[0].field].targets.indexOf(field) === -1) {
this.fields[showonData[0].field].targets.push(field);
}
});
}
}
});
// Do some binding
this.linkedOptions = this.linkedOptions.bind(this);
// Attach events to referenced element, to check condition on change
Object.keys(this.fields).forEach((key) => {
if (this.fields[key].origin.length) {
this.fields[key].origin.forEach((elem) => {
// Initialise
self.linkedOptions(key);
// Setup listeners
elem.addEventListener('change', () => { self.linkedOptions(key); });
});
}
});
}
}
/**
*
* @param key
*/
linkedOptions(key) {
// Loop through the elements that need to be either shown or hidden
this.fields[key].targets.forEach((field) => {
const elementShowonDatas = JSON.parse(field.getAttribute('data-showon')) || [];
let showfield = true;
let itemval;
// Check if target conditions are satisfied
elementShowonDatas.forEach((elementShowonData, index) => {
const condition = elementShowonData || {};
condition.valid = 0;
// Test in each of the elements in the field array if condition is valid
this.fields[key].origin.forEach((originField) => {
if (originField.name !== elementShowonData.field) {
return;
}
const originId = originField.id;
// If checkbox or radio box the value is read from properties
if (originField.getAttribute('type') && ['checkbox', 'radio'].indexOf(originField.getAttribute('type').toLowerCase()) !== -1) {
if (!originField.checked) {
// Unchecked fields will return a blank and so always match
// a != condition so we skip them
return;
}
itemval = document.getElementById(originId).value;
} else {
// Select lists, text-area etc. Note that multiple-select list returns
// an Array here s0 we can always treat 'itemval' as an array
itemval = document.getElementById(originId).value;
// A multi-select <select> $field will return null when no elements are
// selected so we need to define itemval accordingly
if (itemval === null && originField.tagName.toLowerCase() === 'select') {
itemval = [];
}
}
// Convert to array to allow multiple values in the field (e.g. type=list multiple)
// and normalize as string
if (!(typeof itemval === 'object')) {
itemval = JSON.parse(`["${itemval}"]`);
}
// Test if any of the values of the field exists in showon conditions
itemval.forEach((val) => {
// ":" Equal to one or more of the values condition
if (condition.sign === '=' && condition.values.indexOf(val) !== -1) {
condition.valid = 1;
}
// "!:" Not equal to one or more of the values condition
if (condition.sign === '!=' && condition.values.indexOf(val) === -1) {
condition.valid = 1;
}
});
});
// Verify conditions
// First condition (no operator): current condition must be valid
if (condition.op === '') {
if (condition.valid === 0) {
showfield = false;
}
} else {
// Other conditions (if exists)
// AND operator: both the previous and current conditions must be valid
if (condition.op === 'AND' && condition.valid + elementShowonDatas[index - 1].valid < 2) {
showfield = false;
}
// OR operator: one of the previous and current conditions must be valid
if (condition.op === 'OR' && condition.valid + elementShowonDatas[index - 1].valid > 0) {
showfield = true;
}
}
});
// If conditions are satisfied show the target field(s), else hide
field.style.display = (showfield) ? 'block' : 'none';
});
}
}
/**
* Initialize 'showon' feature at an initial page load
*/
document.addEventListener('DOMContentLoaded', () => {
// eslint-disable-next-line no-new
new Showon(document);
});
/**
* Initialize 'showon' feature when part of the page was updated
*/
document.addEventListener('joomla:updated', (event) => {
// eslint-disable-next-line prefer-destructuring
const target = event.target;
// Check is it subform, then wee need to fix some "showon" config
if (target.classList.contains('subform-repeatable-group')) {
const elements = [].slice.call(target.querySelectorAll('[data-showon]'));
const baseName = target.getAttribute('data-baseName');
const group = target.getAttribute('data-group');
const search = new RegExp(`\\[${baseName}\\]\\[${baseName}X\\]`, 'g');
const replace = `[${baseName}][${group}]`;
// Fix showon field names in a current group
elements.forEach((element) => {
const showon = element.getAttribute('data-showon').replace(search, replace);
element.setAttribute('data-showon', showon);
});
}
// eslint-disable-next-line no-new
new Showon(event.target);
});
})(document);