aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/forms.js
blob: e4d54a2a876c540a44e82dba27775f61fb6de5c7 (plain)
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/* ------------------------------------------------------------------------
 * Forms
 * ------------------------------------------------------------------------ */

import Report from "./report";
import {$gettext} from "./gettext";
import Dialog from "./dialog";

const Forms = {
    initialized: false,
    initialize: function(scope) {
        if (scope === undefined) {
            scope = document;
        }

        $('input[required],textarea[required]', scope).attr('aria-required', true);
        $('input[pattern][title],textarea[pattern][title]', scope).each(function() {
            $(this).data('message', $(this).attr('title'));
        });

        if (!Forms.initialized) {
            // add invalid-handler to every input and textarea on the page
            $(document).on('invalid', 'input, textarea', function() {
                $(this)
                    .attr('aria-invalid', 'true')
                    .change(function() {
                        $(this).removeAttr('aria-invalid');
                    });

                // get the fieldset that contains the invalid input
                var fieldset = $(this).closest('fieldset');
                // toggle the collapsed class if the fieldset is currently collapsed
                if (fieldset.hasClass('collapsed')) {
                    fieldset.toggleClass('collapsed');
                }
            });

            $(document).on('change', 'form.default label.file-upload input[type=file]', function(ev) {
                var selected_file = ev.target.files[0],
                    filename;
                if (
                    $(this)
                        .closest('label')
                        .find('.filename').length
                ) {
                    filename = $(this)
                        .closest('label')
                        .find('.filename');
                } else {
                    filename = $('<span class="filename"/>');
                    $(this)
                        .closest('label')
                        .append(filename);
                }
                filename.text(selected_file.name + ' ' + Math.ceil(selected_file.size / 1024) + 'KB');
            });
        }

        Forms.initialized = true;
    },
    create: function(forms) {
        STUDIP.Vue.load().then(({createApp}) => {
            forms.forEach(f => {
                if (f.nodeType !== 3) {
                    f.classList.add('vueified');

                    const app = createApp({
                        data() {
                            let params = JSON.parse(f.dataset.inputs);
                            params.STUDIPFORM_REQUIRED = f.dataset.required ? JSON.parse(f.dataset.required) : [];
                            params.STUDIPFORM_SERVERVALIDATION = f.dataset.server_validation > 0;
                            params.STUDIPFORM_DISPLAYVALIDATION = false;
                            params.STUDIPFORM_VALIDATIONNOTES = [];
                            params.STUDIPFORM_AUTOSAVEURL = f.dataset.autosave;
                            params.STUDIPFORM_VALIDATION_URL = f.dataset.validation_url;
                            params.STUDIPFORM_VALIDATED = false;
                            params.STUDIPFORM_REDIRECTURL = f.dataset.url;
                            params.STUDIPFORM_INPUTS_ORDER = [];
                            params.STUDIPFORM_SELECTEDLANGUAGES = {};
                            params.STUDIPFORM_EMIT_VALUES = f.dataset.emit;
                            for (let i in JSON.parse(f.dataset.inputs)) {
                                params.STUDIPFORM_INPUTS_ORDER.push(i);
                            }
                            return params;
                        },
                        methods: {
                            submit: function (e) {
                                if (this.STUDIPFORM_VALIDATED) {
                                    return;
                                }
                                this.STUDIPFORM_VALIDATIONNOTES = [];
                                this.STUDIPFORM_DISPLAYVALIDATION = true;

                                // validation:
                                this.validate()
                                    .then(() => {
                                        if (this.STUDIPFORM_EMIT_VALUES) {
                                            STUDIP.eventBus.emit('form.emitValues', this.getFormValues());
                                        } else {
                                            console.log('After validating');
                                            if (this.STUDIPFORM_AUTOSAVEURL) {
                                                let params = this.getFormValues();
                                                params.STUDIPFORM_AUTOSTORE = 1;

                                                $.post(this.STUDIPFORM_AUTOSAVEURL, params).done((output) => {
                                                    if (output === 'STUDIPFORM_STORE_SUCCESS' && this.STUDIPFORM_REDIRECTURL) {
                                                        //The form has been stored successfully:
                                                        window.location.href = this.STUDIPFORM_REDIRECTURL;
                                                    } else if (output !== 'STUDIPFORM_STORE_SUCCESS') {
                                                        Report.error($gettext('Es ist ein Fehler aufgetreten.'), output);
                                                    }
                                                });
                                            } else {
                                                this.STUDIPFORM_VALIDATED = true;
                                                this.$el.submit();
                                            }
                                        }
                                    }).catch(errors => {
                                        this.STUDIPFORM_VALIDATIONNOTES = errors;
                                        this.$el.scrollIntoView({behavior: 'smooth'});
                                    }
                                );
                                e.preventDefault();
                            },
                            getFormValues() {
                                let params = {
                                    security_token: this.$refs.securityToken.value
                                };
                                Object.keys(this.$data).forEach(i => {
                                    if (!i.startsWith('STUDIPFORM_')) {
                                        if (typeof this.$data[i] === 'boolean') {
                                            params[i] = this.$data[i] ? 1 : 0;
                                        } else {
                                            params[i] = this.$data[i];
                                        }
                                    }
                                });
                                return params;
                            },
                            async validate() {
                                this.$el.checkValidity();

                                // Check inputs
                                const inputs = this.$el.querySelectorAll('input,select,textarea');
                                let notes = Array.from(inputs)
                                    .filter(node => !node.validity.valid)
                                    .map(node => {
                                        const note = {
                                            name: node.name,
                                            label: node.labels[0].querySelector('.textlabel').innerText,
                                            description: node.dataset.validation_requirement ?? $gettext('Fehler'),
                                            describedby: node.id
                                        };

                                        if (node.validity.tooShort) {
                                            note.description = $gettext(
                                                'Geben Sie mindestens %{min} Zeichen ein.',
                                                {min: node.minLength}
                                            );
                                        }
                                        if (node.validity.valueMissing) {
                                            if (node.type === 'checkbox') {
                                                note.description = $gettext('Dieses Feld muss ausgewählt sein.');
                                            } else if (node.minLength > 0) {
                                                note.description = $gettext(
                                                    'Hier muss ein Wert mit mindestens %{min} Zeichen eingetragen werden.',
                                                    {min: node.minLength}
                                                );
                                            } else {
                                                note.description = $gettext('Hier muss ein Wert eingetragen werden.');
                                            }
                                        }

                                        return note;
                                    });

                                // Optional server validation
                                if (this.STUDIPFORM_SERVERVALIDATION) {
                                    let params = this.getFormValues();
                                    if (this.STUDIPFORM_AUTOSAVEURL) {
                                        params.STUDIPFORM_AUTOSTORE = 1;
                                    }
                                    params.STUDIPFORM_SERVERVALIDATION = 1;

                                    const output = await fetch(this.STUDIPFORM_VALIDATION_URL, {
                                        method: 'POST',
                                        body: new URLSearchParams(params),
                                        headers: {'X-Requested-With': 'XMLHttpRequest'}
                                    }).then(response => response.json());
                                    notes.push(
                                        ...output.map(item => ({
                                            name: item.name,
                                            label: item.label,
                                            description: item.error,
                                            describedby: null
                                        }))
                                    );
                                }

                                // Resolve or reject based on present error notes
                                if (notes.length > 0) {
                                    return Promise.reject(notes);
                                } else {
                                    return Promise.resolve();
                                }
                            },
                            setInputs(inputs) {
                                for (const [key, value] of Object.entries(inputs)) {
                                    if (this[key] !== undefined) {
                                        this[key] = value;
                                    }
                                }
                            },
                            selectLanguage(input_name, language_id) {
                                let languages = {
                                    ...this.STUDIPFORM_SELECTEDLANGUAGES
                                };
                                languages[input_name] = language_id;
                                this.STUDIPFORM_SELECTEDLANGUAGES = languages;
                            }
                        },
                        computed: {
                            ordererValidationNotes: function () {
                                let orderedNotes = [];
                                let inserted = [];
                                for (let i in this.STUDIPFORM_INPUTS_ORDER) {
                                    for (let k in this.STUDIPFORM_VALIDATIONNOTES) {
                                        if (this.STUDIPFORM_VALIDATIONNOTES[k].name === this.STUDIPFORM_INPUTS_ORDER[i]) {
                                            orderedNotes.push(this.STUDIPFORM_VALIDATIONNOTES[k]);
                                            inserted.push(k);
                                        }
                                    }
                                }
                                return orderedNotes.concat(
                                    this.STUDIPFORM_VALIDATIONNOTES.filter((note, index) => !inserted.includes(index))
                                );
                            }
                        },
                        mounted() {
                            if (this.$el.closest('.ui-dialog')) {
                                const cancelButton = this.$el.querySelector('footer .button.cancel:last-of-type');
                                if (cancelButton) {
                                    cancelButton.addEventListener('click', (e) => {
                                        Dialog.close();
                                        e.preventDefault();
                                    })
                                }
                            }
                        }
                    });
                    const instance = app.mount(f);
                    STUDIP.Vue.emit('form.mounted', {app: app, instance: instance});
                }
            });
        });
    }
};

export default Forms;