import { Logger } from '../../Log/Logger.js'; import { NotificationLevel } from '../../Message/Notification/NotificationLevel.js'; import { NotificationMessage } from '../../Message/Notification/NotificationMessage.js'; import { NotificationType } from '../../Message/Notification/NotificationType.js'; import { Request } from '../../Message/Request/Request.js'; import { RequestMethod } from '../../Message/Request/RequestMethod.js'; import { RequestType } from '../../Message/Request/RequestType.js'; import { Response } from '../../Message/Response/Response.js'; import { FormView } from '../../Views/FormView.js'; import { UriFactory } from '../../Uri/UriFactory.js'; /** * Form manager class. * * @copyright Dennis Eichhorn * @license OMS License 1.0 * @version 1.0.0 * @since 1.0.0 * * data-ui-content = what is the main parent * data-ui-element = what are the elements to replace * * @todo Orange-Management/jsOMS#60 * On change listener * Allow to add a on change listener in a form. This should result in automatic submits after changing a form. * Consider the following cases to submit the form: * * on Enter (all except textarea) * * on Change (by using a timer) * * on Leave (all elements) * The listener should be defined in the form definition once and in js be applied to all form elements. * * @todo Orange-Management/Modules#177 * Hotkey for saving forms for creation/edit * Instead of using the mouse to click save the user should be able to use a hotkey to save/create/update the current form. * The hotkey on PC should be alt+enter or alt+shift+enter or alt+s */ export class Form { /** * @constructor * * @param {Object} app Application * * @since 1.0.0 */ constructor (app) { this.app = app; this.forms = {}; this.ignore = {}; }; /** * Get form * * @param {string} id Form Id * * @return {void} * * @since 1.0.0 */ get (id) { if (!this.forms.hasOwnProperty(id)) { this.bind(id); } return this.forms[id]; }; /** * Is form ignored? * * @param {string} id Form Id * * @return {boolean} * * @since 1.0.0 */ isIgnored (id) { return this.ignore.indexOf(id) !== -1; }; /** * Unbind form * * @param {string} id Form Id * * @return {void} * * @since 1.0.0 */ unbind (id) { }; /** * Bind form * * @param {string} id Form Id (optional) * * @return {void} * * @since 1.0.0 */ bind (id) { if (typeof id !== 'undefined' && typeof this.ignore[id] === 'undefined') { this.bindForm(id); } else { const forms = document.querySelectorAll('form, [data-tag=form]'), length = !forms ? 0 : forms.length; for (let i = 0; i < length; ++i) { let formId = forms[i].getAttribute('id'); if (typeof formId !== 'undefined' && formId !== null && typeof this.ignore[formId] === 'undefined') { this.bindForm(formId); } } } }; /** * Bind form * * @param {string} id Form Id * * @return {void} * * @since 1.0.0 */ bindForm (id) { if (typeof id === 'undefined' || !id) { Logger.instance.info('A form doesn\'t have an ID.'); return; } // don't overwrite bind if (this.forms.hasOwnProperty(id)) { return; } const self = this; this.forms[id] = new FormView(id); let length = 0; const submits = this.forms[id].getSubmit() const submitLength = submits.length; this.unbind(id); const removable = this.forms[id].getRemove(); length = removable === null ? 0 : removable.length; for (let i = 0; i < length; ++i) { this.bindRemovable(removable[i], id); } const addable = this.forms[id].getAdd(); length = addable === null ? 0 : addable.length; for (let i = 0; i < length; ++i) { this.bindAdd(addable[i], id); } const save = this.forms[id].getSave(); length = save === null ? 0 : save.length; for (let i = 0; i < length; ++i) { this.bindSaveInline(save[i], id); } // @todo implement bindSaveExternal ??? const cancel = this.forms[id].getCancel(); length = cancel === null ? 0 : cancel.length; for (let i = 0; i < length; ++i) { this.bindCancelInline(cancel[i], id); } const update = this.forms[id].getUpdate(); length = update === null ? 0 : update.length; for (let i = 0; i < length; ++i) { this.bindUpdatable(update[i], id); } const imgPreviews = this.forms[id].getImagePreviews(); length = imgPreviews === null ? 0 : imgPreviews.length; for (let i = 0; i < length; ++i) { this.bindImagePreview(imgPreviews[i], id); } for (let i = 0; i < submitLength; ++i) { submits[i].addEventListener('click', function (event) { jsOMS.preventAll(event); self.submit(self.forms[id], submits[i].getAttribute('formaction')); }); } }; /** * Create the new input * * @param {string} imageUpload Create form * @param {Object} id Id * * @return {void} * * @since 1.0.0 */ bindImagePreview(imageUpload, id) { const self = this; imageUpload.addEventListener('change', function () { const preview = document.querySelector('#preview-' + imageUpload.getAttribute('name')); preview.src = window.URL.createObjectURL(imageUpload.files[0]); preview.onload = function () { window.URL.revokeObjectURL(this.src); } }); } /** * Unbind form * * @param {string} id Form Id * * @return {boolean} * * @since 1.0.0 */ unbindForm (id) { if ((findex = this.forms[id]) !== 'undefined') { this.forms[id].unbind(); this.forms.splice(id, 1); return true; } return false; }; /** * Submit form * * Calls injections first before executing the actual form submit * * @param {Object} form Form object * @param {string} [action] Action different from the form action (e.g. formaction=*) * * @return {void} * * @since 1.0.0 */ submit (form, action = null) { action = typeof action !== 'undefined' ? action : null; /* Handle injects */ const self = this, injects = form.getSubmitInjects(); let counter = 0; // Register normal form behavior if (!this.app.eventManager.isAttached(form.getId())) { this.app.eventManager.attach(form.getId(), function () { self.submitForm(form, action); }, true); } // Run all injects first for (const property in injects) { if (injects.hasOwnProperty(property)) { ++counter; //this.app.eventManager.addGroup(form.getId(), counter); const result = injects[property](form, form.getId()); if (result === false) { return; } } else { Logger.instance.warning('Invalid property.'); } } if (counter < 1) { this.app.eventManager.trigger(form.getId()); } }; /** * Submit form data * * Submits the main form data * * @param {Object} form Form object * @param {string} [action] Action different from the form action (e.g. formaction=*) * * @return {void} * * @since 1.0.0 */ submitForm (form, action = null) { action = typeof action !== 'undefined' ? action : null; if (!form.isValid()) { this.app.notifyManager.send( new NotificationMessage( NotificationLevel.INFO, jsOMS.lang.Info, jsOMS.lang.invalid_form ), NotificationType.APP_NOTIFICATION ); Logger.instance.debug('Form "' + form.getId() + '" has invalid values.'); return; } if (form.getMethod() !== RequestMethod.GET && Math.abs(Date.now() - form.getLastSubmit()) < 500 ) { return; } form.updateLastSubmit(); /* Handle default submit */ const request = new Request(), self = this; request.setData(form.getData()); request.setType(RequestType.FORM_DATA); request.setUri(action ? action : form.getAction()); request.setMethod(form.getMethod()); request.setSuccess(function (xhr) { console.log(xhr.response); try { const o = JSON.parse(xhr.response)[0], response = new Response(o); let successInject = null; if ((successInject = form.getSuccess()) !== null) { successInject(response); } else if (typeof response.get('type') !== 'undefined') { self.app.responseManager.run(response.get('type'), response.get(), request); } else if (typeof o.status !== 'undefined' && o.status !== NotificationLevel.HIDDEN) { self.app.notifyManager.send( new NotificationMessage(o.status, o.title, o.message), NotificationType.APP_NOTIFICATION ); } } catch (e) { console.log(e); Logger.instance.error('Invalid form response. \n' + 'URL: ' + form.getAction() + '\n' + 'Request: ' + JSON.stringify(form.getData()) + '\n' + 'Response: ' + xhr.response ); } }); request.setResultCallback(0, function (xhr) { self.app.notifyManager.send( new NotificationMessage( NotificationLevel.ERROR, 'Failure', 'Some failure happened' ), NotificationType.APP_NOTIFICATION ); }); request.send(); if (form.getFinally() !== null) { form.getFinally()(); } }; /** * Count the bound forms * * @return {int} * * @since 1.0.0 */ count () { return this.forms.length; }; /** * Create the ui element * * @param {string} create Create form button * @param {Object} id Id * * @return {void} * * @since 1.0.0 */ bindAddExternal(create, id) { const self = this; /** * @todo Orange-Management/jsOMS#75 * Currently only one add button is allowed per form. Allow multiple/different add buttons in a form. */ create.addEventListener('click', function () { const formElement = document.getElementById(id); const parents = []; const selectors = formElement.getAttribute('data-add-element').split(','), selectorLength = selectors.length; const addTpl = formElement.getAttribute('data-add-tpl').split(','); const subMain = formElement.getAttribute('data-add-content').charAt(0) === '#' ? document.querySelector(formElement.getAttribute('data-add-content')) : formElement.querySelector(formElement.getAttribute('data-add-content')); let values = []; let text = []; const newEle = []; for (let i = 0; i < selectorLength; ++i) { // this handles selectors such as 'ancestor > child/or/sibling' and many more const selector = selectors[i].trim(' ').split(' '); let subSelector = ''; if (selector.length !== 0) { selector.shift(); subSelector = selector.join(' ').trim(); } newEle.push(document.querySelector(addTpl[i]).content.cloneNode(true)); parents.push( selector.length === 0 ? newEle[i].firstElementChild : newEle[i].firstElementChild.querySelector(subSelector) ); values = values.concat( parents[i].hasAttribute('data-tpl-value') ? parents[i] : Array.prototype.slice.call(parents[i].querySelectorAll('[data-tpl-value]')) ); text = text.concat( parents[i].hasAttribute('data-tpl-text') ? parents[i] : Array.prototype.slice.call(parents[i].querySelectorAll('[data-tpl-text]')) ); if (newEle[i].firstElementChild.id === null) { let eleId = ''; do { eleId = 'f' + Math.random().toString(36).substring(7); } while (document.getElementById(eleId) !== null); // root element is form even if it has a different tag than