Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/**
2
 * Show/hide admin settings based on other settings selected
3
 *
4
 * @copyright 2018 Davo Smith, Synergy Learning
5
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6
 */
7
define(['jquery'], function($) {
8
    var dependencies;
9
 
10
    // -------------------------------------------------
11
    // Support functions, used by dependency functions.
12
    // -------------------------------------------------
13
 
14
    /**
15
     * Check to see if the given element is the hidden element that makes sure checkbox
16
     * elements always submit a value.
17
     * @param {jQuery} $el
18
     * @returns {boolean}
19
     */
20
    function isCheckboxHiddenElement($el) {
21
        return ($el.is('input[type=hidden]') && $el.siblings('input[type=checkbox][name="' + $el.attr('name') + '"]').length);
22
    }
23
 
24
    /**
25
     * Check to see if this is a radio button with the wrong value (i.e. a radio button from
26
     * the group we are interested in, but not the specific one we wanted).
27
     * @param {jQuery} $el
28
     * @param {string} value
29
     * @returns {boolean}
30
     */
31
    function isWrongRadioButton($el, value) {
32
        return ($el.is('input[type=radio]') && $el.attr('value') !== value);
33
    }
34
 
35
    /**
36
     * Is this element relevant when we're looking for checked / not checked status?
37
     * @param {jQuery} $el
38
     * @param {string} value
39
     * @returns {boolean}
40
     */
41
    function isCheckedRelevant($el, value) {
42
        return (!isCheckboxHiddenElement($el) && !isWrongRadioButton($el, value));
43
    }
44
 
45
    /**
46
     * Is this an unchecked radio button? (If it is, we want to skip it, as
47
     * we're only interested in the value of the radio button that is checked)
48
     * @param {jQuery} $el
49
     * @returns {boolean}
50
     */
51
    function isUncheckedRadioButton($el) {
52
        return ($el.is('input[type=radio]') && !$el.prop('checked'));
53
    }
54
 
55
    /**
56
     * Is this an unchecked checkbox?
57
     * @param {jQuery} $el
58
     * @returns {boolean}
59
     */
60
    function isUncheckedCheckbox($el) {
61
        return ($el.is('input[type=checkbox]') && !$el.prop('checked'));
62
    }
63
 
64
    /**
65
     * Is this a multi-select select element?
66
     * @param {jQuery} $el
67
     * @returns {boolean}
68
     */
69
    function isMultiSelect($el) {
70
        return ($el.is('select') && $el.prop('multiple'));
71
    }
72
 
73
    /**
1441 ariadna 74
     * Are the selected values of a multi-select a subset of (i.e. 'in') the list of values provided?
1 efrain 75
     * @param {jQuery} $el
76
     * @param {array} values
77
     * @returns {boolean}
78
     */
1441 ariadna 79
    function multiSelectIn($el, values) {
80
        let selected = $el.val() || [];
81
        if (selected.length == 0) {
82
            selected.push('');
83
        }
84
 
85
        // Lock/hide if the selected values are a subset of the values.
86
        let isSubset = selected.every(element => values.includes(element));
87
        return isSubset;
88
    }
89
 
90
    /**
91
     * Are the selected values of a multi-select an exact match (i.e. 'eq') to the list of values provided?
92
     * @param {jQuery} $el
93
     * @param {array} values
94
     * @returns {boolean}
95
     */
1 efrain 96
    function multiSelectMatches($el, values) {
97
        var selected = $el.val() || [];
1441 ariadna 98
        if (values.length === 1 && values[0] === '') {
99
            // Values array contains a single empty entry -> value was empty.
100
            return selected.length === 0;
1 efrain 101
        }
102
        if (selected.length !== values.length) {
103
            // Different number of expected and actual values - cannot possibly be a match.
104
            return false;
105
        }
106
        for (var i in selected) {
107
            if (selected.hasOwnProperty(i)) {
108
                if (values.indexOf(selected[i]) === -1) {
109
                    return false; // Found a non-matching value - give up immediately.
110
                }
111
            }
112
        }
113
        // Didn't find a non-matching value, so we have a match.
114
        return true;
115
    }
116
 
117
    // -------------------------------
118
    // Specific dependency functions.
119
    // -------------------------------
120
 
121
    var depFns = {
122
        notchecked: function($dependon, value) {
123
            var hide = false;
124
            value = String(value);
125
            $dependon.each(function(idx, el) {
126
                var $el = $(el);
127
                if (isCheckedRelevant($el, value)) {
128
                    hide = hide || !$el.prop('checked');
129
                }
130
            });
131
            return hide;
132
        },
133
 
134
        checked: function($dependon, value) {
135
            var hide = false;
136
            value = String(value);
137
            $dependon.each(function(idx, el) {
138
                var $el = $(el);
139
                if (isCheckedRelevant($el, value)) {
140
                    hide = hide || $el.prop('checked');
141
                }
142
            });
143
            return hide;
144
        },
145
 
146
        noitemselected: function($dependon) {
147
            var hide = false;
148
            $dependon.each(function(idx, el) {
149
                var $el = $(el);
150
                hide = hide || ($el.prop('selectedIndex') === -1);
151
            });
152
            return hide;
153
        },
154
 
155
        eq: function($dependon, value) {
156
            var hide = false;
157
            var hiddenVal = false;
158
            value = String(value);
159
            $dependon.each(function(idx, el) {
160
                var $el = $(el);
161
                if (isUncheckedRadioButton($el)) {
162
                    // For radio buttons, we're only interested in the one that is checked.
163
                    return;
164
                }
165
                if (isCheckboxHiddenElement($el)) {
166
                    // This is the hidden input that is part of the checkbox setting.
167
                    // We will use this value, if the associated checkbox is unchecked.
168
                    hiddenVal = ($el.val() === value);
169
                    return;
170
                }
171
                if (isUncheckedCheckbox($el)) {
172
                    // Checkbox is not checked - hide depends on the 'unchecked' value stored in
173
                    // the associated hidden element, which we have already found, above.
174
                    hide = hide || hiddenVal;
175
                    return;
176
                }
177
                if (isMultiSelect($el)) {
178
                    // Expect a list of values to match, separated by '|' - all of them must
179
                    // match the values selected.
180
                    var values = value.split('|');
181
                    hide = multiSelectMatches($el, values);
182
                    return;
183
                }
184
                // All other element types - just compare the value directly.
185
                hide = hide || ($el.val() === value);
186
            });
187
            return hide;
188
        },
189
 
190
        'in': function($dependon, value) {
191
            var hide = false;
192
            var hiddenVal = false;
193
            var values = value.split('|');
194
            $dependon.each(function(idx, el) {
195
                var $el = $(el);
196
                if (isUncheckedRadioButton($el)) {
197
                    // For radio buttons, we're only interested in the one that is checked.
198
                    return;
199
                }
200
                if (isCheckboxHiddenElement($el)) {
201
                    // This is the hidden input that is part of the checkbox setting.
202
                    // We will use this value, if the associated checkbox is unchecked.
203
                    hiddenVal = (values.indexOf($el.val()) > -1);
204
                    return;
205
                }
206
                if (isUncheckedCheckbox($el)) {
207
                    // Checkbox is not checked - hide depends on the 'unchecked' value stored in
208
                    // the associated hidden element, which we have already found, above.
209
                    hide = hide || hiddenVal;
210
                    return;
211
                }
212
                if (isMultiSelect($el)) {
1441 ariadna 213
                    // For multiselect, we check to see if the selected values are a subset of the list of values provided.
214
                    hide = multiSelectIn($el, values);
1 efrain 215
                    return;
216
                }
217
                // All other element types - check to see if the value is in the list.
218
                hide = hide || (values.indexOf($el.val()) > -1);
219
            });
220
            return hide;
221
        },
222
 
223
        defaultCondition: function($dependon, value) { // Not equal.
224
            var hide = false;
225
            var hiddenVal = false;
226
            value = String(value);
227
            $dependon.each(function(idx, el) {
228
                var $el = $(el);
229
                if (isUncheckedRadioButton($el)) {
230
                    // For radio buttons, we're only interested in the one that is checked.
231
                    return;
232
                }
233
                if (isCheckboxHiddenElement($el)) {
234
                    // This is the hidden input that is part of the checkbox setting.
235
                    // We will use this value, if the associated checkbox is unchecked.
236
                    hiddenVal = ($el.val() !== value);
237
                    return;
238
                }
239
                if (isUncheckedCheckbox($el)) {
240
                    // Checkbox is not checked - hide depends on the 'unchecked' value stored in
241
                    // the associated hidden element, which we have already found, above.
242
                    hide = hide || hiddenVal;
243
                    return;
244
                }
245
                if (isMultiSelect($el)) {
246
                    // Expect a list of values to match, separated by '|' - all of them must
247
                    // match the values selected to *not* hide the element.
248
                    var values = value.split('|');
249
                    hide = !multiSelectMatches($el, values);
250
                    return;
251
                }
252
                // All other element types - just compare the value directly.
253
                hide = hide || ($el.val() !== value);
254
            });
255
            return hide;
256
        }
257
    };
258
 
259
    /**
260
     * Find the element with the given name
261
     * @param {String} name
262
     * @returns {*|jQuery|HTMLElement}
263
     */
264
    function getElementsByName(name) {
265
        // For the array elements, we use [name^="something["] to find the elements that their name begins with 'something['/
266
        // This is to find both name = 'something[]' and name='something[index]'.
267
        return $('[name="' + name + '"],[name^="' + name + '["]');
268
    }
269
 
270
    /**
271
     * Check to see whether a particular condition is met
272
     * @param {*|jQuery|HTMLElement} $dependon
273
     * @param {String} condition
274
     * @param {mixed} value
275
     * @returns {Boolean}
276
     */
277
    function checkDependency($dependon, condition, value) {
278
        if (typeof depFns[condition] === "function") {
279
            return depFns[condition]($dependon, value);
280
        }
281
        return depFns.defaultCondition($dependon, value);
282
    }
283
 
284
    /**
285
     * Show / hide the elements that depend on some elements.
286
     */
287
    function updateDependencies() {
288
        // Process all dependency conditions.
289
        var toHide = {};
290
        $.each(dependencies, function(dependonname) {
291
            var dependon = getElementsByName(dependonname);
292
            $.each(dependencies[dependonname], function(condition, values) {
293
                $.each(values, function(value, elements) {
294
                    var hide = checkDependency(dependon, condition, value);
295
                    $.each(elements, function(idx, elToHide) {
296
                        if (toHide.hasOwnProperty(elToHide)) {
297
                            toHide[elToHide] = toHide[elToHide] || hide;
298
                        } else {
299
                            toHide[elToHide] = hide;
300
                        }
301
                    });
302
                });
303
            });
304
        });
305
 
306
        // Update the hidden status of all relevant elements.
307
        $.each(toHide, function(elToHide, hide) {
308
            getElementsByName(elToHide).each(function(idx, el) {
309
                var $parent = $(el).closest('.form-item');
310
                if ($parent.length) {
311
                    if (hide) {
312
                        $parent.hide();
313
                    } else {
314
                        $parent.show();
315
                    }
316
                }
317
            });
318
        });
319
    }
320
 
321
    /**
322
     * Initialise the event handlers.
323
     */
324
    function initHandlers() {
325
        $.each(dependencies, function(depname) {
326
            var $el = getElementsByName(depname);
327
            if ($el.length) {
328
                $el.on('change', updateDependencies);
329
            }
330
        });
331
        updateDependencies();
332
    }
333
 
334
    /**
335
     * Hide the 'this setting may be hidden' messages.
336
     */
337
    function hideDependencyInfo() {
338
        $('.form-dependenton').hide();
339
    }
340
 
341
    return {
342
        init: function(opts) {
343
            dependencies = opts.dependencies;
344
            initHandlers();
345
            hideDependencyInfo();
346
        }
347
    };
1441 ariadna 348
});