diff --git a/lang/en/form.php b/lang/en/form.php index ab3ee372988..0041e324c1d 100644 --- a/lang/en/form.php +++ b/lang/en/form.php @@ -60,6 +60,7 @@ $string['mustbeoverriden'] = 'Abstract form_definition() method in class {$a} mu $string['newvaluefor'] = 'New value for {$a}'; $string['nomethodforaddinghelpbutton'] = 'There is no method for adding a help button to form element {$a->name} (class {$a->classname})'; $string['nonexistentformelements'] = 'Trying to add help buttons to non-existent form elements : {$a}'; +$string['nopermissionform'] = 'You don\'t have permission to access this form.'; $string['noselection'] = 'No selection'; $string['nosuggestions'] = 'No suggestions'; $string['novalue'] = 'Nothing entered'; diff --git a/lib/amd/build/fragment.min.js b/lib/amd/build/fragment.min.js index ce282dd54b3..e553771da71 100644 --- a/lib/amd/build/fragment.min.js +++ b/lib/amd/build/fragment.min.js @@ -1,2 +1,2 @@ -define ("core/fragment",["jquery","core/ajax"],function(a,b){var c=function loadFragment(a,c,d,e){var f=[];for(var g in e){f.push({name:g,value:e[g]})}return b.call([{methodname:"core_get_fragment",args:{component:a,callback:c,contextid:d,args:f}}])[0]};return{loadFragment:function loadFragment(b,d,e,f){var g=a.Deferred();c(b,d,e,f).then(function(b){var c=a(b.javascript),d="";c.each(function(b,c){c=a(c);var e=c.prop("tagName");if(e&&"script"==e.toLowerCase()){if(c.attr("src")){var f=!1;a("script").each(function(b,d){if(a(d).attr("src")==c.attr("src")){f=!0}return!f});if(!f){d+=" { ";d+=" node = document.createElement(\"script\"); ";d+=" node.type = \"text/javascript\"; ";d+=" node.src = decodeURI(\""+encodeURI(c.attr("src"))+"\"); ";d+=" document.getElementsByTagName(\"head\")[0].appendChild(node); ";d+=" } "}}else{d+=" "+c.text()}}});g.resolve(b.html,d)}).fail(function(a){g.reject(a)});return g.promise()}}}); +define ("core/fragment",["jquery","core/ajax"],function(a,b){var c=function loadFragment(a,c,d,e){var f=[];for(var g in e){f.push({name:g,value:e[g]})}return b.call([{methodname:"core_get_fragment",args:{component:a,callback:c,contextid:d,args:f}}])[0]},d=function processCollectedJavascript(b){var c=a(b),d="";c.each(function(b,c){c=a(c);var e=c.prop("tagName");if(e&&"script"==e.toLowerCase()){if(c.attr("src")){var f=!1;a("script").each(function(b,d){if(a(d).attr("src")==c.attr("src")){f=!0}return!f});if(!f){d+=" { ";d+=" node = document.createElement(\"script\"); ";d+=" node.type = \"text/javascript\"; ";d+=" node.src = decodeURI(\""+encodeURI(c.attr("src"))+"\"); ";d+=" document.getElementsByTagName(\"head\")[0].appendChild(node); ";d+=" } "}}else{d+=" "+c.text()}}});return d};return{loadFragment:function loadFragment(b,e,f,g){var h=a.Deferred();c(b,e,f,g).then(function(a){h.resolve(a.html,d(a.javascript))}).fail(function(a){h.reject(a)});return h.promise()},processCollectedJavascript:function processCollectedJavascript(a){return d(a)}}}); //# sourceMappingURL=fragment.min.js.map diff --git a/lib/amd/build/fragment.min.js.map b/lib/amd/build/fragment.min.js.map index 78686e71234..7bd0174c553 100644 --- a/lib/amd/build/fragment.min.js.map +++ b/lib/amd/build/fragment.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/fragment.js"],"names":["define","$","ajax","loadFragment","component","callback","contextid","params","formattedparams","index","push","name","value","call","methodname","args","promise","Deferred","then","data","jsNodes","javascript","allScript","each","scriptNode","tagName","prop","toLowerCase","attr","exists","s","encodeURI","text","resolve","html","fail","ex","reject"],"mappings":"AAyBAA,OAAM,iBAAC,CAAC,QAAD,CAAW,WAAX,CAAD,CAA0B,SAASC,CAAT,CAAYC,CAAZ,CAAkB,CAY9C,GAAIC,CAAAA,CAAY,CAAG,QAAfA,CAAAA,YAAe,CAASC,CAAT,CAAoBC,CAApB,CAA8BC,CAA9B,CAAyCC,CAAzC,CAAiD,CAEhE,GAAIC,CAAAA,CAAe,CAAG,EAAtB,CACA,IAAK,GAAIC,CAAAA,CAAT,GAAkBF,CAAAA,CAAlB,CAA0B,CACtBC,CAAe,CAACE,IAAhB,CAAqB,CACjBC,IAAI,CAAEF,CADW,CAEjBG,KAAK,CAAEL,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,MAAO,CAACA,CACX,CALD,EAMA,GAAI,CAACA,CAAL,CAAa,CACTP,CAAS,EAAI,KAAb,CACAA,CAAS,EAAI,8CAAb,CACAA,CAAS,EAAI,oCAAb,CACAA,CAAS,EAAI,2BAA4BS,SAAS,CAACP,CAAU,CAACI,IAAX,CAAgB,KAAhB,CAAD,CAArC,CAAgE,OAA7E,CACAN,CAAS,EAAI,iEAAb,CACAA,CAAS,EAAI,KAChB,CACJ,CAjBD,IAiBO,CACHA,CAAS,EAAI,IAAME,CAAU,CAACQ,IAAX,EACtB,CACJ,CACJ,CAzBD,EA0BAhB,CAAO,CAACiB,OAAR,CAAgBd,CAAI,CAACe,IAArB,CAA2BZ,CAA3B,CAEH,CA/BD,EA+BGa,IA/BH,CA+BQ,SAASC,CAAT,CAAa,CACjBpB,CAAO,CAACqB,MAAR,CAAeD,CAAf,CACH,CAjCD,EAkCA,MAAOpB,CAAAA,CAAO,CAACA,OAAR,EACV,CAlDoC,CAoD5C,CArFK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A way to call HTML fragments to be inserted as required via JavaScript.\n *\n * @module core/fragment\n * @class fragment\n * @package core\n * @copyright 2016 Adrian Greeve \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 3.1\n */\ndefine(['jquery', 'core/ajax'], function($, ajax) {\n\n /**\n * Loads an HTML fragment through a callback.\n *\n * @method loadFragment\n * @param {string} component Component where callback is located.\n * @param {string} callback Callback function name.\n * @param {integer} contextid Context ID of the fragment.\n * @param {object} params Parameters for the callback.\n * @return {Promise} JQuery promise object resolved when the fragment has been loaded.\n */\n var loadFragment = function(component, callback, contextid, params) {\n // Change params into required webservice format.\n var formattedparams = [];\n for (var index in params) {\n formattedparams.push({\n name: index,\n value: params[index]\n });\n }\n\n return ajax.call([{\n methodname: 'core_get_fragment',\n args: {\n component: component,\n callback: callback,\n contextid: contextid,\n args: formattedparams\n }\n }])[0];\n };\n\n return /** @alias module:core/fragment */{\n /**\n * Appends HTML and JavaScript fragments to specified nodes.\n * Callbacks called by this AMD module are responsible for doing the appropriate security checks\n * to access the information that is returned. This only does minimal validation on the context.\n *\n * @method fragmentAppend\n * @param {string} component Component where callback is located.\n * @param {string} callback Callback function name.\n * @param {integer} contextid Context ID of the fragment.\n * @param {object} params Parameters for the callback.\n * @return {Deferred} new promise that is resolved with the html and js.\n */\n loadFragment: function(component, callback, contextid, params) {\n var promise = $.Deferred();\n loadFragment(component, callback, contextid, params).then(function(data) {\n var jsNodes = $(data.javascript);\n var allScript = '';\n jsNodes.each(function(index, scriptNode) {\n scriptNode = $(scriptNode);\n var tagName = scriptNode.prop('tagName');\n if (tagName && (tagName.toLowerCase() == 'script')) {\n if (scriptNode.attr('src')) {\n // We only reload the script if it was not loaded already.\n var exists = false;\n $('script').each(function(index, s) {\n if ($(s).attr('src') == scriptNode.attr('src')) {\n exists = true;\n }\n return !exists;\n });\n if (!exists) {\n allScript += ' { ';\n allScript += ' node = document.createElement(\"script\"); ';\n allScript += ' node.type = \"text/javascript\"; ';\n allScript += ' node.src = decodeURI(\"' + encodeURI(scriptNode.attr('src')) + '\"); ';\n allScript += ' document.getElementsByTagName(\"head\")[0].appendChild(node); ';\n allScript += ' } ';\n }\n } else {\n allScript += ' ' + scriptNode.text();\n }\n }\n });\n promise.resolve(data.html, allScript);\n return;\n }).fail(function(ex) {\n promise.reject(ex);\n });\n return promise.promise();\n }\n };\n});\n"],"file":"fragment.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/fragment.js"],"names":["define","$","ajax","loadFragment","component","callback","contextid","params","formattedparams","index","push","name","value","call","methodname","args","processCollectedJavascript","js","jsNodes","allScript","each","scriptNode","tagName","prop","toLowerCase","attr","exists","s","encodeURI","text","promise","Deferred","then","data","resolve","html","javascript","fail","ex","reject"],"mappings":"AAyBAA,OAAM,iBAAC,CAAC,QAAD,CAAW,WAAX,CAAD,CAA0B,SAASC,CAAT,CAAYC,CAAZ,CAAkB,IAY1CC,CAAAA,CAAY,CAAG,QAAfA,CAAAA,YAAe,CAASC,CAAT,CAAoBC,CAApB,CAA8BC,CAA9B,CAAyCC,CAAzC,CAAiD,CAEhE,GAAIC,CAAAA,CAAe,CAAG,EAAtB,CACA,IAAK,GAAIC,CAAAA,CAAT,GAAkBF,CAAAA,CAAlB,CAA0B,CACtBC,CAAe,CAACE,IAAhB,CAAqB,CACjBC,IAAI,CAAEF,CADW,CAEjBG,KAAK,CAAEL,CAAM,CAACE,CAAD,CAFI,CAArB,CAIH,CAED,MAAOP,CAAAA,CAAI,CAACW,IAAL,CAAU,CAAC,CACdC,UAAU,CAAE,mBADE,CAEdC,IAAI,CAAE,CACFX,SAAS,CAAEA,CADT,CAEFC,QAAQ,CAAEA,CAFR,CAGFC,SAAS,CAAEA,CAHT,CAIFS,IAAI,CAAEP,CAJJ,CAFQ,CAAD,CAAV,EAQH,CARG,CASV,CA/B6C,CAuC1CQ,CAA0B,CAAG,QAA7BA,CAAAA,0BAA6B,CAASC,CAAT,CAAa,IACtCC,CAAAA,CAAO,CAAGjB,CAAC,CAACgB,CAAD,CAD2B,CAEtCE,CAAS,CAAG,EAF0B,CAG1CD,CAAO,CAACE,IAAR,CAAa,SAASX,CAAT,CAAgBY,CAAhB,CAA4B,CACrCA,CAAU,CAAGpB,CAAC,CAACoB,CAAD,CAAd,CACA,GAAIC,CAAAA,CAAO,CAAGD,CAAU,CAACE,IAAX,CAAgB,SAAhB,CAAd,CACA,GAAID,CAAO,EAA8B,QAAzB,EAAAA,CAAO,CAACE,WAAR,EAAhB,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AAA,CAAO,CAACA,OAAR,EACV,CArBoC,CA6BrCd,0BAA0B,CAAE,oCAASC,CAAT,CAAa,CACrC,MAAOD,CAAAA,CAA0B,CAACC,CAAD,CACpC,CA/BoC,CAiC5C,CAxGK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A way to call HTML fragments to be inserted as required via JavaScript.\n *\n * @module core/fragment\n * @class fragment\n * @package core\n * @copyright 2016 Adrian Greeve \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 3.1\n */\ndefine(['jquery', 'core/ajax'], function($, ajax) {\n\n /**\n * Loads an HTML fragment through a callback.\n *\n * @method loadFragment\n * @param {string} component Component where callback is located.\n * @param {string} callback Callback function name.\n * @param {integer} contextid Context ID of the fragment.\n * @param {object} params Parameters for the callback.\n * @return {Promise} JQuery promise object resolved when the fragment has been loaded.\n */\n var loadFragment = function(component, callback, contextid, params) {\n // Change params into required webservice format.\n var formattedparams = [];\n for (var index in params) {\n formattedparams.push({\n name: index,\n value: params[index]\n });\n }\n\n return ajax.call([{\n methodname: 'core_get_fragment',\n args: {\n component: component,\n callback: callback,\n contextid: contextid,\n args: formattedparams\n }\n }])[0];\n };\n\n /**\n * Converts the JS that was received from collecting JS requirements on the $PAGE so it can be added to the existing page\n *\n * @param {string} js\n * @return {string}\n */\n var processCollectedJavascript = function(js) {\n var jsNodes = $(js);\n var allScript = '';\n jsNodes.each(function(index, scriptNode) {\n scriptNode = $(scriptNode);\n var tagName = scriptNode.prop('tagName');\n if (tagName && (tagName.toLowerCase() == 'script')) {\n if (scriptNode.attr('src')) {\n // We only reload the script if it was not loaded already.\n var exists = false;\n $('script').each(function(index, s) {\n if ($(s).attr('src') == scriptNode.attr('src')) {\n exists = true;\n }\n return !exists;\n });\n if (!exists) {\n allScript += ' { ';\n allScript += ' node = document.createElement(\"script\"); ';\n allScript += ' node.type = \"text/javascript\"; ';\n allScript += ' node.src = decodeURI(\"' + encodeURI(scriptNode.attr('src')) + '\"); ';\n allScript += ' document.getElementsByTagName(\"head\")[0].appendChild(node); ';\n allScript += ' } ';\n }\n } else {\n allScript += ' ' + scriptNode.text();\n }\n }\n });\n return allScript;\n };\n\n return /** @alias module:core/fragment */{\n /**\n * Appends HTML and JavaScript fragments to specified nodes.\n * Callbacks called by this AMD module are responsible for doing the appropriate security checks\n * to access the information that is returned. This only does minimal validation on the context.\n *\n * @method fragmentAppend\n * @param {string} component Component where callback is located.\n * @param {string} callback Callback function name.\n * @param {integer} contextid Context ID of the fragment.\n * @param {object} params Parameters for the callback.\n * @return {Deferred} new promise that is resolved with the html and js.\n */\n loadFragment: function(component, callback, contextid, params) {\n var promise = $.Deferred();\n loadFragment(component, callback, contextid, params).then(function(data) {\n promise.resolve(data.html, processCollectedJavascript(data.javascript));\n }).fail(function(ex) {\n promise.reject(ex);\n });\n return promise.promise();\n },\n\n /**\n * Converts the JS that was received from collecting JS requirements on the $PAGE so it can be added to the existing page\n *\n * @param {string} js\n * @return {string}\n */\n processCollectedJavascript: function(js) {\n return processCollectedJavascript(js);\n }\n };\n});\n"],"file":"fragment.min.js"} \ No newline at end of file diff --git a/lib/amd/build/modal.min.js b/lib/amd/build/modal.min.js index dfa48eac577..39a63e403d5 100644 --- a/lib/amd/build/modal.min.js +++ b/lib/amd/build/modal.min.js @@ -1,2 +1,2 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("core/modal",["jquery","core/templates","core/notification","core/key_codes","core/custom_interaction_events","core/modal_backdrop","core/event","core/modal_events","core/local/aria/focuslock","core/pending","core/aria","core/fullscreen"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m={CONTAINER:"[data-region=\"modal-container\"]",MODAL:"[data-region=\"modal\"]",HEADER:"[data-region=\"header\"]",TITLE:"[data-region=\"title\"]",BODY:"[data-region=\"body\"]",FOOTER:"[data-region=\"footer\"]",HIDE:"[data-action=\"hide\"]",DIALOG:"[role=dialog]",FORM:"form",MENU_BAR:"[role=menubar]",HAS_Z_INDEX:".moodle-has-zindex",CAN_RECEIVE_FOCUS:"input:not([type=\"hidden\"]), a[href], button, textarea, select, [tabindex]"},n={LOADING:"core/loading",BACKDROP:"core/modal_backdrop"},o,p=0,q=function(b){this.root=a(b);this.modal=this.root.find(m.MODAL);this.header=this.modal.find(m.HEADER);this.headerPromise=a.Deferred();this.title=this.header.find(m.TITLE);this.titlePromise=a.Deferred();this.body=this.modal.find(m.BODY);this.bodyPromise=a.Deferred();this.footer=this.modal.find(m.FOOTER);this.footerPromise=a.Deferred();this.hiddenSiblings=[];this.isAttached=!1;this.bodyJS=null;this.footerJS=null;this.modalCount=p++;this.attachmentPoint=document.createElement("div");document.body.append(this.attachmentPoint);if(!this.root.is(m.CONTAINER)){c.exception({message:"Element is not a modal container"})}if(!this.modal.length){c.exception({message:"Container does not contain a modal"})}if(!this.header.length){c.exception({message:"Modal is missing a header region"})}if(!this.title.length){c.exception({message:"Modal header is missing a title region"})}if(!this.body.length){c.exception({message:"Modal is missing a body region"})}if(!this.footer.length){c.exception({message:"Modal is missing a footer region"})}this.registerEventListeners()};q.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root);if(this.isAttached){return}i.trapFocus(this.root[0]);if(this.bodyJS){b.runTemplateJS(this.bodyJS);this.bodyJS=null}if(this.footerJS){b.runTemplateJS(this.footerJS);this.footerJS=null}this.isAttached=!0};q.prototype.countOtherVisibleModals=function(){var b=0;a("body").find(m.CONTAINER).each(function(c,d){d=a(d);if(!this.root.is(d)&&d.hasClass("show")){b++}}.bind(this));return b};q.prototype.getBackdrop=function(){if(!o){o=b.render(n.BACKDROP,{}).then(function(b){var c=a(b);return new f(c)}).fail(c.exception)}return o};q.prototype.getRoot=function(){return this.root};q.prototype.getModal=function(){return this.modal};q.prototype.getTitle=function(){return this.title};q.prototype.getBody=function(){return this.body};q.prototype.getFooter=function(){return this.footer};q.prototype.getTitlePromise=function(){return this.titlePromise};q.prototype.getBodyPromise=function(){return this.bodyPromise};q.prototype.getFooterPromise=function(){return this.footerPromise};q.prototype.getModalCount=function(){return this.modalCount};q.prototype.setTitle=function(b){var d=this.getTitle();this.titlePromise=a.Deferred();this.asyncSet(b,d.html.bind(d)).then(function(){this.titlePromise.resolve(d)}.bind(this)).catch(c.exception)};q.prototype.setBody=function(d){this.bodyPromise=a.Deferred();var e=this.getBody();if("string"==typeof d){e.html(d);g.notifyFilterContentUpdated(e);this.getRoot().trigger(h.bodyRendered,this);this.bodyPromise.resolve(e)}else{var f="amd-modal-js-pending-id-"+this.getModalCount();M.util.js_pending(f);var i=null;e.css("overflow","hidden");d=a.when(d);if("pending"==d.state()){var j=e.innerHeight();if(100>j){j=100}e.animate({height:j+"px"},150);e.html("");i=b.render(n.LOADING,{}).then(function(b){var c=a(b).hide();e.html(c);c.fadeIn(150);return a.when(c.promise(),d)}).then(function(a){return a.fadeOut(100).promise()}).then(function(){return d})}else{i=d}i.then(function(a,c){var d=null;if(this.isVisible()){e.css("opacity",0);var f=e.innerHeight();e.html(a);e.css("height","");var g=e.innerHeight();e.css("height",f+"px");d=e.animate({height:g+"px",opacity:1},{duration:150,queue:!1}).promise()}else{e.html(a)}if(c){if(this.isAttached){b.runTemplateJS(c)}else{this.bodyJS=c}}return d}.bind(this)).then(function(a){g.notifyFilterContentUpdated(e);this.getRoot().trigger(h.bodyRendered,this);return a}.bind(this)).then(function(){this.bodyPromise.resolve(e)}.bind(this)).fail(c.exception).always(function(){e.css("height","");e.css("overflow","");e.css("opacity","");M.util.js_complete(f)}).fail(c.exception)}};q.prototype.setFooter=function(d){this.showFooter();this.footerPromise=a.Deferred();var e=this.getFooter();if("string"==typeof d){e.html(d);this.footerPromise.resolve(e)}else{b.render(n.LOADING,{}).then(function(a){e.html(a);return d}).then(function(a,c){e.html(a);if(c){if(this.isAttached){b.runTemplateJS(c)}else{this.footerJS=c}}return e}.bind(this)).then(function(a){this.footerPromise.resolve(a)}.bind(this)).catch(c.exception)}};q.prototype.hasFooterContent=function(){return this.getFooter().children().length?!0:!1};q.prototype.hideFooter=function(){this.getFooter().addClass("hidden")};q.prototype.showFooter=function(){this.getFooter().removeClass("hidden")};q.prototype.setLarge=function(){if(this.isLarge()){return}this.getModal().addClass("modal-lg")};q.prototype.isLarge=function(){return this.getModal().hasClass("modal-lg")};q.prototype.setSmall=function(){if(this.isSmall()){return}this.getModal().removeClass("modal-lg")};q.prototype.isSmall=function(){return!this.getModal().hasClass("modal-lg")};q.prototype.setScrollable=function(a){if(!a){this.getModal()[0].classList.remove("modal-dialog-scrollable");return}this.getModal()[0].classList.add("modal-dialog-scrollable")};q.prototype.calculateZIndex=function(){var b=a(m.DIALOG+", "+m.MENU_BAR+", "+m.HAS_Z_INDEX),c=parseInt(this.root.css("z-index"));b.each(function(b,d){d=a(d);var e=d.css("z-index")?parseInt(d.css("z-index")):0;if(e>c){c=e}});return c};q.prototype.isVisible=function(){return this.root.hasClass("show")};q.prototype.hasFocus=function(){var b=a(document.activeElement);return this.root.is(b)||this.root.has(b).length};q.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")};q.prototype.getAttachmentPoint=function(){return a(l.getElement()||this.attachmentPoint)};q.prototype.show=function(){if(this.isVisible()){return a.Deferred().resolve()}var b=new j("core/modal:show");if(this.hasFooterContent()){this.showFooter()}else{this.hideFooter()}this.attachToDOM();return this.getBackdrop().then(function(b){var c=this.calculateZIndex(),d=c+2;this.root.css("z-index",d);b.setZIndex(d-1);b.show();this.root.removeClass("hide").addClass("show");this.accessibilityShow();this.getModal().focus();a("body").addClass("modal-open");this.root.trigger(h.shown,this)}.bind(this)).then(b.resolve)};q.prototype.hideIfNotForm=function(){var a=this.modal.find(m.FORM);if(0==a.length){this.hide()}};q.prototype.hide=function(){this.getBackdrop().done(function(b){i.untrapFocus();if(!this.countOtherVisibleModals()){b.hide();a("body").removeClass("modal-open")}var c=parseInt(this.root.css("z-index"));this.root.css("z-index","");b.setZIndex(c-3);this.accessibilityHide();if(this.hasTransitions()){this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this))}else{this.getRoot().removeClass("show").addClass("hide")}if(a(document.body).find(this.getRoot()).length){a(document.body).append(this.getRoot())}this.root.trigger(h.hidden,this)}.bind(this))};q.prototype.destroy=function(){this.hide();this.root.remove();this.root.trigger(h.destroyed,this);this.attachmentPoint.remove()};q.prototype.accessibilityShow=function(){k.unhide(this.root.get());k.hideSiblings(this.root.get()[0])};q.prototype.accessibilityHide=function(){k.unhideSiblings(this.root.get()[0]);k.hide(this.root.get())};q.prototype.registerEventListeners=function(){this.getRoot().on("keydown",function(a){if(!this.isVisible()){return}if(a.keyCode==d.escape){if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this));this.getRoot().click(function(b){if(!a(b.target).closest(m.MODAL).length){if(a(b.target).closest(m.CONTAINER).length){var c=a.Event(h.outsideClick);this.getRoot().trigger(c,this);if(!c.isDefaultPrevented()){this.hideIfNotForm()}}}}.bind(this));e.define(this.getModal(),[e.events.activate]);this.getModal().on(e.events.activate,m.HIDE,function(a,b){this.hide();b.originalEvent.preventDefault()}.bind(this))};q.prototype.registerCloseOnCancel=function(){this.getModal().on(e.events.activate,this.getActionSelector("cancel"),function(b,c){var d=a.Event(h.cancel);this.getRoot().trigger(d,this);if(!d.isDefaultPrevented()){c.originalEvent.preventDefault();if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this))};q.prototype.registerCloseOnSave=function(){this.getModal().on(e.events.activate,this.getActionSelector("save"),function(b,c){var d=a.Event(h.save);this.getRoot().trigger(d,this);if(!d.isDefaultPrevented()){c.originalEvent.preventDefault();if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this))};q.prototype.asyncSet=function(b,d){var e=b;if("object"!==_typeof(b)||!b.hasOwnProperty("then")){e=a.Deferred();e.resolve(b)}e.then(function(a){d(a)}).fail(c.exception);return e};q.prototype.setButtonText=function(a,b){var c=this.getFooter().find(this.getActionSelector(a));if(!c){throw new Error("Unable to find the '"+a+"' button")}return this.asyncSet(b,c.text.bind(c))};q.prototype.getActionSelector=function(a){return"[data-action='"+a+"']"};q.prototype.setRemoveOnClose=function(a){this.removeOnClose=a};return q}); +function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("core/modal",["jquery","core/templates","core/notification","core/key_codes","core/custom_interaction_events","core/modal_backdrop","core/event","core/modal_events","core/local/aria/focuslock","core/pending","core/aria","core/fullscreen"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m={CONTAINER:"[data-region=\"modal-container\"]",MODAL:"[data-region=\"modal\"]",HEADER:"[data-region=\"header\"]",TITLE:"[data-region=\"title\"]",BODY:"[data-region=\"body\"]",FOOTER:"[data-region=\"footer\"]",HIDE:"[data-action=\"hide\"]",DIALOG:"[role=dialog]",FORM:"form",MENU_BAR:"[role=menubar]",HAS_Z_INDEX:".moodle-has-zindex",CAN_RECEIVE_FOCUS:"input:not([type=\"hidden\"]), a[href], button, textarea, select, [tabindex]"},n={LOADING:"core/loading",BACKDROP:"core/modal_backdrop"},o,p=0,q=function(b){this.root=a(b);this.modal=this.root.find(m.MODAL);this.header=this.modal.find(m.HEADER);this.headerPromise=a.Deferred();this.title=this.header.find(m.TITLE);this.titlePromise=a.Deferred();this.body=this.modal.find(m.BODY);this.bodyPromise=a.Deferred();this.footer=this.modal.find(m.FOOTER);this.footerPromise=a.Deferred();this.hiddenSiblings=[];this.isAttached=!1;this.bodyJS=null;this.footerJS=null;this.modalCount=p++;this.attachmentPoint=document.createElement("div");document.body.append(this.attachmentPoint);if(!this.root.is(m.CONTAINER)){c.exception({message:"Element is not a modal container"})}if(!this.modal.length){c.exception({message:"Container does not contain a modal"})}if(!this.header.length){c.exception({message:"Modal is missing a header region"})}if(!this.title.length){c.exception({message:"Modal header is missing a title region"})}if(!this.body.length){c.exception({message:"Modal is missing a body region"})}if(!this.footer.length){c.exception({message:"Modal is missing a footer region"})}this.registerEventListeners()};q.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root);if(this.isAttached){return}i.trapFocus(this.root[0]);if(this.bodyJS){b.runTemplateJS(this.bodyJS);this.bodyJS=null}if(this.footerJS){b.runTemplateJS(this.footerJS);this.footerJS=null}this.isAttached=!0};q.prototype.countOtherVisibleModals=function(){var b=0;a("body").find(m.CONTAINER).each(function(c,d){d=a(d);if(!this.root.is(d)&&d.hasClass("show")){b++}}.bind(this));return b};q.prototype.getBackdrop=function(){if(!o){o=b.render(n.BACKDROP,{}).then(function(b){var c=a(b);return new f(c)}).fail(c.exception)}return o};q.prototype.getRoot=function(){return this.root};q.prototype.getModal=function(){return this.modal};q.prototype.getTitle=function(){return this.title};q.prototype.getBody=function(){return this.body};q.prototype.getFooter=function(){return this.footer};q.prototype.getTitlePromise=function(){return this.titlePromise};q.prototype.getBodyPromise=function(){return this.bodyPromise};q.prototype.getFooterPromise=function(){return this.footerPromise};q.prototype.getModalCount=function(){return this.modalCount};q.prototype.setTitle=function(b){var d=this.getTitle();this.titlePromise=a.Deferred();this.asyncSet(b,d.html.bind(d)).then(function(){this.titlePromise.resolve(d)}.bind(this)).catch(c.exception)};q.prototype.setBody=function(d){this.bodyPromise=a.Deferred();var e=this.getBody();if("string"==typeof d){e.html(d);g.notifyFilterContentUpdated(e);this.getRoot().trigger(h.bodyRendered,this);this.bodyPromise.resolve(e)}else{var f="amd-modal-js-pending-id-"+this.getModalCount();M.util.js_pending(f);var i=null;e.css("overflow","hidden");d=a.when(d);if("pending"==d.state()){var j=e.innerHeight();if(100>j){j=100}e.animate({height:j+"px"},150);e.html("");i=b.render(n.LOADING,{}).then(function(b){var c=a(b).hide();e.html(c);c.fadeIn(150);return a.when(c.promise(),d)}).then(function(a){return a.fadeOut(100).promise()}).then(function(){return d})}else{i=d}i.then(function(a,c){var d=null;if(this.isVisible()){e.css("opacity",0);var f=e.innerHeight();e.html(a);e.css("height","");var g=e.innerHeight();e.css("height",f+"px");d=e.animate({height:g+"px",opacity:1},{duration:150,queue:!1}).promise()}else{e.html(a)}if(c){if(this.isAttached){b.runTemplateJS(c)}else{this.bodyJS=c}}return d}.bind(this)).then(function(a){g.notifyFilterContentUpdated(e);this.getRoot().trigger(h.bodyRendered,this);return a}.bind(this)).then(function(){this.bodyPromise.resolve(e)}.bind(this)).fail(c.exception).always(function(){e.css("height","");e.css("overflow","");e.css("opacity","");M.util.js_complete(f)}).fail(c.exception)}};q.prototype.setBodyContent=function(b){var c=this;return b.then(function(b){var d=b.html,e=b.js;return c.setBody(a.when(d,e))})};q.prototype.setFooter=function(d){this.showFooter();this.footerPromise=a.Deferred();var e=this.getFooter();if("string"==typeof d){e.html(d);this.footerPromise.resolve(e)}else{b.render(n.LOADING,{}).then(function(a){e.html(a);return d}).then(function(a,c){e.html(a);if(c){if(this.isAttached){b.runTemplateJS(c)}else{this.footerJS=c}}return e}.bind(this)).then(function(a){this.footerPromise.resolve(a)}.bind(this)).catch(c.exception)}};q.prototype.hasFooterContent=function(){return this.getFooter().children().length?!0:!1};q.prototype.hideFooter=function(){this.getFooter().addClass("hidden")};q.prototype.showFooter=function(){this.getFooter().removeClass("hidden")};q.prototype.setLarge=function(){if(this.isLarge()){return}this.getModal().addClass("modal-lg")};q.prototype.isLarge=function(){return this.getModal().hasClass("modal-lg")};q.prototype.setSmall=function(){if(this.isSmall()){return}this.getModal().removeClass("modal-lg")};q.prototype.isSmall=function(){return!this.getModal().hasClass("modal-lg")};q.prototype.setScrollable=function(a){if(!a){this.getModal()[0].classList.remove("modal-dialog-scrollable");return}this.getModal()[0].classList.add("modal-dialog-scrollable")};q.prototype.calculateZIndex=function(){var b=a(m.DIALOG+", "+m.MENU_BAR+", "+m.HAS_Z_INDEX),c=parseInt(this.root.css("z-index"));b.each(function(b,d){d=a(d);var e=d.css("z-index")?parseInt(d.css("z-index")):0;if(e>c){c=e}});return c};q.prototype.isVisible=function(){return this.root.hasClass("show")};q.prototype.hasFocus=function(){var b=a(document.activeElement);return this.root.is(b)||this.root.has(b).length};q.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")};q.prototype.getAttachmentPoint=function(){return a(l.getElement()||this.attachmentPoint)};q.prototype.show=function(){if(this.isVisible()){return a.Deferred().resolve()}var b=new j("core/modal:show");if(this.hasFooterContent()){this.showFooter()}else{this.hideFooter()}this.attachToDOM();return this.getBackdrop().then(function(b){var c=this.calculateZIndex(),d=c+2;this.root.css("z-index",d);b.setZIndex(d-1);b.show();this.root.removeClass("hide").addClass("show");this.accessibilityShow();this.getModal().focus();a("body").addClass("modal-open");this.root.trigger(h.shown,this)}.bind(this)).then(b.resolve)};q.prototype.hideIfNotForm=function(){var a=this.modal.find(m.FORM);if(0==a.length){this.hide()}};q.prototype.hide=function(){this.getBackdrop().done(function(b){i.untrapFocus();if(!this.countOtherVisibleModals()){b.hide();a("body").removeClass("modal-open")}var c=parseInt(this.root.css("z-index"));this.root.css("z-index","");b.setZIndex(c-3);this.accessibilityHide();if(this.hasTransitions()){this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this))}else{this.getRoot().removeClass("show").addClass("hide")}if(a(document.body).find(this.getRoot()).length){a(document.body).append(this.getRoot())}this.root.trigger(h.hidden,this)}.bind(this))};q.prototype.destroy=function(){this.hide();this.root.remove();this.root.trigger(h.destroyed,this);this.attachmentPoint.remove()};q.prototype.accessibilityShow=function(){k.unhide(this.root.get());k.hideSiblings(this.root.get()[0])};q.prototype.accessibilityHide=function(){k.unhideSiblings(this.root.get()[0]);k.hide(this.root.get())};q.prototype.registerEventListeners=function(){this.getRoot().on("keydown",function(a){if(!this.isVisible()){return}if(a.keyCode==d.escape){if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this));this.getRoot().click(function(b){if(!a(b.target).closest(m.MODAL).length){if(a(b.target).closest(m.CONTAINER).length){var c=a.Event(h.outsideClick);this.getRoot().trigger(c,this);if(!c.isDefaultPrevented()){this.hideIfNotForm()}}}}.bind(this));e.define(this.getModal(),[e.events.activate]);this.getModal().on(e.events.activate,m.HIDE,function(a,b){this.hide();b.originalEvent.preventDefault()}.bind(this))};q.prototype.registerCloseOnCancel=function(){this.getModal().on(e.events.activate,this.getActionSelector("cancel"),function(b,c){var d=a.Event(h.cancel);this.getRoot().trigger(d,this);if(!d.isDefaultPrevented()){c.originalEvent.preventDefault();if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this))};q.prototype.registerCloseOnSave=function(){this.getModal().on(e.events.activate,this.getActionSelector("save"),function(b,c){var d=a.Event(h.save);this.getRoot().trigger(d,this);if(!d.isDefaultPrevented()){c.originalEvent.preventDefault();if(this.removeOnClose){this.destroy()}else{this.hide()}}}.bind(this))};q.prototype.asyncSet=function(b,d){var e=b;if("object"!==_typeof(b)||!b.hasOwnProperty("then")){e=a.Deferred();e.resolve(b)}e.then(function(a){d(a)}).fail(c.exception);return e};q.prototype.setButtonText=function(a,b){var c=this.getFooter().find(this.getActionSelector(a));if(!c){throw new Error("Unable to find the '"+a+"' button")}return this.asyncSet(b,c.text.bind(c))};q.prototype.getActionSelector=function(a){return"[data-action='"+a+"']"};q.prototype.setRemoveOnClose=function(a){this.removeOnClose=a};return q}); //# sourceMappingURL=modal.min.js.map diff --git a/lib/amd/build/modal.min.js.map b/lib/amd/build/modal.min.js.map index 0e682d0482c..d4e3b8a85a5 100644 --- a/lib/amd/build/modal.min.js.map +++ b/lib/amd/build/modal.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/modal.js"],"names":["define","$","Templates","Notification","KeyCodes","CustomEvents","ModalBackdrop","Event","ModalEvents","FocusLock","Pending","Aria","Fullscreen","SELECTORS","CONTAINER","MODAL","HEADER","TITLE","BODY","FOOTER","HIDE","DIALOG","FORM","MENU_BAR","HAS_Z_INDEX","CAN_RECEIVE_FOCUS","TEMPLATES","LOADING","BACKDROP","backdropPromise","modalCounter","Modal","root","modal","find","header","headerPromise","Deferred","title","titlePromise","body","bodyPromise","footer","footerPromise","hiddenSiblings","isAttached","bodyJS","footerJS","modalCount","attachmentPoint","document","createElement","append","is","exception","message","length","registerEventListeners","prototype","attachToDOM","getAttachmentPoint","trapFocus","runTemplateJS","countOtherVisibleModals","count","each","index","element","hasClass","bind","getBackdrop","render","then","html","fail","getRoot","getModal","getTitle","getBody","getFooter","getTitlePromise","getBodyPromise","getFooterPromise","getModalCount","setTitle","value","asyncSet","resolve","catch","setBody","notifyFilterContentUpdated","trigger","bodyRendered","jsPendingId","M","util","js_pending","contentPromise","css","when","state","height","innerHeight","animate","loadingIcon","hide","fadeIn","promise","fadeOut","js","result","isVisible","currentHeight","newHeight","opacity","duration","queue","always","js_complete","setFooter","showFooter","hasFooterContent","children","hideFooter","addClass","removeClass","setLarge","isLarge","setSmall","isSmall","setScrollable","classList","remove","add","calculateZIndex","items","zIndex","parseInt","item","itemZIndex","hasFocus","target","activeElement","has","hasTransitions","getElement","show","pendingPromise","backdrop","currentIndex","newIndex","setZIndex","accessibilityShow","focus","shown","hideIfNotForm","formElement","done","untrapFocus","accessibilityHide","one","hidden","destroy","destroyed","unhide","get","hideSiblings","unhideSiblings","on","e","keyCode","escape","removeOnClose","click","closest","outsideClickEvent","outsideClick","isDefaultPrevented","events","activate","data","originalEvent","preventDefault","registerCloseOnCancel","getActionSelector","cancelEvent","cancel","registerCloseOnSave","saveEvent","save","setFunction","p","hasOwnProperty","content","setButtonText","action","button","Error","text","setRemoveOnClose"],"mappings":"mSAwBAA,OAAM,cAAC,CACH,QADG,CAEH,gBAFG,CAGH,mBAHG,CAIH,gBAJG,CAKH,gCALG,CAMH,qBANG,CAOH,YAPG,CAQH,mBARG,CASH,2BATG,CAUH,cAVG,CAWH,WAXG,CAYH,iBAZG,CAAD,CAaH,SACCC,CADD,CAECC,CAFD,CAGCC,CAHD,CAICC,CAJD,CAKCC,CALD,CAMCC,CAND,CAOCC,CAPD,CAQCC,CARD,CASCC,CATD,CAUCC,CAVD,CAWCC,CAXD,CAYCC,CAZD,CAaD,IAEMC,CAAAA,CAAS,CAAG,CACZC,SAAS,CAAE,mCADC,CAEZC,KAAK,CAAE,yBAFK,CAGZC,MAAM,CAAE,0BAHI,CAIZC,KAAK,CAAE,yBAJK,CAKZC,IAAI,CAAE,wBALM,CAMZC,MAAM,CAAE,0BANI,CAOZC,IAAI,CAAE,wBAPM,CAQZC,MAAM,CAAE,eARI,CASZC,IAAI,CAAE,MATM,CAUZC,QAAQ,CAAE,gBAVE,CAWZC,WAAW,CAAE,oBAXD,CAYZC,iBAAiB,CAAE,6EAZP,CAFlB,CAiBMC,CAAS,CAAG,CACZC,OAAO,CAAE,cADG,CAEZC,QAAQ,CAAE,qBAFE,CAjBlB,CAyBMC,CAzBN,CA+BMC,CAAY,CAAG,CA/BrB,CAsCMC,CAAK,CAAG,SAASC,CAAT,CAAe,CACvB,KAAKA,IAAL,CAAY/B,CAAC,CAAC+B,CAAD,CAAb,CACA,KAAKC,KAAL,CAAa,KAAKD,IAAL,CAAUE,IAAV,CAAerB,CAAS,CAACE,KAAzB,CAAb,CACA,KAAKoB,MAAL,CAAc,KAAKF,KAAL,CAAWC,IAAX,CAAgBrB,CAAS,CAACG,MAA1B,CAAd,CACA,KAAKoB,aAAL,CAAqBnC,CAAC,CAACoC,Q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WAAOA,CAAP,GAA6B,CAACA,CAAK,CAAC2G,cAAN,CAAqB,MAArB,CAAlC,CAAgE,CAC5DD,CAAC,CAAG9L,CAAC,CAACoC,QAAF,EAAJ,CACA0J,CAAC,CAACxG,OAAF,CAAUF,CAAV,CACH,CAED0G,CAAC,CAACvH,IAAF,CAAO,SAASyH,CAAT,CAAkB,CACrBH,CAAW,CAACG,CAAD,CAGd,CAJD,EAKCvH,IALD,CAKMvE,CAAY,CAACmD,SALnB,EAOA,MAAOyI,CAAAA,CACV,CAfD,CA2BAhK,CAAK,CAAC2B,SAAN,CAAgBwI,aAAhB,CAAgC,SAASC,CAAT,CAAiB9G,CAAjB,CAAwB,CACpD,GAAM+G,CAAAA,CAAM,CAAG,KAAKrH,SAAL,GAAiB7C,IAAjB,CAAsB,KAAKsJ,iBAAL,CAAuBW,CAAvB,CAAtB,CAAf,CAEA,GAAI,CAACC,CAAL,CAAa,CACT,KAAM,IAAIC,CAAAA,KAAJ,CAAU,uBAAyBF,CAAzB,CAAkC,UAA5C,CACT,CAED,MAAO,MAAK7G,QAAL,CAAcD,CAAd,CAAqB+G,CAAM,CAACE,IAAP,CAAYjI,IAAZ,CAAiB+H,CAAjB,CAArB,CACV,CARD,CAgBArK,CAAK,CAAC2B,SAAN,CAAgB8H,iBAAhB,CAAoC,SAASW,CAAT,CAAiB,CACjD,MAAO,iBAAmBA,CAAnB,CAA4B,IACtC,CAFD,CASApK,CAAK,CAAC2B,SAAN,CAAgB6I,gBAAhB,CAAmC,SAASnE,CAAT,CAAiB,CAChD,KAAKwC,aAAL,CAAqBxC,CACxB,CAFD,CAIA,MAAOrG,CAAAA,CACV,CA35BK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Contain the logic for modals.\n *\n * @module core/modal\n * @class modal\n * @package core\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/templates',\n 'core/notification',\n 'core/key_codes',\n 'core/custom_interaction_events',\n 'core/modal_backdrop',\n 'core/event',\n 'core/modal_events',\n 'core/local/aria/focuslock',\n 'core/pending',\n 'core/aria',\n 'core/fullscreen'\n], function(\n $,\n Templates,\n Notification,\n KeyCodes,\n CustomEvents,\n ModalBackdrop,\n Event,\n ModalEvents,\n FocusLock,\n Pending,\n Aria,\n Fullscreen\n) {\n\n var SELECTORS = {\n CONTAINER: '[data-region=\"modal-container\"]',\n MODAL: '[data-region=\"modal\"]',\n HEADER: '[data-region=\"header\"]',\n TITLE: '[data-region=\"title\"]',\n BODY: '[data-region=\"body\"]',\n FOOTER: '[data-region=\"footer\"]',\n HIDE: '[data-action=\"hide\"]',\n DIALOG: '[role=dialog]',\n FORM: 'form',\n MENU_BAR: '[role=menubar]',\n HAS_Z_INDEX: '.moodle-has-zindex',\n CAN_RECEIVE_FOCUS: 'input:not([type=\"hidden\"]), a[href], button, textarea, select, [tabindex]',\n };\n\n var TEMPLATES = {\n LOADING: 'core/loading',\n BACKDROP: 'core/modal_backdrop',\n };\n\n /**\n * Module singleton for the backdrop to be reused by all Modal instances.\n */\n var backdropPromise;\n\n /**\n * A counter that gets incremented for each modal created. This can be\n * used to generate unique values for the modals.\n */\n var modalCounter = 0;\n\n /**\n * Constructor for the Modal.\n *\n * @param {object} root The root jQuery element for the modal\n */\n var Modal = function(root) {\n this.root = $(root);\n this.modal = this.root.find(SELECTORS.MODAL);\n this.header = this.modal.find(SELECTORS.HEADER);\n this.headerPromise = $.Deferred();\n this.title = this.header.find(SELECTORS.TITLE);\n this.titlePromise = $.Deferred();\n this.body = this.modal.find(SELECTORS.BODY);\n this.bodyPromise = $.Deferred();\n this.footer = this.modal.find(SELECTORS.FOOTER);\n this.footerPromise = $.Deferred();\n this.hiddenSiblings = [];\n this.isAttached = false;\n this.bodyJS = null;\n this.footerJS = null;\n this.modalCount = modalCounter++;\n this.attachmentPoint = document.createElement('div');\n document.body.append(this.attachmentPoint);\n\n if (!this.root.is(SELECTORS.CONTAINER)) {\n Notification.exception({message: 'Element is not a modal container'});\n }\n\n if (!this.modal.length) {\n Notification.exception({message: 'Container does not contain a modal'});\n }\n\n if (!this.header.length) {\n Notification.exception({message: 'Modal is missing a header region'});\n }\n\n if (!this.title.length) {\n Notification.exception({message: 'Modal header is missing a title region'});\n }\n\n if (!this.body.length) {\n Notification.exception({message: 'Modal is missing a body region'});\n }\n\n if (!this.footer.length) {\n Notification.exception({message: 'Modal is missing a footer region'});\n }\n\n this.registerEventListeners();\n };\n\n /**\n * Attach the modal to the correct part of the page.\n *\n * If it hasn't already been added it runs any\n * javascript that has been cached until now.\n *\n * @method attachToDOM\n */\n Modal.prototype.attachToDOM = function() {\n this.getAttachmentPoint().append(this.root);\n\n if (this.isAttached) {\n return;\n }\n\n FocusLock.trapFocus(this.root[0]);\n\n // If we'd cached any JS then we can run it how that the modal is\n // attached to the DOM.\n if (this.bodyJS) {\n Templates.runTemplateJS(this.bodyJS);\n this.bodyJS = null;\n }\n\n if (this.footerJS) {\n Templates.runTemplateJS(this.footerJS);\n this.footerJS = null;\n }\n\n this.isAttached = true;\n };\n\n /**\n * Count the number of other visible modals (not including this one).\n *\n * @method countOtherVisibleModals\n * @return {int}\n */\n Modal.prototype.countOtherVisibleModals = function() {\n var count = 0;\n $('body').find(SELECTORS.CONTAINER).each(function(index, element) {\n element = $(element);\n\n // If we haven't found ourself and the element is visible.\n if (!this.root.is(element) && element.hasClass('show')) {\n count++;\n }\n }.bind(this));\n\n return count;\n };\n\n /**\n * Get the modal backdrop.\n *\n * @method getBackdrop\n * @return {object} jQuery promise\n */\n Modal.prototype.getBackdrop = function() {\n if (!backdropPromise) {\n backdropPromise = Templates.render(TEMPLATES.BACKDROP, {})\n .then(function(html) {\n var element = $(html);\n\n return new ModalBackdrop(element);\n })\n .fail(Notification.exception);\n }\n\n return backdropPromise;\n };\n\n /**\n * Get the root element of this modal.\n *\n * @method getRoot\n * @return {object} jQuery object\n */\n Modal.prototype.getRoot = function() {\n return this.root;\n };\n\n /**\n * Get the modal element of this modal.\n *\n * @method getModal\n * @return {object} jQuery object\n */\n Modal.prototype.getModal = function() {\n return this.modal;\n };\n\n /**\n * Get the modal title element.\n *\n * @method getTitle\n * @return {object} jQuery object\n */\n Modal.prototype.getTitle = function() {\n return this.title;\n };\n\n /**\n * Get the modal body element.\n *\n * @method getBody\n * @return {object} jQuery object\n */\n Modal.prototype.getBody = function() {\n return this.body;\n };\n\n /**\n * Get the modal footer element.\n *\n * @method getFooter\n * @return {object} jQuery object\n */\n Modal.prototype.getFooter = function() {\n return this.footer;\n };\n\n /**\n * Get a promise resolving to the title region.\n *\n * @method getTitlePromise\n * @return {Promise}\n */\n Modal.prototype.getTitlePromise = function() {\n return this.titlePromise;\n };\n\n /**\n * Get a promise resolving to the body region.\n *\n * @method getBodyPromise\n * @return {object} jQuery object\n */\n Modal.prototype.getBodyPromise = function() {\n return this.bodyPromise;\n };\n\n /**\n * Get a promise resolving to the footer region.\n *\n * @method getFooterPromise\n * @return {object} jQuery object\n */\n Modal.prototype.getFooterPromise = function() {\n return this.footerPromise;\n };\n\n /**\n * Get the unique modal count.\n *\n * @method getModalCount\n * @return {int}\n */\n Modal.prototype.getModalCount = function() {\n return this.modalCount;\n };\n\n /**\n * Set the modal title element.\n *\n * This method is overloaded to take either a string value for the title or a jQuery promise that is resolved with\n * HTML most commonly from a Str.get_string call.\n *\n * @method setTitle\n * @param {(string|object)} value The title string or jQuery promise which resolves to the title.\n */\n Modal.prototype.setTitle = function(value) {\n var title = this.getTitle();\n this.titlePromise = $.Deferred();\n\n this.asyncSet(value, title.html.bind(title))\n .then(function() {\n this.titlePromise.resolve(title);\n }.bind(this))\n .catch(Notification.exception);\n };\n\n /**\n * Set the modal body element.\n *\n * This method is overloaded to take either a string value for the body or a jQuery promise that is resolved with\n * HTML and Javascript most commonly from a Templates.render call.\n *\n * @method setBody\n * @param {(string|object)} value The body string or jQuery promise which resolves to the body.\n */\n Modal.prototype.setBody = function(value) {\n this.bodyPromise = $.Deferred();\n\n var body = this.getBody();\n\n if (typeof value === 'string') {\n // Just set the value if it's a string.\n body.html(value);\n Event.notifyFilterContentUpdated(body);\n this.getRoot().trigger(ModalEvents.bodyRendered, this);\n this.bodyPromise.resolve(body);\n } else {\n var jsPendingId = 'amd-modal-js-pending-id-' + this.getModalCount();\n M.util.js_pending(jsPendingId);\n // Otherwise we assume it's a promise to be resolved with\n // html and javascript.\n var contentPromise = null;\n body.css('overflow', 'hidden');\n\n // Ensure that the `value` is a jQuery Promise.\n value = $.when(value);\n\n if (value.state() == 'pending') {\n // We're still waiting for the body promise to resolve so\n // let's show a loading icon.\n var height = body.innerHeight();\n if (height < 100) {\n height = 100;\n }\n\n body.animate({height: height + 'px'}, 150);\n\n body.html('');\n contentPromise = Templates.render(TEMPLATES.LOADING, {})\n .then(function(html) {\n var loadingIcon = $(html).hide();\n body.html(loadingIcon);\n loadingIcon.fadeIn(150);\n\n // We only want the loading icon to fade out\n // when the content for the body has finished\n // loading.\n return $.when(loadingIcon.promise(), value);\n })\n .then(function(loadingIcon) {\n // Once the content has finished loading and\n // the loading icon has been shown then we can\n // fade the icon away to reveal the content.\n return loadingIcon.fadeOut(100).promise();\n })\n .then(function() {\n return value;\n });\n } else {\n // The content is already loaded so let's just display\n // it to the user. No need for a loading icon.\n contentPromise = value;\n }\n\n // Now we can actually display the content.\n contentPromise.then(function(html, js) {\n var result = null;\n\n if (this.isVisible()) {\n // If the modal is visible then we should display\n // the content gracefully for the user.\n body.css('opacity', 0);\n var currentHeight = body.innerHeight();\n body.html(html);\n // We need to clear any height values we've set here\n // in order to measure the height of the content being\n // added. This then allows us to animate the height\n // transition.\n body.css('height', '');\n var newHeight = body.innerHeight();\n body.css('height', currentHeight + 'px');\n result = body.animate(\n {height: newHeight + 'px', opacity: 1},\n {duration: 150, queue: false}\n ).promise();\n } else {\n // Since the modal isn't visible we can just immediately\n // set the content. No need to animate it.\n body.html(html);\n }\n\n if (js) {\n if (this.isAttached) {\n // If we're in the DOM then run the JS immediately.\n Templates.runTemplateJS(js);\n } else {\n // Otherwise cache it to be run when we're attached.\n this.bodyJS = js;\n }\n }\n\n return result;\n }.bind(this))\n .then(function(result) {\n Event.notifyFilterContentUpdated(body);\n this.getRoot().trigger(ModalEvents.bodyRendered, this);\n return result;\n }.bind(this))\n .then(function() {\n this.bodyPromise.resolve(body);\n return;\n }.bind(this))\n .fail(Notification.exception)\n .always(function() {\n // When we're done displaying all of the content we need\n // to clear the custom values we've set here.\n body.css('height', '');\n body.css('overflow', '');\n body.css('opacity', '');\n M.util.js_complete(jsPendingId);\n\n return;\n })\n .fail(Notification.exception);\n }\n };\n\n /**\n * Set the modal footer element. The footer element is made visible, if it\n * isn't already.\n *\n * This method is overloaded to take either a string\n * value for the body or a jQuery promise that is resolved with HTML and Javascript\n * most commonly from a Templates.render call.\n *\n * @method setFooter\n * @param {(string|object)} value The footer string or jQuery promise\n */\n Modal.prototype.setFooter = function(value) {\n // Make sure the footer is visible.\n this.showFooter();\n this.footerPromise = $.Deferred();\n\n var footer = this.getFooter();\n\n if (typeof value === 'string') {\n // Just set the value if it's a string.\n footer.html(value);\n this.footerPromise.resolve(footer);\n } else {\n // Otherwise we assume it's a promise to be resolved with\n // html and javascript.\n Templates.render(TEMPLATES.LOADING, {})\n .then(function(html) {\n footer.html(html);\n\n return value;\n })\n .then(function(html, js) {\n footer.html(html);\n\n if (js) {\n if (this.isAttached) {\n // If we're in the DOM then run the JS immediately.\n Templates.runTemplateJS(js);\n } else {\n // Otherwise cache it to be run when we're attached.\n this.footerJS = js;\n }\n }\n\n return footer;\n }.bind(this))\n .then(function(footer) {\n this.footerPromise.resolve(footer);\n return;\n }.bind(this))\n .catch(Notification.exception);\n }\n };\n\n /**\n * Check if the footer has any content in it.\n *\n * @method hasFooterContent\n * @return {bool}\n */\n Modal.prototype.hasFooterContent = function() {\n return this.getFooter().children().length ? true : false;\n };\n\n /**\n * Hide the footer element.\n *\n * @method hideFooter\n */\n Modal.prototype.hideFooter = function() {\n this.getFooter().addClass('hidden');\n };\n\n /**\n * Show the footer element.\n *\n * @method showFooter\n */\n Modal.prototype.showFooter = function() {\n this.getFooter().removeClass('hidden');\n };\n\n /**\n * Mark the modal as a large modal.\n *\n * @method setLarge\n */\n Modal.prototype.setLarge = function() {\n if (this.isLarge()) {\n return;\n }\n\n this.getModal().addClass('modal-lg');\n };\n\n /**\n * Check if the modal is a large modal.\n *\n * @method isLarge\n * @return {bool}\n */\n Modal.prototype.isLarge = function() {\n return this.getModal().hasClass('modal-lg');\n };\n\n /**\n * Mark the modal as a small modal.\n *\n * @method setSmall\n */\n Modal.prototype.setSmall = function() {\n if (this.isSmall()) {\n return;\n }\n\n this.getModal().removeClass('modal-lg');\n };\n\n /**\n * Check if the modal is a small modal.\n *\n * @method isSmall\n * @return {bool}\n */\n Modal.prototype.isSmall = function() {\n return !this.getModal().hasClass('modal-lg');\n };\n\n /**\n * Set this modal to be scrollable or not.\n *\n * @method setScrollable\n * @param {bool} value Whether the modal is scrollable or not\n */\n Modal.prototype.setScrollable = function(value) {\n if (!value) {\n this.getModal()[0].classList.remove('modal-dialog-scrollable');\n return;\n }\n\n this.getModal()[0].classList.add('modal-dialog-scrollable');\n };\n\n\n /**\n * Determine the highest z-index value currently on the page.\n *\n * @method calculateZIndex\n * @return {int}\n */\n Modal.prototype.calculateZIndex = function() {\n var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);\n var zIndex = parseInt(this.root.css('z-index'));\n\n items.each(function(index, item) {\n item = $(item);\n // Note that webkit browsers won't return the z-index value from the CSS stylesheet\n // if the element doesn't have a position specified. Instead it'll return \"auto\".\n var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;\n\n if (itemZIndex > zIndex) {\n zIndex = itemZIndex;\n }\n });\n\n return zIndex;\n };\n\n /**\n * Check if this modal is visible.\n *\n * @method isVisible\n * @return {bool}\n */\n Modal.prototype.isVisible = function() {\n return this.root.hasClass('show');\n };\n\n /**\n * Check if this modal has focus.\n *\n * @method hasFocus\n * @return {bool}\n */\n Modal.prototype.hasFocus = function() {\n var target = $(document.activeElement);\n return this.root.is(target) || this.root.has(target).length;\n };\n\n /**\n * Check if this modal has CSS transitions applied.\n *\n * @method hasTransitions\n * @return {bool}\n */\n Modal.prototype.hasTransitions = function() {\n return this.getRoot().hasClass('fade');\n };\n\n /**\n * Gets the jQuery wrapped node that the Modal should be attached to.\n *\n * @returns {jQuery}\n */\n Modal.prototype.getAttachmentPoint = function() {\n return $(Fullscreen.getElement() || this.attachmentPoint);\n };\n\n /**\n * Display this modal. The modal will be attached to the DOM if it hasn't\n * already been.\n *\n * @method show\n * @returns {Promise}\n */\n Modal.prototype.show = function() {\n if (this.isVisible()) {\n return $.Deferred().resolve();\n }\n\n var pendingPromise = new Pending('core/modal:show');\n\n if (this.hasFooterContent()) {\n this.showFooter();\n } else {\n this.hideFooter();\n }\n\n this.attachToDOM();\n\n return this.getBackdrop()\n .then(function(backdrop) {\n var currentIndex = this.calculateZIndex();\n var newIndex = currentIndex + 2;\n var newBackdropIndex = newIndex - 1;\n this.root.css('z-index', newIndex);\n backdrop.setZIndex(newBackdropIndex);\n backdrop.show();\n\n this.root.removeClass('hide').addClass('show');\n this.accessibilityShow();\n this.getModal().focus();\n $('body').addClass('modal-open');\n this.root.trigger(ModalEvents.shown, this);\n\n return;\n }.bind(this))\n .then(pendingPromise.resolve);\n };\n\n /**\n * Hide this modal if it does not contain a form.\n *\n * @method hideIfNotForm\n */\n Modal.prototype.hideIfNotForm = function() {\n var formElement = this.modal.find(SELECTORS.FORM);\n if (formElement.length == 0) {\n this.hide();\n }\n };\n\n /**\n * Hide this modal.\n *\n * @method hide\n */\n Modal.prototype.hide = function() {\n this.getBackdrop().done(function(backdrop) {\n FocusLock.untrapFocus();\n\n if (!this.countOtherVisibleModals()) {\n // Hide the backdrop if we're the last open modal.\n backdrop.hide();\n $('body').removeClass('modal-open');\n }\n\n var currentIndex = parseInt(this.root.css('z-index'));\n this.root.css('z-index', '');\n backdrop.setZIndex(currentIndex - 3);\n\n this.accessibilityHide();\n\n if (this.hasTransitions()) {\n // Wait for CSS transitions to complete before hiding the element.\n this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {\n this.getRoot().removeClass('show').addClass('hide');\n }.bind(this));\n } else {\n this.getRoot().removeClass('show').addClass('hide');\n }\n\n // Ensure the modal is moved onto the body node if it is still attached to the DOM.\n if ($(document.body).find(this.getRoot()).length) {\n $(document.body).append(this.getRoot());\n }\n\n this.root.trigger(ModalEvents.hidden, this);\n }.bind(this));\n };\n\n /**\n * Remove this modal from the DOM.\n *\n * @method destroy\n */\n Modal.prototype.destroy = function() {\n this.hide();\n this.root.remove();\n this.root.trigger(ModalEvents.destroyed, this);\n this.attachmentPoint.remove();\n };\n\n /**\n * Sets the appropriate aria attributes on this dialogue and the other\n * elements in the DOM to ensure that screen readers are able to navigate\n * the dialogue popup correctly.\n *\n * @method accessibilityShow\n */\n Modal.prototype.accessibilityShow = function() {\n // Make us visible to screen readers.\n Aria.unhide(this.root.get());\n\n // Hide siblings.\n Aria.hideSiblings(this.root.get()[0]);\n };\n\n /**\n * Restores the aria visibility on the DOM elements changed when displaying\n * the dialogue popup and makes the dialogue aria hidden to allow screen\n * readers to navigate the main page correctly when the dialogue is closed.\n *\n * @method accessibilityHide\n */\n Modal.prototype.accessibilityHide = function() {\n // Unhide siblings.\n Aria.unhideSiblings(this.root.get()[0]);\n\n // Hide this modal.\n Aria.hide(this.root.get());\n };\n\n /**\n * Set up all of the event handling for the modal.\n *\n * @method registerEventListeners\n */\n Modal.prototype.registerEventListeners = function() {\n this.getRoot().on('keydown', function(e) {\n if (!this.isVisible()) {\n return;\n }\n\n if (e.keyCode == KeyCodes.escape) {\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n\n // Listen for clicks on the modal container.\n this.getRoot().click(function(e) {\n // If the click wasn't inside the modal element then we should\n // hide the modal.\n if (!$(e.target).closest(SELECTORS.MODAL).length) {\n // The check above fails to detect the click was inside the modal when the DOM tree is already changed.\n // So, we check if we can still find the container element or not. If not, then the DOM tree is changed.\n // It's best not to hide the modal in that case.\n if ($(e.target).closest(SELECTORS.CONTAINER).length) {\n var outsideClickEvent = $.Event(ModalEvents.outsideClick);\n this.getRoot().trigger(outsideClickEvent, this);\n\n if (!outsideClickEvent.isDefaultPrevented()) {\n this.hideIfNotForm();\n }\n }\n }\n }.bind(this));\n\n CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);\n this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {\n this.hide();\n data.originalEvent.preventDefault();\n }.bind(this));\n };\n\n /**\n * Register a listener to close the dialogue when the cancel button is pressed.\n *\n * @method registerCloseOnCancel\n */\n Modal.prototype.registerCloseOnCancel = function() {\n // Handle the clicking of the Cancel button.\n this.getModal().on(CustomEvents.events.activate, this.getActionSelector('cancel'), function(e, data) {\n var cancelEvent = $.Event(ModalEvents.cancel);\n this.getRoot().trigger(cancelEvent, this);\n\n if (!cancelEvent.isDefaultPrevented()) {\n data.originalEvent.preventDefault();\n\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n };\n\n /**\n * Register a listener to close the dialogue when the save button is pressed.\n *\n * @method registerCloseOnSave\n */\n Modal.prototype.registerCloseOnSave = function() {\n // Handle the clicking of the Cancel button.\n this.getModal().on(CustomEvents.events.activate, this.getActionSelector('save'), function(e, data) {\n var saveEvent = $.Event(ModalEvents.save);\n this.getRoot().trigger(saveEvent, this);\n\n if (!saveEvent.isDefaultPrevented()) {\n data.originalEvent.preventDefault();\n\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n };\n\n /**\n * Set or resolve and set the value using the function.\n *\n * @method asyncSet\n * @param {(string|object)} value The string or jQuery promise.\n * @param {function} setFunction The setter\n * @return {Promise}\n */\n Modal.prototype.asyncSet = function(value, setFunction) {\n var p = value;\n if (typeof value !== 'object' || !value.hasOwnProperty('then')) {\n p = $.Deferred();\n p.resolve(value);\n }\n\n p.then(function(content) {\n setFunction(content);\n\n return;\n })\n .fail(Notification.exception);\n\n return p;\n };\n\n /**\n * Set the title text of a button.\n *\n * This method is overloaded to take either a string value for the button title or a jQuery promise that is resolved with\n * text most commonly from a Str.get_string call.\n *\n * @param {DOMString} action The action of the button\n * @param {(String|object)} value The button text, or a promise which will resolve to it\n * @returns {Promise}\n */\n Modal.prototype.setButtonText = function(action, value) {\n const button = this.getFooter().find(this.getActionSelector(action));\n\n if (!button) {\n throw new Error(\"Unable to find the '\" + action + \"' button\");\n }\n\n return this.asyncSet(value, button.text.bind(button));\n };\n\n /**\n * Get the Selector for an action.\n *\n * @param {String} action\n * @returns {DOMString}\n */\n Modal.prototype.getActionSelector = function(action) {\n return \"[data-action='\" + action + \"']\";\n };\n\n /**\n * Set the flag to remove the modal from the DOM on close.\n *\n * @param {Boolean} remove\n */\n Modal.prototype.setRemoveOnClose = function(remove) {\n this.removeOnClose = remove;\n };\n\n return Modal;\n});\n"],"file":"modal.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/modal.js"],"names":["define","$","Templates","Notification","KeyCodes","CustomEvents","ModalBackdrop","Event","ModalEvents","FocusLock","Pending","Aria","Fullscreen","SELECTORS","CONTAINER","MODAL","HEADER","TITLE","BODY","FOOTER","HIDE","DIALOG","FORM","MENU_BAR","HAS_Z_INDEX","CAN_RECEIVE_FOCUS","TEMPLATES","LOADING","BACKDROP","backdropPromise","modalCounter","Modal","root","modal","find","header","headerPromise","Deferred","title","titlePromise","body","bodyPromise","footer","footerPromise","hiddenSiblings","isAttached","bodyJS","footerJS","modalCount","attachmentPoint","document","createElement","append","is","exception","message","length","registerEventListeners","prototype","attachToDOM","getAttachmentPoint","trapFocus","runTemplateJS","countOtherVisibleModals","count","each","index","element","hasClass","bind","getBackdrop","render","then","html","fail","getRoot","getModal","getTitle","getBody","getFooter","getTitlePromise","getBodyPromise","getFooterPromise","getModalCount","setTitle","value","asyncSet","resolve","catch","setBody","notifyFilterContentUpdated","trigger","bodyRendered","jsPendingId","M","util","js_pending","contentPromise","css","when","state","height","innerHeight","animate","loadingIcon","hide","fadeIn","promise","fadeOut","js","result","isVisible","currentHeight","newHeight","opacity","duration","queue","always","js_complete","setBodyContent","setFooter","showFooter","hasFooterContent","children","hideFooter","addClass","removeClass","setLarge","isLarge","setSmall","isSmall","setScrollable","classList","remove","add","calculateZIndex","items","zIndex","parseInt","item","itemZIndex","hasFocus","target","activeElement","has","hasTransitions","getElement","show","pendingPromise","backdrop","currentIndex","newIndex","setZIndex","accessibilityShow","focus","shown","hideIfNotForm","formElement","done","untrapFocus","accessibilityHide","one","hidden","destroy","destroyed","unhide","get","hideSiblings","unhideSiblings","on","e","keyCode","escape","removeOnClose","click","closest","outsideClickEvent","outsideClick","isDefaultPrevented","events","activate","data","originalEvent","preventDefault","registerCloseOnCancel","getActionSelector","cancelEvent","cancel","registerCloseOnSave","saveEvent","save","setFunction","p","hasOwnProperty","content","setButtonText","action","button","Error","text","setRemoveOnClose"],"mappings":"mSAwBAA,OAAM,cAAC,CACH,QADG,CAEH,gBAFG,CAGH,mBAHG,CAIH,gBAJG,CAKH,gCALG,CAMH,qBANG,CAOH,YAPG,CAQH,mBARG,CASH,2BATG,CAUH,cAVG,CAWH,WAXG,CAYH,iBAZG,CAAD,CAaH,SACCC,CADD,CAECC,CAFD,CAGCC,CAHD,CAICC,CAJD,CAKCC,CALD,CAMCC,CAND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5DD,CAAC,CAAG/L,CAAC,CAACoC,QAAF,EAAJ,CACA2J,CAAC,CAACzG,OAAF,CAAUF,CAAV,CACH,CAED2G,CAAC,CAACxH,IAAF,CAAO,SAAS0H,CAAT,CAAkB,CACrBH,CAAW,CAACG,CAAD,CAGd,CAJD,EAKCxH,IALD,CAKMvE,CAAY,CAACmD,SALnB,EAOA,MAAO0I,CAAAA,CACV,CAfD,CA2BAjK,CAAK,CAAC2B,SAAN,CAAgByI,aAAhB,CAAgC,SAASC,CAAT,CAAiB/G,CAAjB,CAAwB,CACpD,GAAMgH,CAAAA,CAAM,CAAG,KAAKtH,SAAL,GAAiB7C,IAAjB,CAAsB,KAAKuJ,iBAAL,CAAuBW,CAAvB,CAAtB,CAAf,CAEA,GAAI,CAACC,CAAL,CAAa,CACT,KAAM,IAAIC,CAAAA,KAAJ,CAAU,uBAAyBF,CAAzB,CAAkC,UAA5C,CACT,CAED,MAAO,MAAK9G,QAAL,CAAcD,CAAd,CAAqBgH,CAAM,CAACE,IAAP,CAAYlI,IAAZ,CAAiBgI,CAAjB,CAArB,CACV,CARD,CAgBAtK,CAAK,CAAC2B,SAAN,CAAgB+H,iBAAhB,CAAoC,SAASW,CAAT,CAAiB,CACjD,MAAO,iBAAmBA,CAAnB,CAA4B,IACtC,CAFD,CASArK,CAAK,CAAC2B,SAAN,CAAgB8I,gBAAhB,CAAmC,SAASnE,CAAT,CAAiB,CAChD,KAAKwC,aAAL,CAAqBxC,CACxB,CAFD,CAIA,MAAOtG,CAAAA,CACV,CAz6BK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Contain the logic for modals.\n *\n * @module core/modal\n * @class modal\n * @package core\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/templates',\n 'core/notification',\n 'core/key_codes',\n 'core/custom_interaction_events',\n 'core/modal_backdrop',\n 'core/event',\n 'core/modal_events',\n 'core/local/aria/focuslock',\n 'core/pending',\n 'core/aria',\n 'core/fullscreen'\n], function(\n $,\n Templates,\n Notification,\n KeyCodes,\n CustomEvents,\n ModalBackdrop,\n Event,\n ModalEvents,\n FocusLock,\n Pending,\n Aria,\n Fullscreen\n) {\n\n var SELECTORS = {\n CONTAINER: '[data-region=\"modal-container\"]',\n MODAL: '[data-region=\"modal\"]',\n HEADER: '[data-region=\"header\"]',\n TITLE: '[data-region=\"title\"]',\n BODY: '[data-region=\"body\"]',\n FOOTER: '[data-region=\"footer\"]',\n HIDE: '[data-action=\"hide\"]',\n DIALOG: '[role=dialog]',\n FORM: 'form',\n MENU_BAR: '[role=menubar]',\n HAS_Z_INDEX: '.moodle-has-zindex',\n CAN_RECEIVE_FOCUS: 'input:not([type=\"hidden\"]), a[href], button, textarea, select, [tabindex]',\n };\n\n var TEMPLATES = {\n LOADING: 'core/loading',\n BACKDROP: 'core/modal_backdrop',\n };\n\n /**\n * Module singleton for the backdrop to be reused by all Modal instances.\n */\n var backdropPromise;\n\n /**\n * A counter that gets incremented for each modal created. This can be\n * used to generate unique values for the modals.\n */\n var modalCounter = 0;\n\n /**\n * Constructor for the Modal.\n *\n * @param {object} root The root jQuery element for the modal\n */\n var Modal = function(root) {\n this.root = $(root);\n this.modal = this.root.find(SELECTORS.MODAL);\n this.header = this.modal.find(SELECTORS.HEADER);\n this.headerPromise = $.Deferred();\n this.title = this.header.find(SELECTORS.TITLE);\n this.titlePromise = $.Deferred();\n this.body = this.modal.find(SELECTORS.BODY);\n this.bodyPromise = $.Deferred();\n this.footer = this.modal.find(SELECTORS.FOOTER);\n this.footerPromise = $.Deferred();\n this.hiddenSiblings = [];\n this.isAttached = false;\n this.bodyJS = null;\n this.footerJS = null;\n this.modalCount = modalCounter++;\n this.attachmentPoint = document.createElement('div');\n document.body.append(this.attachmentPoint);\n\n if (!this.root.is(SELECTORS.CONTAINER)) {\n Notification.exception({message: 'Element is not a modal container'});\n }\n\n if (!this.modal.length) {\n Notification.exception({message: 'Container does not contain a modal'});\n }\n\n if (!this.header.length) {\n Notification.exception({message: 'Modal is missing a header region'});\n }\n\n if (!this.title.length) {\n Notification.exception({message: 'Modal header is missing a title region'});\n }\n\n if (!this.body.length) {\n Notification.exception({message: 'Modal is missing a body region'});\n }\n\n if (!this.footer.length) {\n Notification.exception({message: 'Modal is missing a footer region'});\n }\n\n this.registerEventListeners();\n };\n\n /**\n * Attach the modal to the correct part of the page.\n *\n * If it hasn't already been added it runs any\n * javascript that has been cached until now.\n *\n * @method attachToDOM\n */\n Modal.prototype.attachToDOM = function() {\n this.getAttachmentPoint().append(this.root);\n\n if (this.isAttached) {\n return;\n }\n\n FocusLock.trapFocus(this.root[0]);\n\n // If we'd cached any JS then we can run it how that the modal is\n // attached to the DOM.\n if (this.bodyJS) {\n Templates.runTemplateJS(this.bodyJS);\n this.bodyJS = null;\n }\n\n if (this.footerJS) {\n Templates.runTemplateJS(this.footerJS);\n this.footerJS = null;\n }\n\n this.isAttached = true;\n };\n\n /**\n * Count the number of other visible modals (not including this one).\n *\n * @method countOtherVisibleModals\n * @return {int}\n */\n Modal.prototype.countOtherVisibleModals = function() {\n var count = 0;\n $('body').find(SELECTORS.CONTAINER).each(function(index, element) {\n element = $(element);\n\n // If we haven't found ourself and the element is visible.\n if (!this.root.is(element) && element.hasClass('show')) {\n count++;\n }\n }.bind(this));\n\n return count;\n };\n\n /**\n * Get the modal backdrop.\n *\n * @method getBackdrop\n * @return {object} jQuery promise\n */\n Modal.prototype.getBackdrop = function() {\n if (!backdropPromise) {\n backdropPromise = Templates.render(TEMPLATES.BACKDROP, {})\n .then(function(html) {\n var element = $(html);\n\n return new ModalBackdrop(element);\n })\n .fail(Notification.exception);\n }\n\n return backdropPromise;\n };\n\n /**\n * Get the root element of this modal.\n *\n * @method getRoot\n * @return {object} jQuery object\n */\n Modal.prototype.getRoot = function() {\n return this.root;\n };\n\n /**\n * Get the modal element of this modal.\n *\n * @method getModal\n * @return {object} jQuery object\n */\n Modal.prototype.getModal = function() {\n return this.modal;\n };\n\n /**\n * Get the modal title element.\n *\n * @method getTitle\n * @return {object} jQuery object\n */\n Modal.prototype.getTitle = function() {\n return this.title;\n };\n\n /**\n * Get the modal body element.\n *\n * @method getBody\n * @return {object} jQuery object\n */\n Modal.prototype.getBody = function() {\n return this.body;\n };\n\n /**\n * Get the modal footer element.\n *\n * @method getFooter\n * @return {object} jQuery object\n */\n Modal.prototype.getFooter = function() {\n return this.footer;\n };\n\n /**\n * Get a promise resolving to the title region.\n *\n * @method getTitlePromise\n * @return {Promise}\n */\n Modal.prototype.getTitlePromise = function() {\n return this.titlePromise;\n };\n\n /**\n * Get a promise resolving to the body region.\n *\n * @method getBodyPromise\n * @return {object} jQuery object\n */\n Modal.prototype.getBodyPromise = function() {\n return this.bodyPromise;\n };\n\n /**\n * Get a promise resolving to the footer region.\n *\n * @method getFooterPromise\n * @return {object} jQuery object\n */\n Modal.prototype.getFooterPromise = function() {\n return this.footerPromise;\n };\n\n /**\n * Get the unique modal count.\n *\n * @method getModalCount\n * @return {int}\n */\n Modal.prototype.getModalCount = function() {\n return this.modalCount;\n };\n\n /**\n * Set the modal title element.\n *\n * This method is overloaded to take either a string value for the title or a jQuery promise that is resolved with\n * HTML most commonly from a Str.get_string call.\n *\n * @method setTitle\n * @param {(string|object)} value The title string or jQuery promise which resolves to the title.\n */\n Modal.prototype.setTitle = function(value) {\n var title = this.getTitle();\n this.titlePromise = $.Deferred();\n\n this.asyncSet(value, title.html.bind(title))\n .then(function() {\n this.titlePromise.resolve(title);\n }.bind(this))\n .catch(Notification.exception);\n };\n\n /**\n * Set the modal body element.\n *\n * This method is overloaded to take either a string value for the body or a jQuery promise that is resolved with\n * HTML and Javascript most commonly from a Templates.render call.\n *\n * @method setBody\n * @param {(string|object)} value The body string or jQuery promise which resolves to the body.\n */\n Modal.prototype.setBody = function(value) {\n this.bodyPromise = $.Deferred();\n\n var body = this.getBody();\n\n if (typeof value === 'string') {\n // Just set the value if it's a string.\n body.html(value);\n Event.notifyFilterContentUpdated(body);\n this.getRoot().trigger(ModalEvents.bodyRendered, this);\n this.bodyPromise.resolve(body);\n } else {\n var jsPendingId = 'amd-modal-js-pending-id-' + this.getModalCount();\n M.util.js_pending(jsPendingId);\n // Otherwise we assume it's a promise to be resolved with\n // html and javascript.\n var contentPromise = null;\n body.css('overflow', 'hidden');\n\n // Ensure that the `value` is a jQuery Promise.\n value = $.when(value);\n\n if (value.state() == 'pending') {\n // We're still waiting for the body promise to resolve so\n // let's show a loading icon.\n var height = body.innerHeight();\n if (height < 100) {\n height = 100;\n }\n\n body.animate({height: height + 'px'}, 150);\n\n body.html('');\n contentPromise = Templates.render(TEMPLATES.LOADING, {})\n .then(function(html) {\n var loadingIcon = $(html).hide();\n body.html(loadingIcon);\n loadingIcon.fadeIn(150);\n\n // We only want the loading icon to fade out\n // when the content for the body has finished\n // loading.\n return $.when(loadingIcon.promise(), value);\n })\n .then(function(loadingIcon) {\n // Once the content has finished loading and\n // the loading icon has been shown then we can\n // fade the icon away to reveal the content.\n return loadingIcon.fadeOut(100).promise();\n })\n .then(function() {\n return value;\n });\n } else {\n // The content is already loaded so let's just display\n // it to the user. No need for a loading icon.\n contentPromise = value;\n }\n\n // Now we can actually display the content.\n contentPromise.then(function(html, js) {\n var result = null;\n\n if (this.isVisible()) {\n // If the modal is visible then we should display\n // the content gracefully for the user.\n body.css('opacity', 0);\n var currentHeight = body.innerHeight();\n body.html(html);\n // We need to clear any height values we've set here\n // in order to measure the height of the content being\n // added. This then allows us to animate the height\n // transition.\n body.css('height', '');\n var newHeight = body.innerHeight();\n body.css('height', currentHeight + 'px');\n result = body.animate(\n {height: newHeight + 'px', opacity: 1},\n {duration: 150, queue: false}\n ).promise();\n } else {\n // Since the modal isn't visible we can just immediately\n // set the content. No need to animate it.\n body.html(html);\n }\n\n if (js) {\n if (this.isAttached) {\n // If we're in the DOM then run the JS immediately.\n Templates.runTemplateJS(js);\n } else {\n // Otherwise cache it to be run when we're attached.\n this.bodyJS = js;\n }\n }\n\n return result;\n }.bind(this))\n .then(function(result) {\n Event.notifyFilterContentUpdated(body);\n this.getRoot().trigger(ModalEvents.bodyRendered, this);\n return result;\n }.bind(this))\n .then(function() {\n this.bodyPromise.resolve(body);\n return;\n }.bind(this))\n .fail(Notification.exception)\n .always(function() {\n // When we're done displaying all of the content we need\n // to clear the custom values we've set here.\n body.css('height', '');\n body.css('overflow', '');\n body.css('opacity', '');\n M.util.js_complete(jsPendingId);\n\n return;\n })\n .fail(Notification.exception);\n }\n };\n\n /**\n * Alternative to setBody() that can be used from non-Jquery modules\n *\n * @param {Promise} promise promise that returns {html, js} object\n * @return {Promise}\n */\n Modal.prototype.setBodyContent = function(promise) {\n // Call the leegacy API for now and pass it a jQuery Promise.\n // This is a non-spec feature of jQuery and cannot be produced with spec promises.\n // We can encourage people to migrate to this approach, and in future we can swap\n // it so that setBody() calls setBodyPromise().\n return promise.then(({html, js}) => this.setBody($.when(html, js)));\n };\n\n /**\n * Set the modal footer element. The footer element is made visible, if it\n * isn't already.\n *\n * This method is overloaded to take either a string\n * value for the body or a jQuery promise that is resolved with HTML and Javascript\n * most commonly from a Templates.render call.\n *\n * @method setFooter\n * @param {(string|object)} value The footer string or jQuery promise\n */\n Modal.prototype.setFooter = function(value) {\n // Make sure the footer is visible.\n this.showFooter();\n this.footerPromise = $.Deferred();\n\n var footer = this.getFooter();\n\n if (typeof value === 'string') {\n // Just set the value if it's a string.\n footer.html(value);\n this.footerPromise.resolve(footer);\n } else {\n // Otherwise we assume it's a promise to be resolved with\n // html and javascript.\n Templates.render(TEMPLATES.LOADING, {})\n .then(function(html) {\n footer.html(html);\n\n return value;\n })\n .then(function(html, js) {\n footer.html(html);\n\n if (js) {\n if (this.isAttached) {\n // If we're in the DOM then run the JS immediately.\n Templates.runTemplateJS(js);\n } else {\n // Otherwise cache it to be run when we're attached.\n this.footerJS = js;\n }\n }\n\n return footer;\n }.bind(this))\n .then(function(footer) {\n this.footerPromise.resolve(footer);\n return;\n }.bind(this))\n .catch(Notification.exception);\n }\n };\n\n /**\n * Check if the footer has any content in it.\n *\n * @method hasFooterContent\n * @return {bool}\n */\n Modal.prototype.hasFooterContent = function() {\n return this.getFooter().children().length ? true : false;\n };\n\n /**\n * Hide the footer element.\n *\n * @method hideFooter\n */\n Modal.prototype.hideFooter = function() {\n this.getFooter().addClass('hidden');\n };\n\n /**\n * Show the footer element.\n *\n * @method showFooter\n */\n Modal.prototype.showFooter = function() {\n this.getFooter().removeClass('hidden');\n };\n\n /**\n * Mark the modal as a large modal.\n *\n * @method setLarge\n */\n Modal.prototype.setLarge = function() {\n if (this.isLarge()) {\n return;\n }\n\n this.getModal().addClass('modal-lg');\n };\n\n /**\n * Check if the modal is a large modal.\n *\n * @method isLarge\n * @return {bool}\n */\n Modal.prototype.isLarge = function() {\n return this.getModal().hasClass('modal-lg');\n };\n\n /**\n * Mark the modal as a small modal.\n *\n * @method setSmall\n */\n Modal.prototype.setSmall = function() {\n if (this.isSmall()) {\n return;\n }\n\n this.getModal().removeClass('modal-lg');\n };\n\n /**\n * Check if the modal is a small modal.\n *\n * @method isSmall\n * @return {bool}\n */\n Modal.prototype.isSmall = function() {\n return !this.getModal().hasClass('modal-lg');\n };\n\n /**\n * Set this modal to be scrollable or not.\n *\n * @method setScrollable\n * @param {bool} value Whether the modal is scrollable or not\n */\n Modal.prototype.setScrollable = function(value) {\n if (!value) {\n this.getModal()[0].classList.remove('modal-dialog-scrollable');\n return;\n }\n\n this.getModal()[0].classList.add('modal-dialog-scrollable');\n };\n\n\n /**\n * Determine the highest z-index value currently on the page.\n *\n * @method calculateZIndex\n * @return {int}\n */\n Modal.prototype.calculateZIndex = function() {\n var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);\n var zIndex = parseInt(this.root.css('z-index'));\n\n items.each(function(index, item) {\n item = $(item);\n // Note that webkit browsers won't return the z-index value from the CSS stylesheet\n // if the element doesn't have a position specified. Instead it'll return \"auto\".\n var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;\n\n if (itemZIndex > zIndex) {\n zIndex = itemZIndex;\n }\n });\n\n return zIndex;\n };\n\n /**\n * Check if this modal is visible.\n *\n * @method isVisible\n * @return {bool}\n */\n Modal.prototype.isVisible = function() {\n return this.root.hasClass('show');\n };\n\n /**\n * Check if this modal has focus.\n *\n * @method hasFocus\n * @return {bool}\n */\n Modal.prototype.hasFocus = function() {\n var target = $(document.activeElement);\n return this.root.is(target) || this.root.has(target).length;\n };\n\n /**\n * Check if this modal has CSS transitions applied.\n *\n * @method hasTransitions\n * @return {bool}\n */\n Modal.prototype.hasTransitions = function() {\n return this.getRoot().hasClass('fade');\n };\n\n /**\n * Gets the jQuery wrapped node that the Modal should be attached to.\n *\n * @returns {jQuery}\n */\n Modal.prototype.getAttachmentPoint = function() {\n return $(Fullscreen.getElement() || this.attachmentPoint);\n };\n\n /**\n * Display this modal. The modal will be attached to the DOM if it hasn't\n * already been.\n *\n * @method show\n * @returns {Promise}\n */\n Modal.prototype.show = function() {\n if (this.isVisible()) {\n return $.Deferred().resolve();\n }\n\n var pendingPromise = new Pending('core/modal:show');\n\n if (this.hasFooterContent()) {\n this.showFooter();\n } else {\n this.hideFooter();\n }\n\n this.attachToDOM();\n\n return this.getBackdrop()\n .then(function(backdrop) {\n var currentIndex = this.calculateZIndex();\n var newIndex = currentIndex + 2;\n var newBackdropIndex = newIndex - 1;\n this.root.css('z-index', newIndex);\n backdrop.setZIndex(newBackdropIndex);\n backdrop.show();\n\n this.root.removeClass('hide').addClass('show');\n this.accessibilityShow();\n this.getModal().focus();\n $('body').addClass('modal-open');\n this.root.trigger(ModalEvents.shown, this);\n\n return;\n }.bind(this))\n .then(pendingPromise.resolve);\n };\n\n /**\n * Hide this modal if it does not contain a form.\n *\n * @method hideIfNotForm\n */\n Modal.prototype.hideIfNotForm = function() {\n var formElement = this.modal.find(SELECTORS.FORM);\n if (formElement.length == 0) {\n this.hide();\n }\n };\n\n /**\n * Hide this modal.\n *\n * @method hide\n */\n Modal.prototype.hide = function() {\n this.getBackdrop().done(function(backdrop) {\n FocusLock.untrapFocus();\n\n if (!this.countOtherVisibleModals()) {\n // Hide the backdrop if we're the last open modal.\n backdrop.hide();\n $('body').removeClass('modal-open');\n }\n\n var currentIndex = parseInt(this.root.css('z-index'));\n this.root.css('z-index', '');\n backdrop.setZIndex(currentIndex - 3);\n\n this.accessibilityHide();\n\n if (this.hasTransitions()) {\n // Wait for CSS transitions to complete before hiding the element.\n this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {\n this.getRoot().removeClass('show').addClass('hide');\n }.bind(this));\n } else {\n this.getRoot().removeClass('show').addClass('hide');\n }\n\n // Ensure the modal is moved onto the body node if it is still attached to the DOM.\n if ($(document.body).find(this.getRoot()).length) {\n $(document.body).append(this.getRoot());\n }\n\n this.root.trigger(ModalEvents.hidden, this);\n }.bind(this));\n };\n\n /**\n * Remove this modal from the DOM.\n *\n * @method destroy\n */\n Modal.prototype.destroy = function() {\n this.hide();\n this.root.remove();\n this.root.trigger(ModalEvents.destroyed, this);\n this.attachmentPoint.remove();\n };\n\n /**\n * Sets the appropriate aria attributes on this dialogue and the other\n * elements in the DOM to ensure that screen readers are able to navigate\n * the dialogue popup correctly.\n *\n * @method accessibilityShow\n */\n Modal.prototype.accessibilityShow = function() {\n // Make us visible to screen readers.\n Aria.unhide(this.root.get());\n\n // Hide siblings.\n Aria.hideSiblings(this.root.get()[0]);\n };\n\n /**\n * Restores the aria visibility on the DOM elements changed when displaying\n * the dialogue popup and makes the dialogue aria hidden to allow screen\n * readers to navigate the main page correctly when the dialogue is closed.\n *\n * @method accessibilityHide\n */\n Modal.prototype.accessibilityHide = function() {\n // Unhide siblings.\n Aria.unhideSiblings(this.root.get()[0]);\n\n // Hide this modal.\n Aria.hide(this.root.get());\n };\n\n /**\n * Set up all of the event handling for the modal.\n *\n * @method registerEventListeners\n */\n Modal.prototype.registerEventListeners = function() {\n this.getRoot().on('keydown', function(e) {\n if (!this.isVisible()) {\n return;\n }\n\n if (e.keyCode == KeyCodes.escape) {\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n\n // Listen for clicks on the modal container.\n this.getRoot().click(function(e) {\n // If the click wasn't inside the modal element then we should\n // hide the modal.\n if (!$(e.target).closest(SELECTORS.MODAL).length) {\n // The check above fails to detect the click was inside the modal when the DOM tree is already changed.\n // So, we check if we can still find the container element or not. If not, then the DOM tree is changed.\n // It's best not to hide the modal in that case.\n if ($(e.target).closest(SELECTORS.CONTAINER).length) {\n var outsideClickEvent = $.Event(ModalEvents.outsideClick);\n this.getRoot().trigger(outsideClickEvent, this);\n\n if (!outsideClickEvent.isDefaultPrevented()) {\n this.hideIfNotForm();\n }\n }\n }\n }.bind(this));\n\n CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);\n this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {\n this.hide();\n data.originalEvent.preventDefault();\n }.bind(this));\n };\n\n /**\n * Register a listener to close the dialogue when the cancel button is pressed.\n *\n * @method registerCloseOnCancel\n */\n Modal.prototype.registerCloseOnCancel = function() {\n // Handle the clicking of the Cancel button.\n this.getModal().on(CustomEvents.events.activate, this.getActionSelector('cancel'), function(e, data) {\n var cancelEvent = $.Event(ModalEvents.cancel);\n this.getRoot().trigger(cancelEvent, this);\n\n if (!cancelEvent.isDefaultPrevented()) {\n data.originalEvent.preventDefault();\n\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n };\n\n /**\n * Register a listener to close the dialogue when the save button is pressed.\n *\n * @method registerCloseOnSave\n */\n Modal.prototype.registerCloseOnSave = function() {\n // Handle the clicking of the Cancel button.\n this.getModal().on(CustomEvents.events.activate, this.getActionSelector('save'), function(e, data) {\n var saveEvent = $.Event(ModalEvents.save);\n this.getRoot().trigger(saveEvent, this);\n\n if (!saveEvent.isDefaultPrevented()) {\n data.originalEvent.preventDefault();\n\n if (this.removeOnClose) {\n this.destroy();\n } else {\n this.hide();\n }\n }\n }.bind(this));\n };\n\n /**\n * Set or resolve and set the value using the function.\n *\n * @method asyncSet\n * @param {(string|object)} value The string or jQuery promise.\n * @param {function} setFunction The setter\n * @return {Promise}\n */\n Modal.prototype.asyncSet = function(value, setFunction) {\n var p = value;\n if (typeof value !== 'object' || !value.hasOwnProperty('then')) {\n p = $.Deferred();\n p.resolve(value);\n }\n\n p.then(function(content) {\n setFunction(content);\n\n return;\n })\n .fail(Notification.exception);\n\n return p;\n };\n\n /**\n * Set the title text of a button.\n *\n * This method is overloaded to take either a string value for the button title or a jQuery promise that is resolved with\n * text most commonly from a Str.get_string call.\n *\n * @param {DOMString} action The action of the button\n * @param {(String|object)} value The button text, or a promise which will resolve to it\n * @returns {Promise}\n */\n Modal.prototype.setButtonText = function(action, value) {\n const button = this.getFooter().find(this.getActionSelector(action));\n\n if (!button) {\n throw new Error(\"Unable to find the '\" + action + \"' button\");\n }\n\n return this.asyncSet(value, button.text.bind(button));\n };\n\n /**\n * Get the Selector for an action.\n *\n * @param {String} action\n * @returns {DOMString}\n */\n Modal.prototype.getActionSelector = function(action) {\n return \"[data-action='\" + action + \"']\";\n };\n\n /**\n * Set the flag to remove the modal from the DOM on close.\n *\n * @param {Boolean} remove\n */\n Modal.prototype.setRemoveOnClose = function(remove) {\n this.removeOnClose = remove;\n };\n\n return Modal;\n});\n"],"file":"modal.min.js"} \ No newline at end of file diff --git a/lib/amd/src/fragment.js b/lib/amd/src/fragment.js index 0a29f68156c..7c45ca3105f 100644 --- a/lib/amd/src/fragment.js +++ b/lib/amd/src/fragment.js @@ -56,6 +56,44 @@ define(['jquery', 'core/ajax'], function($, ajax) { }])[0]; }; + /** + * Converts the JS that was received from collecting JS requirements on the $PAGE so it can be added to the existing page + * + * @param {string} js + * @return {string} + */ + var processCollectedJavascript = function(js) { + var jsNodes = $(js); + var allScript = ''; + jsNodes.each(function(index, scriptNode) { + scriptNode = $(scriptNode); + var tagName = scriptNode.prop('tagName'); + if (tagName && (tagName.toLowerCase() == 'script')) { + if (scriptNode.attr('src')) { + // We only reload the script if it was not loaded already. + var exists = false; + $('script').each(function(index, s) { + if ($(s).attr('src') == scriptNode.attr('src')) { + exists = true; + } + return !exists; + }); + if (!exists) { + allScript += ' { '; + allScript += ' node = document.createElement("script"); '; + allScript += ' node.type = "text/javascript"; '; + allScript += ' node.src = decodeURI("' + encodeURI(scriptNode.attr('src')) + '"); '; + allScript += ' document.getElementsByTagName("head")[0].appendChild(node); '; + allScript += ' } '; + } + } else { + allScript += ' ' + scriptNode.text(); + } + } + }); + return allScript; + }; + return /** @alias module:core/fragment */{ /** * Appends HTML and JavaScript fragments to specified nodes. @@ -72,40 +110,21 @@ define(['jquery', 'core/ajax'], function($, ajax) { loadFragment: function(component, callback, contextid, params) { var promise = $.Deferred(); loadFragment(component, callback, contextid, params).then(function(data) { - var jsNodes = $(data.javascript); - var allScript = ''; - jsNodes.each(function(index, scriptNode) { - scriptNode = $(scriptNode); - var tagName = scriptNode.prop('tagName'); - if (tagName && (tagName.toLowerCase() == 'script')) { - if (scriptNode.attr('src')) { - // We only reload the script if it was not loaded already. - var exists = false; - $('script').each(function(index, s) { - if ($(s).attr('src') == scriptNode.attr('src')) { - exists = true; - } - return !exists; - }); - if (!exists) { - allScript += ' { '; - allScript += ' node = document.createElement("script"); '; - allScript += ' node.type = "text/javascript"; '; - allScript += ' node.src = decodeURI("' + encodeURI(scriptNode.attr('src')) + '"); '; - allScript += ' document.getElementsByTagName("head")[0].appendChild(node); '; - allScript += ' } '; - } - } else { - allScript += ' ' + scriptNode.text(); - } - } - }); - promise.resolve(data.html, allScript); - return; + promise.resolve(data.html, processCollectedJavascript(data.javascript)); }).fail(function(ex) { promise.reject(ex); }); return promise.promise(); + }, + + /** + * Converts the JS that was received from collecting JS requirements on the $PAGE so it can be added to the existing page + * + * @param {string} js + * @return {string} + */ + processCollectedJavascript: function(js) { + return processCollectedJavascript(js); } }; }); diff --git a/lib/amd/src/modal.js b/lib/amd/src/modal.js index ea2defa057a..8a5840c1c35 100644 --- a/lib/amd/src/modal.js +++ b/lib/amd/src/modal.js @@ -445,6 +445,20 @@ define([ } }; + /** + * Alternative to setBody() that can be used from non-Jquery modules + * + * @param {Promise} promise promise that returns {html, js} object + * @return {Promise} + */ + Modal.prototype.setBodyContent = function(promise) { + // Call the leegacy API for now and pass it a jQuery Promise. + // This is a non-spec feature of jQuery and cannot be produced with spec promises. + // We can encourage people to migrate to this approach, and in future we can swap + // it so that setBody() calls setBodyPromise(). + return promise.then(({html, js}) => this.setBody($.when(html, js))); + }; + /** * Set the modal footer element. The footer element is made visible, if it * isn't already. diff --git a/lib/db/services.php b/lib/db/services.php index 17b2443d558..785286404d1 100644 --- a/lib/db/services.php +++ b/lib/db/services.php @@ -837,6 +837,13 @@ $functions = array( 'loginrequired' => false, 'ajax' => true, ), + 'core_form_dynamic_form' => array( + 'classname' => 'core_form\external\dynamic_form', + 'methodname' => 'execute', + 'description' => 'Process submission of a dynamic (modal) form', + 'type' => 'write', + 'ajax' => true, + ), 'core_get_component_strings' => array( 'classname' => 'core_external', 'methodname' => 'get_component_strings', diff --git a/lib/form/amd/build/dynamicform.min.js b/lib/form/amd/build/dynamicform.min.js new file mode 100644 index 00000000000..7599b09e0eb --- /dev/null +++ b/lib/form/amd/build/dynamicform.min.js @@ -0,0 +1,2 @@ +define ("core_form/dynamicform",["exports","core/ajax","core/notification","core/templates","core/event","core/str","core/yui","core/fragment","core/pending"],function(a,b,c,d,e,f,g,h,i){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.default=void 0;b=j(b);c=j(c);d=j(d);e=j(e);g=j(g);h=j(h);i=j(i);function j(a){return a&&a.__esModule?a:{default:a}}function k(a,b,c,d,e,f,g){try{var h=a[f](g),i=h.value}catch(a){c(a);return}if(h.done){b(i)}else{Promise.resolve(i).then(d,e)}}function l(a){return function(){var b=this,c=arguments;return new Promise(function(d,e){var h=a.apply(b,c);function f(a){k(h,d,e,f,g,"next",a)}function g(a){k(h,d,e,f,g,"throw",a)}f(void 0)})}}function m(a){return q(a)||p(a)||o(a)||n()}function n(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(a,b){if(!a)return;if("string"==typeof a)return r(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);if("Object"===c&&a.constructor)c=a.constructor.name;if("Map"===c||"Set"===c)return Array.from(c);if("Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c))return r(a,b)}function p(a){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(a))return Array.from(a)}function q(a){if(Array.isArray(a))return r(a)}function r(a,b){if(null==b||b>a.length)b=a.length;for(var c=0,d=Array(b);c.\n\n/**\n * Display an embedded form, it is only loaded and reloaded inside its container\n *\n * Example:\n * import DynamicForm from 'core_form/dynamicform';\n *\n * const dynamicForm = new DynamicForm(document.querySelector('#mycontainer', 'pluginname\\\\form\\\\formname');\n * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => {\n * e.preventDefault();\n * window.console.log(e.detail);\n * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!';\n * });\n * dynamicForm.load();\n *\n * See also https://docs.moodle.org/dev/Modal_and_AJAX_forms\n *\n * @module core_form/dynamicform\n * @package core_form\n * @copyright 2019 Marina Glancy\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport Templates from 'core/templates';\nimport Event from 'core/event';\nimport {get_strings as getStrings} from 'core/str';\nimport Y from 'core/yui';\nimport Fragment from 'core/fragment';\nimport Pending from 'core/pending';\n\nexport default class DynamicForm {\n\n /**\n * Various events that can be observed.\n *\n * @type {Object}\n */\n events = {\n // Form was successfully submitted - the response is passed to the event listener.\n // Cancellable (in order to prevent default behavior to clear the container).\n FORM_SUBMITTED: 'core_form_dynamicform_formsubmitted',\n // Cancel button was pressed.\n // Cancellable (in order to prevent default behavior to clear the container).\n FORM_CANCELLED: 'core_form_dynamicform_formcancelled',\n // User attempted to submit the form but there was client-side validation error.\n CLIENT_VALIDATION_ERROR: 'core_form_dynamicform_clientvalidationerror',\n // User attempted to submit the form but server returned validation error.\n SERVER_VALIDATION_ERROR: 'core_form_dynamicform_validationerror',\n // Error occurred while performing request to the server.\n // Cancellable (by default calls Notification.exception).\n ERROR: 'core_form_dynamicform_error',\n // Right after user pressed no-submit button,\n // listen to this event if you want to add JS validation or processing for no-submit button.\n // Cancellable.\n NOSUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_nosubmitbutton',\n // Right after user pressed submit button,\n // listen to this event if you want to add additional JS validation or confirmation dialog.\n // Cancellable.\n SUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_submitbutton',\n // Right after user pressed cancel button,\n // listen to this event if you want to add confirmation dialog.\n // Cancellable.\n CANCEL_BUTTON_PRESSED: 'core_form_dynamicform_cancelbutton',\n };\n\n /**\n * Constructor\n *\n * Creates an instance\n *\n * @param {Element} container - the parent element for the form\n * @param {string} formClass full name of the php class that extends \\core_form\\modal , must be in autoloaded location\n */\n constructor(container, formClass) {\n this.formClass = formClass;\n this.container = container;\n\n // Ensure strings required for shortforms are always available.\n getStrings([\n {key: 'collapseall', component: 'moodle'},\n {key: 'expandall', component: 'moodle'}\n ]).catch(Notification.exception);\n\n // Register delegated events handlers in vanilla JS.\n this.container.addEventListener('click', e => {\n if (e.target.matches('form input[type=submit][data-cancel]')) {\n e.preventDefault();\n const event = this.trigger(this.events.CANCEL_BUTTON_PRESSED, e.target);\n if (!event.defaultPrevented) {\n this.processCancelButton();\n }\n } else if (e.target.matches('form input[type=submit][data-no-submit=\"1\"]')) {\n e.preventDefault();\n const event = this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED, e.target);\n if (!event.defaultPrevented) {\n this.processNoSubmitButton(e.target);\n }\n }\n });\n\n this.container.addEventListener('submit', e => {\n if (e.target.matches('form')) {\n e.preventDefault();\n const event = this.trigger(this.events.SUBMIT_BUTTON_PRESSED);\n if (!event.defaultPrevented) {\n this.submitFormAjax();\n }\n }\n });\n }\n\n /**\n * Loads the form via AJAX and shows it inside a given container\n *\n * @param {Object} args\n * @return {Promise}\n * @public\n */\n load(args = null) {\n const formData = new URLSearchParams(Object.entries(args || {}));\n const pendingPromise = new Pending('core_form/dynamicform:load');\n return this.getBody(formData.toString())\n .then((resp) => this.updateForm(resp))\n .then(pendingPromise.resolve);\n }\n\n /**\n * Triggers a custom event\n *\n * @private\n * @param {String} eventName\n * @param {*} detail\n * @param {Boolean} cancelable\n * @return {CustomEvent}\n */\n trigger(eventName, detail = null, cancelable = true) {\n const e = new CustomEvent(eventName, {detail, cancelable});\n this.container.dispatchEvent(e);\n return e;\n }\n\n /**\n * Add listener for an event\n *\n * Example:\n * const dynamicForm = new DynamicForm(...);\n * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => {\n * e.preventDefault();\n * window.console.log(e.detail);\n * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!';\n * });\n */\n addEventListener(...args) {\n this.container.addEventListener(...args);\n }\n\n /**\n * Get form body\n *\n * @param {String} formDataString form data in format of a query string\n * @private\n * @return {Promise}\n */\n getBody(formDataString) {\n return Ajax.call([{\n methodname: 'core_form_dynamic_form',\n args: {\n formdata: formDataString,\n form: this.formClass,\n }\n }])[0]\n .then(response => {\n return {html: response.html, js: Fragment.processCollectedJavascript(response.javascript)};\n });\n }\n\n /**\n * On form submit\n *\n * @param {*} response Response received from the form's \"process\" method\n */\n onSubmitSuccess(response) {\n const event = this.trigger(this.events.FORM_SUBMITTED, response);\n if (event.defaultPrevented) {\n return;\n }\n\n // Default implementation is to remove the form. Event listener should either remove or reload the form\n // since its contents is no longer correct. For example, if an element was created as a result of\n // form submission, the \"id\" in the form would be still zero. Also the server-side validation\n // errors from the previous submission may still be present.\n this.container.innerHTML = '';\n }\n\n /**\n * On exception during form processing\n *\n * @private\n * @param {Object} exception\n */\n onSubmitError(exception) {\n const event = this.trigger(this.events.ERROR, exception);\n if (event.defaultPrevented) {\n return;\n }\n\n Notification.exception(exception);\n }\n\n /**\n * Click on a \"submit\" button that is marked in the form as registerNoSubmitButton()\n *\n * @method submitButtonPressed\n * @param {Element} button that was pressed\n */\n processNoSubmitButton(button) {\n const pendingPromise = new Pending('core_form/dynamicform:nosubmit');\n const form = this.container.querySelector('form');\n const formData = new URLSearchParams([...(new FormData(form)).entries()]);\n formData.append(button.getAttribute('name'), button.getAttribute('value'));\n\n this.notifyFormSubmitAjax(true)\n .then(() => {\n // Add the button name to the form data and submit it.\n this.disableButtons();\n return this.getBody(formData.toString());\n })\n .then((resp) => this.updateForm(resp))\n .finally(pendingPromise.resolve)\n .catch(this.onSubmitError);\n }\n\n /**\n * Wrapper for Event.notifyFormSubmitAjax that waits for the module to load\n *\n * We often destroy the form right after calling this function and we need to make sure that it actually\n * completes before it, or otherwise it will try to work with a form that does not exist.\n *\n * @param {Boolean} skipValidation\n * @return {Promise}\n */\n notifyFormSubmitAjax(skipValidation = false) {\n const form = this.container.querySelector('form');\n return new Promise(resolve => {\n Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', function() {\n Event.notifyFormSubmitAjax(form, skipValidation);\n resolve();\n });\n });\n }\n\n /**\n * Notifies listeners that form dirty state should be reset.\n *\n * @return {Promise}\n */\n notifyResetFormChanges() {\n const form = this.container.querySelector('form');\n return new Promise(resolve => {\n Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => {\n Event.notifyFormSubmitAjax(form, true);\n M.core_formchangechecker.reset_form_dirty_state();\n resolve();\n });\n });\n }\n\n /**\n * Click on a \"cancel\" button\n */\n processCancelButton() {\n // Notify listeners that the form is about to be submitted (this will reset atto autosave).\n this.notifyResetFormChanges()\n .then(() => {\n const event = this.trigger(this.events.FORM_CANCELLED);\n if (!event.defaultPrevented) {\n // By default removes the form from the DOM.\n this.container.innerHTML = '';\n }\n return null;\n })\n .catch(null);\n }\n\n /**\n * Update form contents\n *\n * @param {string} html\n * @param {string} js\n */\n updateForm({html, js}) {\n Templates.replaceNodeContents(this.container, html, js);\n }\n\n /**\n * Validate form elements\n * @return {Promise} promise that returns true if client-side validation has passed, false if there are errors\n */\n validateElements() {\n // Notify listeners that the form is about to be submitted (this will reset atto autosave).\n return this.notifyFormSubmitAjax()\n .then(() => {\n // Now the change events have run, see if there are any \"invalid\" form fields.\n const invalid = [...this.container.querySelectorAll('[aria-invalid=\"true\"], .error')];\n\n // If we found invalid fields, focus on the first one and do not submit via ajax.\n if (invalid.length) {\n invalid[0].focus();\n return false;\n }\n\n return true;\n });\n }\n\n /**\n * Disable buttons during form submission\n */\n disableButtons() {\n this.container.querySelectorAll('form input[type=\"submit\"]')\n .forEach(el => el.setAttribute('disabled', true));\n }\n\n /**\n * Enable buttons after form submission (on validation error)\n */\n enableButtons() {\n this.container.querySelectorAll('form input[type=\"submit\"]')\n .forEach(el => el.removeAttribute('disabled'));\n }\n\n /**\n * Submit the form via AJAX call to the core_form_dynamic_form WS\n */\n async submitFormAjax() {\n // If we found invalid fields, focus on the first one and do not submit via ajax.\n if (!(await this.validateElements())) {\n this.trigger(this.events.CLIENT_VALIDATION_ERROR, null, false);\n return;\n }\n this.disableButtons();\n\n // Convert all the form elements values to a serialised string.\n const form = this.container.querySelector('form');\n const formData = new URLSearchParams([...(new FormData(form)).entries()]);\n\n // Now we can continue...\n Ajax.call([{\n methodname: 'core_form_dynamic_form',\n args: {\n formdata: formData.toString(),\n form: this.formClass\n }\n }])[0]\n .then((response) => {\n if (!response.submitted) {\n // Form was not submitted, it could be either because validation failed or because no-submit button was pressed.\n this.updateForm({html: response.html, js: Fragment.processCollectedJavascript(response.javascript)});\n this.enableButtons();\n this.trigger(this.events.SERVER_VALIDATION_ERROR, null, false);\n } else {\n // Form was submitted properly.\n const data = JSON.parse(response.data);\n this.enableButtons();\n this.notifyResetFormChanges()\n .then(() => this.onSubmitSuccess(data))\n .catch();\n }\n return null;\n })\n .catch(this.onSubmitError);\n }\n}\n"],"file":"dynamicform.min.js"} \ No newline at end of file diff --git a/lib/form/amd/build/modalform.min.js b/lib/form/amd/build/modalform.min.js new file mode 100644 index 00000000000..2d8efbae64e --- /dev/null +++ b/lib/form/amd/build/modalform.min.js @@ -0,0 +1,2 @@ +define ("core_form/modalform",["exports","core/modal_factory","core/modal_events","core/ajax","core/notification","core/yui","core/event","core/fragment","core/pending"],function(a,b,c,d,e,f,g,h,i){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.default=void 0;b=j(b);c=j(c);d=j(d);e=j(e);f=j(f);g=j(g);h=j(h);i=j(i);function j(a){return a&&a.__esModule?a:{default:a}}function k(a,b,c,d,e,f,g){try{var h=a[f](g),i=h.value}catch(a){c(a);return}if(h.done){b(i)}else{Promise.resolve(i).then(d,e)}}function l(a){return function(){var b=this,c=arguments;return new Promise(function(d,e){var h=a.apply(b,c);function f(a){k(h,d,e,f,g,"next",a)}function g(a){k(h,d,e,f,g,"throw",a)}f(void 0)})}}function m(a){return q(a)||p(a)||o(a)||n()}function n(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(a,b){if(!a)return;if("string"==typeof a)return r(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);if("Object"===c&&a.constructor)c=a.constructor.name;if("Map"===c||"Set"===c)return Array.from(c);if("Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c))return r(a,b)}function p(a){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(a))return Array.from(a)}function q(a){if(Array.isArray(a))return r(a)}function r(a,b){if(null==b||b>a.length)b=a.length;for(var c=0,d=Array(b);c.\n\n/**\n * Display a form in a modal dialogue\n *\n * Example:\n * import ModalForm from 'core_form/modalform';\n *\n * const modalForm = new ModalForm({\n * formClass: 'pluginname\\\\form\\\\formname',\n * modalConfig: {title: 'Here comes the title'},\n * args: {categoryid: 123},\n * returnFocus: e.target,\n * });\n * modalForm.addEventListener(modalForm.events.FORM_SUBMITTED, (c) => window.console.log(c.detail));\n * modalForm.show();\n *\n * See also https://docs.moodle.org/dev/Modal_and_AJAX_forms\n *\n * @module core_form/modalform\n * @package core_form\n * @copyright 2018 Mitxel Moriana \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport ModalFactory from 'core/modal_factory';\nimport ModalEvents from 'core/modal_events';\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport Y from 'core/yui';\nimport Event from 'core/event';\nimport Fragment from 'core/fragment';\nimport Pending from 'core/pending';\n\nexport default class ModalForm {\n\n /**\n * Various events that can be observed.\n *\n * @type {Object}\n */\n events = {\n // Form was successfully submitted - the response is passed to the event listener.\n // Cancellable (but it's hardly ever needed to cancel this event).\n FORM_SUBMITTED: 'core_form_modalform_formsubmitted',\n // Cancel button was pressed.\n // Cancellable (but it's hardly ever needed to cancel this event).\n FORM_CANCELLED: 'core_form_modalform_formcancelled',\n // User attempted to submit the form but there was client-side validation error.\n CLIENT_VALIDATION_ERROR: 'core_form_modalform_clientvalidationerror',\n // User attempted to submit the form but server returned validation error.\n SERVER_VALIDATION_ERROR: 'core_form_modalform_validationerror',\n // Error occurred while performing request to the server.\n // Cancellable (by default calls Notification.exception).\n ERROR: 'core_form_modalform_error',\n // Right after user pressed no-submit button,\n // listen to this event if you want to add JS validation or processing for no-submit button.\n // Cancellable.\n NOSUBMIT_BUTTON_PRESSED: 'core_form_modalform_nosubmitbutton',\n // Right after user pressed submit button,\n // listen to this event if you want to add additional JS validation or confirmation dialog.\n // Cancellable.\n SUBMIT_BUTTON_PRESSED: 'core_form_modalform_submitbutton',\n // Right after user pressed cancel button,\n // listen to this event if you want to add confirmation dialog.\n // Cancellable.\n CANCEL_BUTTON_PRESSED: 'core_form_modalform_cancelbutton',\n // Modal was loaded and this.modal is available (but the form content may not be loaded yet).\n LOADED: 'core_form_modalform_loaded',\n };\n\n /**\n * Constructor\n *\n * Shows the required form inside a modal dialogue\n *\n * @param {Object} config parameters for the form and modal dialogue:\n * @property {String} config.formClass PHP class name that handles the form (should extend \\core_form\\modal )\n * @property {Object} config.modalConfig modal config - title, type, etc.\n * Default: {removeOnClose: true, type: ModalFactory.types.SAVE_CANCEL}\n * @property {Object} config.args Arguments for the initial form rendering (for example, id of the edited entity)\n * @property {String} config.saveButtonText the text to display on the Modal \"Save\" button (optional)\n * @property {String} config.saveButtonClasses additional CSS classes for the Modal \"Save\" button\n * @property {HTMLElement} config.returnFocus element to return focus to after the dialogue is closed\n */\n constructor(config) {\n this.modal = null;\n this.config = config;\n this.config.modalConfig = {\n removeOnClose: true,\n type: ModalFactory.types.SAVE_CANCEL,\n large: true,\n ...(this.config.modalConfig || {}),\n };\n this.config.args = this.config.args || {};\n this.futureListeners = [];\n }\n\n /**\n * Initialise the modal and shows it\n *\n * @return {Promise}\n */\n show() {\n const pendingPromise = new Pending('core_form/modalform:init');\n return ModalFactory.create(this.config.modalConfig)\n .then((modal) => {\n this.modal = modal;\n\n // Retrieve the form and set the modal body. We can not set the body in the modalConfig,\n // we need to make sure that the modal already exists when we render the form. Some form elements\n // such as date_selector inspect the existing elements on the page to find the highest z-index.\n const formParams = new URLSearchParams(Object.entries(this.config.args || {}));\n this.modal.setBodyContent(this.getBody(formParams.toString()));\n\n // After successfull submit, when we press \"Cancel\" or close the dialogue by clicking on X in the top right corner.\n this.modal.getRoot().on(ModalEvents.hidden, () => {\n this.notifyResetFormChanges()\n .then(() => {\n this.modal.destroy();\n // Focus on the element that actually launched the modal.\n if (this.config.returnFocus) {\n this.config.returnFocus.focus();\n }\n return null;\n })\n .catch(() => null);\n });\n\n // Add the class to the modal dialogue.\n this.modal.getModal().addClass('modal-form-dialogue');\n\n // We catch the press on submit buttons in the forms.\n this.modal.getRoot().on('click', 'form input[type=submit][data-no-submit]',\n (e) => {\n e.preventDefault();\n const event = this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED, e.target);\n if (!event.defaultPrevented) {\n this.processNoSubmitButton(e.target);\n }\n });\n\n // We catch the form submit event and use it to submit the form with ajax.\n this.modal.getRoot().on('submit', 'form', (e) => {\n e.preventDefault();\n const event = this.trigger(this.events.SUBMIT_BUTTON_PRESSED);\n if (!event.defaultPrevented) {\n this.submitFormAjax();\n }\n });\n\n // Change the text for the save button.\n if (typeof this.config.saveButtonText !== 'undefined' &&\n typeof this.modal.setSaveButtonText !== 'undefined') {\n this.modal.setSaveButtonText(this.config.saveButtonText);\n }\n // Set classes for the save button.\n if (typeof this.config.saveButtonClasses !== 'undefined') {\n this.setSaveButtonClasses(this.config.saveButtonClasses);\n }\n // When Save button is pressed - submit the form.\n this.modal.getRoot().on(ModalEvents.save, (e) => {\n e.preventDefault();\n this.modal.getRoot().find('form').submit();\n });\n\n // When Cancel button is pressed - allow to intercept.\n this.modal.getRoot().on(ModalEvents.cancel, (e) => {\n const event = this.trigger(this.events.CANCEL_BUTTON_PRESSED);\n if (event.defaultPrevented) {\n e.preventDefault();\n }\n });\n this.futureListeners.forEach(args => this.modal.getRoot()[0].addEventListener(...args));\n this.futureListeners = [];\n this.trigger(this.events.LOADED, null, false);\n return this.modal.show();\n })\n .then(pendingPromise.resolve);\n }\n\n /**\n * Triggers a custom event\n *\n * @private\n * @param {String} eventName\n * @param {*} detail\n * @param {Boolean} cancelable\n * @return {CustomEvent}\n */\n trigger(eventName, detail = null, cancelable = true) {\n const e = new CustomEvent(eventName, {detail, cancelable});\n this.modal.getRoot()[0].dispatchEvent(e);\n return e;\n }\n\n /**\n * Add listener for an event\n *\n * Example:\n * const modalForm = new ModalForm(...);\n * dynamicForm.addEventListener(modalForm.events.FORM_SUBMITTED, e => {\n * window.console.log(e.detail);\n * });\n */\n addEventListener(...args) {\n if (!this.modal) {\n this.futureListeners.push(args);\n } else {\n this.modal.getRoot()[0].addEventListener(...args);\n }\n }\n\n /**\n * Get form contents (to be used in ModalForm.setBodyContent())\n *\n * @param {String} formDataString form data in format of a query string\n * @method getBody\n * @private\n * @return {Promise}\n */\n getBody(formDataString) {\n const params = {\n formdata: formDataString,\n form: this.config.formClass\n };\n const pendingPromise = new Pending('core_form/modalform:form_body');\n return Ajax.call([{\n methodname: 'core_form_dynamic_form',\n args: params\n }])[0]\n .then(response => {\n pendingPromise.resolve();\n return {html: response.html, js: Fragment.processCollectedJavascript(response.javascript)};\n });\n }\n\n /**\n * On exception during form processing. Caller may override\n *\n * @param {Object} exception\n */\n onSubmitError(exception) {\n const event = this.trigger(this.events.ERROR, exception);\n if (event.defaultPrevented) {\n return;\n }\n\n Notification.exception(exception);\n }\n\n /**\n * Notifies listeners that form dirty state should be reset.\n *\n * @return {Promise}\n */\n notifyResetFormChanges() {\n return new Promise(resolve => {\n Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => {\n Event.notifyFormSubmitAjax(this.modal.getRoot().find('form')[0], true);\n M.core_formchangechecker.reset_form_dirty_state();\n resolve();\n });\n });\n }\n\n /**\n * Wrapper for Event.notifyFormSubmitAjax that waits for the module to load\n *\n * We often destroy the form right after calling this function and we need to make sure that it actually\n * completes before it, or otherwise it will try to work with a form that does not exist.\n *\n * @param {Boolean} skipValidation\n * @return {Promise}\n */\n notifyFormSubmitAjax(skipValidation = false) {\n return new Promise(resolve => {\n Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => {\n Event.notifyFormSubmitAjax(this.modal.getRoot().find('form')[0], skipValidation);\n resolve();\n });\n });\n }\n\n /**\n * Click on a \"submit\" button that is marked in the form as registerNoSubmitButton()\n *\n * @param {Element} button button that was pressed\n */\n processNoSubmitButton(button) {\n this.notifyFormSubmitAjax(true)\n .then(() => {\n // Add the button name to the form data and submit it.\n let formData = this.modal.getRoot().find('form').serialize();\n formData = formData + '&' + encodeURIComponent(button.getAttribute('name')) + '=' +\n encodeURIComponent(button.getAttribute('value'));\n this.modal.setBodyContent(this.getBody(formData));\n return null;\n })\n .catch(null);\n }\n\n /**\n * Validate form elements\n * @return {Promise} promise that returns true if client-side validation has passed, false if there are errors\n */\n validateElements() {\n return this.notifyFormSubmitAjax()\n .then(() => {\n // Now the change events have run, see if there are any \"invalid\" form fields.\n /** @var {jQuery} list of elements with errors */\n const invalid = this.modal.getRoot().find('[aria-invalid=\"true\"], .error');\n\n // If we found invalid fields, focus on the first one and do not submit via ajax.\n if (invalid.length) {\n invalid.first().focus();\n return false;\n }\n\n return true;\n });\n }\n\n /**\n * Disable buttons during form submission\n */\n disableButtons() {\n this.modal.getFooter().find('[data-action]').attr('disabled', true);\n }\n\n /**\n * Enable buttons after form submission (on validation error)\n */\n enableButtons() {\n this.modal.getFooter().find('[data-action]').removeAttr('disabled');\n }\n\n /**\n * Submit the form via AJAX call to the core_form_dynamic_form WS\n */\n async submitFormAjax() {\n // If we found invalid fields, focus on the first one and do not submit via ajax.\n if (!await this.validateElements()) {\n this.trigger(this.events.CLIENT_VALIDATION_ERROR, null, false);\n return;\n }\n this.disableButtons();\n\n // Convert all the form elements values to a serialised string.\n const formData = this.modal.getRoot().find('form').serialize();\n\n // Now we can continue...\n Ajax.call([{\n methodname: 'core_form_dynamic_form',\n args: {\n formdata: formData,\n form: this.config.formClass\n }\n }])[0]\n .then((response) => {\n if (!response.submitted) {\n // Form was not submitted because validation failed.\n const promise = new Promise(\n resolve => resolve({html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}));\n this.modal.setBodyContent(promise);\n this.enableButtons();\n this.trigger(this.events.SERVER_VALIDATION_ERROR);\n } else {\n // Form was submitted properly. Hide the modal and execute callback.\n const data = JSON.parse(response.data);\n const event = this.trigger(this.events.FORM_SUBMITTED, data);\n if (!event.defaultPrevented) {\n this.modal.hide();\n }\n return null;\n }\n return null;\n })\n .catch(this.onSubmitError);\n }\n\n /**\n * Set the classes for the 'save' button.\n *\n * @method setSaveButtonClasses\n * @param {(String)} value The 'save' button classes.\n */\n setSaveButtonClasses(value) {\n const button = this.modal.getFooter().find(\"[data-action='save']\");\n if (!button) {\n throw new Error(\"Unable to find the 'save' button\");\n }\n button.removeClass().addClass(value);\n }\n}\n"],"file":"modalform.min.js"} \ No newline at end of file diff --git a/lib/form/amd/src/dynamicform.js b/lib/form/amd/src/dynamicform.js new file mode 100644 index 00000000000..f8332c3b682 --- /dev/null +++ b/lib/form/amd/src/dynamicform.js @@ -0,0 +1,389 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/** + * Display an embedded form, it is only loaded and reloaded inside its container + * + * Example: + * import DynamicForm from 'core_form/dynamicform'; + * + * const dynamicForm = new DynamicForm(document.querySelector('#mycontainer', 'pluginname\\form\\formname'); + * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => { + * e.preventDefault(); + * window.console.log(e.detail); + * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!'; + * }); + * dynamicForm.load(); + * + * See also https://docs.moodle.org/dev/Modal_and_AJAX_forms + * + * @module core_form/dynamicform + * @package core_form + * @copyright 2019 Marina Glancy + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +import Ajax from 'core/ajax'; +import Notification from 'core/notification'; +import Templates from 'core/templates'; +import Event from 'core/event'; +import {get_strings as getStrings} from 'core/str'; +import Y from 'core/yui'; +import Fragment from 'core/fragment'; +import Pending from 'core/pending'; + +export default class DynamicForm { + + /** + * Various events that can be observed. + * + * @type {Object} + */ + events = { + // Form was successfully submitted - the response is passed to the event listener. + // Cancellable (in order to prevent default behavior to clear the container). + FORM_SUBMITTED: 'core_form_dynamicform_formsubmitted', + // Cancel button was pressed. + // Cancellable (in order to prevent default behavior to clear the container). + FORM_CANCELLED: 'core_form_dynamicform_formcancelled', + // User attempted to submit the form but there was client-side validation error. + CLIENT_VALIDATION_ERROR: 'core_form_dynamicform_clientvalidationerror', + // User attempted to submit the form but server returned validation error. + SERVER_VALIDATION_ERROR: 'core_form_dynamicform_validationerror', + // Error occurred while performing request to the server. + // Cancellable (by default calls Notification.exception). + ERROR: 'core_form_dynamicform_error', + // Right after user pressed no-submit button, + // listen to this event if you want to add JS validation or processing for no-submit button. + // Cancellable. + NOSUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_nosubmitbutton', + // Right after user pressed submit button, + // listen to this event if you want to add additional JS validation or confirmation dialog. + // Cancellable. + SUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_submitbutton', + // Right after user pressed cancel button, + // listen to this event if you want to add confirmation dialog. + // Cancellable. + CANCEL_BUTTON_PRESSED: 'core_form_dynamicform_cancelbutton', + }; + + /** + * Constructor + * + * Creates an instance + * + * @param {Element} container - the parent element for the form + * @param {string} formClass full name of the php class that extends \core_form\modal , must be in autoloaded location + */ + constructor(container, formClass) { + this.formClass = formClass; + this.container = container; + + // Ensure strings required for shortforms are always available. + getStrings([ + {key: 'collapseall', component: 'moodle'}, + {key: 'expandall', component: 'moodle'} + ]).catch(Notification.exception); + + // Register delegated events handlers in vanilla JS. + this.container.addEventListener('click', e => { + if (e.target.matches('form input[type=submit][data-cancel]')) { + e.preventDefault(); + const event = this.trigger(this.events.CANCEL_BUTTON_PRESSED, e.target); + if (!event.defaultPrevented) { + this.processCancelButton(); + } + } else if (e.target.matches('form input[type=submit][data-no-submit="1"]')) { + e.preventDefault(); + const event = this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED, e.target); + if (!event.defaultPrevented) { + this.processNoSubmitButton(e.target); + } + } + }); + + this.container.addEventListener('submit', e => { + if (e.target.matches('form')) { + e.preventDefault(); + const event = this.trigger(this.events.SUBMIT_BUTTON_PRESSED); + if (!event.defaultPrevented) { + this.submitFormAjax(); + } + } + }); + } + + /** + * Loads the form via AJAX and shows it inside a given container + * + * @param {Object} args + * @return {Promise} + * @public + */ + load(args = null) { + const formData = new URLSearchParams(Object.entries(args || {})); + const pendingPromise = new Pending('core_form/dynamicform:load'); + return this.getBody(formData.toString()) + .then((resp) => this.updateForm(resp)) + .then(pendingPromise.resolve); + } + + /** + * Triggers a custom event + * + * @private + * @param {String} eventName + * @param {*} detail + * @param {Boolean} cancelable + * @return {CustomEvent} + */ + trigger(eventName, detail = null, cancelable = true) { + const e = new CustomEvent(eventName, {detail, cancelable}); + this.container.dispatchEvent(e); + return e; + } + + /** + * Add listener for an event + * + * Example: + * const dynamicForm = new DynamicForm(...); + * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => { + * e.preventDefault(); + * window.console.log(e.detail); + * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!'; + * }); + */ + addEventListener(...args) { + this.container.addEventListener(...args); + } + + /** + * Get form body + * + * @param {String} formDataString form data in format of a query string + * @private + * @return {Promise} + */ + getBody(formDataString) { + return Ajax.call([{ + methodname: 'core_form_dynamic_form', + args: { + formdata: formDataString, + form: this.formClass, + } + }])[0] + .then(response => { + return {html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}; + }); + } + + /** + * On form submit + * + * @param {*} response Response received from the form's "process" method + */ + onSubmitSuccess(response) { + const event = this.trigger(this.events.FORM_SUBMITTED, response); + if (event.defaultPrevented) { + return; + } + + // Default implementation is to remove the form. Event listener should either remove or reload the form + // since its contents is no longer correct. For example, if an element was created as a result of + // form submission, the "id" in the form would be still zero. Also the server-side validation + // errors from the previous submission may still be present. + this.container.innerHTML = ''; + } + + /** + * On exception during form processing + * + * @private + * @param {Object} exception + */ + onSubmitError(exception) { + const event = this.trigger(this.events.ERROR, exception); + if (event.defaultPrevented) { + return; + } + + Notification.exception(exception); + } + + /** + * Click on a "submit" button that is marked in the form as registerNoSubmitButton() + * + * @method submitButtonPressed + * @param {Element} button that was pressed + */ + processNoSubmitButton(button) { + const pendingPromise = new Pending('core_form/dynamicform:nosubmit'); + const form = this.container.querySelector('form'); + const formData = new URLSearchParams([...(new FormData(form)).entries()]); + formData.append(button.getAttribute('name'), button.getAttribute('value')); + + this.notifyFormSubmitAjax(true) + .then(() => { + // Add the button name to the form data and submit it. + this.disableButtons(); + return this.getBody(formData.toString()); + }) + .then((resp) => this.updateForm(resp)) + .finally(pendingPromise.resolve) + .catch(this.onSubmitError); + } + + /** + * Wrapper for Event.notifyFormSubmitAjax that waits for the module to load + * + * We often destroy the form right after calling this function and we need to make sure that it actually + * completes before it, or otherwise it will try to work with a form that does not exist. + * + * @param {Boolean} skipValidation + * @return {Promise} + */ + notifyFormSubmitAjax(skipValidation = false) { + const form = this.container.querySelector('form'); + return new Promise(resolve => { + Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', function() { + Event.notifyFormSubmitAjax(form, skipValidation); + resolve(); + }); + }); + } + + /** + * Notifies listeners that form dirty state should be reset. + * + * @return {Promise} + */ + notifyResetFormChanges() { + const form = this.container.querySelector('form'); + return new Promise(resolve => { + Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => { + Event.notifyFormSubmitAjax(form, true); + M.core_formchangechecker.reset_form_dirty_state(); + resolve(); + }); + }); + } + + /** + * Click on a "cancel" button + */ + processCancelButton() { + // Notify listeners that the form is about to be submitted (this will reset atto autosave). + this.notifyResetFormChanges() + .then(() => { + const event = this.trigger(this.events.FORM_CANCELLED); + if (!event.defaultPrevented) { + // By default removes the form from the DOM. + this.container.innerHTML = ''; + } + return null; + }) + .catch(null); + } + + /** + * Update form contents + * + * @param {string} html + * @param {string} js + */ + updateForm({html, js}) { + Templates.replaceNodeContents(this.container, html, js); + } + + /** + * Validate form elements + * @return {Promise} promise that returns true if client-side validation has passed, false if there are errors + */ + validateElements() { + // Notify listeners that the form is about to be submitted (this will reset atto autosave). + return this.notifyFormSubmitAjax() + .then(() => { + // Now the change events have run, see if there are any "invalid" form fields. + const invalid = [...this.container.querySelectorAll('[aria-invalid="true"], .error')]; + + // If we found invalid fields, focus on the first one and do not submit via ajax. + if (invalid.length) { + invalid[0].focus(); + return false; + } + + return true; + }); + } + + /** + * Disable buttons during form submission + */ + disableButtons() { + this.container.querySelectorAll('form input[type="submit"]') + .forEach(el => el.setAttribute('disabled', true)); + } + + /** + * Enable buttons after form submission (on validation error) + */ + enableButtons() { + this.container.querySelectorAll('form input[type="submit"]') + .forEach(el => el.removeAttribute('disabled')); + } + + /** + * Submit the form via AJAX call to the core_form_dynamic_form WS + */ + async submitFormAjax() { + // If we found invalid fields, focus on the first one and do not submit via ajax. + if (!(await this.validateElements())) { + this.trigger(this.events.CLIENT_VALIDATION_ERROR, null, false); + return; + } + this.disableButtons(); + + // Convert all the form elements values to a serialised string. + const form = this.container.querySelector('form'); + const formData = new URLSearchParams([...(new FormData(form)).entries()]); + + // Now we can continue... + Ajax.call([{ + methodname: 'core_form_dynamic_form', + args: { + formdata: formData.toString(), + form: this.formClass + } + }])[0] + .then((response) => { + if (!response.submitted) { + // Form was not submitted, it could be either because validation failed or because no-submit button was pressed. + this.updateForm({html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}); + this.enableButtons(); + this.trigger(this.events.SERVER_VALIDATION_ERROR, null, false); + } else { + // Form was submitted properly. + const data = JSON.parse(response.data); + this.enableButtons(); + this.notifyResetFormChanges() + .then(() => this.onSubmitSuccess(data)) + .catch(); + } + return null; + }) + .catch(this.onSubmitError); + } +} diff --git a/lib/form/amd/src/modalform.js b/lib/form/amd/src/modalform.js new file mode 100644 index 00000000000..3b011f76a5a --- /dev/null +++ b/lib/form/amd/src/modalform.js @@ -0,0 +1,408 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/** + * Display a form in a modal dialogue + * + * Example: + * import ModalForm from 'core_form/modalform'; + * + * const modalForm = new ModalForm({ + * formClass: 'pluginname\\form\\formname', + * modalConfig: {title: 'Here comes the title'}, + * args: {categoryid: 123}, + * returnFocus: e.target, + * }); + * modalForm.addEventListener(modalForm.events.FORM_SUBMITTED, (c) => window.console.log(c.detail)); + * modalForm.show(); + * + * See also https://docs.moodle.org/dev/Modal_and_AJAX_forms + * + * @module core_form/modalform + * @package core_form + * @copyright 2018 Mitxel Moriana + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +import ModalFactory from 'core/modal_factory'; +import ModalEvents from 'core/modal_events'; +import Ajax from 'core/ajax'; +import Notification from 'core/notification'; +import Y from 'core/yui'; +import Event from 'core/event'; +import Fragment from 'core/fragment'; +import Pending from 'core/pending'; + +export default class ModalForm { + + /** + * Various events that can be observed. + * + * @type {Object} + */ + events = { + // Form was successfully submitted - the response is passed to the event listener. + // Cancellable (but it's hardly ever needed to cancel this event). + FORM_SUBMITTED: 'core_form_modalform_formsubmitted', + // Cancel button was pressed. + // Cancellable (but it's hardly ever needed to cancel this event). + FORM_CANCELLED: 'core_form_modalform_formcancelled', + // User attempted to submit the form but there was client-side validation error. + CLIENT_VALIDATION_ERROR: 'core_form_modalform_clientvalidationerror', + // User attempted to submit the form but server returned validation error. + SERVER_VALIDATION_ERROR: 'core_form_modalform_validationerror', + // Error occurred while performing request to the server. + // Cancellable (by default calls Notification.exception). + ERROR: 'core_form_modalform_error', + // Right after user pressed no-submit button, + // listen to this event if you want to add JS validation or processing for no-submit button. + // Cancellable. + NOSUBMIT_BUTTON_PRESSED: 'core_form_modalform_nosubmitbutton', + // Right after user pressed submit button, + // listen to this event if you want to add additional JS validation or confirmation dialog. + // Cancellable. + SUBMIT_BUTTON_PRESSED: 'core_form_modalform_submitbutton', + // Right after user pressed cancel button, + // listen to this event if you want to add confirmation dialog. + // Cancellable. + CANCEL_BUTTON_PRESSED: 'core_form_modalform_cancelbutton', + // Modal was loaded and this.modal is available (but the form content may not be loaded yet). + LOADED: 'core_form_modalform_loaded', + }; + + /** + * Constructor + * + * Shows the required form inside a modal dialogue + * + * @param {Object} config parameters for the form and modal dialogue: + * @property {String} config.formClass PHP class name that handles the form (should extend \core_form\modal ) + * @property {Object} config.modalConfig modal config - title, type, etc. + * Default: {removeOnClose: true, type: ModalFactory.types.SAVE_CANCEL} + * @property {Object} config.args Arguments for the initial form rendering (for example, id of the edited entity) + * @property {String} config.saveButtonText the text to display on the Modal "Save" button (optional) + * @property {String} config.saveButtonClasses additional CSS classes for the Modal "Save" button + * @property {HTMLElement} config.returnFocus element to return focus to after the dialogue is closed + */ + constructor(config) { + this.modal = null; + this.config = config; + this.config.modalConfig = { + removeOnClose: true, + type: ModalFactory.types.SAVE_CANCEL, + large: true, + ...(this.config.modalConfig || {}), + }; + this.config.args = this.config.args || {}; + this.futureListeners = []; + } + + /** + * Initialise the modal and shows it + * + * @return {Promise} + */ + show() { + const pendingPromise = new Pending('core_form/modalform:init'); + return ModalFactory.create(this.config.modalConfig) + .then((modal) => { + this.modal = modal; + + // Retrieve the form and set the modal body. We can not set the body in the modalConfig, + // we need to make sure that the modal already exists when we render the form. Some form elements + // such as date_selector inspect the existing elements on the page to find the highest z-index. + const formParams = new URLSearchParams(Object.entries(this.config.args || {})); + this.modal.setBodyContent(this.getBody(formParams.toString())); + + // After successfull submit, when we press "Cancel" or close the dialogue by clicking on X in the top right corner. + this.modal.getRoot().on(ModalEvents.hidden, () => { + this.notifyResetFormChanges() + .then(() => { + this.modal.destroy(); + // Focus on the element that actually launched the modal. + if (this.config.returnFocus) { + this.config.returnFocus.focus(); + } + return null; + }) + .catch(() => null); + }); + + // Add the class to the modal dialogue. + this.modal.getModal().addClass('modal-form-dialogue'); + + // We catch the press on submit buttons in the forms. + this.modal.getRoot().on('click', 'form input[type=submit][data-no-submit]', + (e) => { + e.preventDefault(); + const event = this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED, e.target); + if (!event.defaultPrevented) { + this.processNoSubmitButton(e.target); + } + }); + + // We catch the form submit event and use it to submit the form with ajax. + this.modal.getRoot().on('submit', 'form', (e) => { + e.preventDefault(); + const event = this.trigger(this.events.SUBMIT_BUTTON_PRESSED); + if (!event.defaultPrevented) { + this.submitFormAjax(); + } + }); + + // Change the text for the save button. + if (typeof this.config.saveButtonText !== 'undefined' && + typeof this.modal.setSaveButtonText !== 'undefined') { + this.modal.setSaveButtonText(this.config.saveButtonText); + } + // Set classes for the save button. + if (typeof this.config.saveButtonClasses !== 'undefined') { + this.setSaveButtonClasses(this.config.saveButtonClasses); + } + // When Save button is pressed - submit the form. + this.modal.getRoot().on(ModalEvents.save, (e) => { + e.preventDefault(); + this.modal.getRoot().find('form').submit(); + }); + + // When Cancel button is pressed - allow to intercept. + this.modal.getRoot().on(ModalEvents.cancel, (e) => { + const event = this.trigger(this.events.CANCEL_BUTTON_PRESSED); + if (event.defaultPrevented) { + e.preventDefault(); + } + }); + this.futureListeners.forEach(args => this.modal.getRoot()[0].addEventListener(...args)); + this.futureListeners = []; + this.trigger(this.events.LOADED, null, false); + return this.modal.show(); + }) + .then(pendingPromise.resolve); + } + + /** + * Triggers a custom event + * + * @private + * @param {String} eventName + * @param {*} detail + * @param {Boolean} cancelable + * @return {CustomEvent} + */ + trigger(eventName, detail = null, cancelable = true) { + const e = new CustomEvent(eventName, {detail, cancelable}); + this.modal.getRoot()[0].dispatchEvent(e); + return e; + } + + /** + * Add listener for an event + * + * Example: + * const modalForm = new ModalForm(...); + * dynamicForm.addEventListener(modalForm.events.FORM_SUBMITTED, e => { + * window.console.log(e.detail); + * }); + */ + addEventListener(...args) { + if (!this.modal) { + this.futureListeners.push(args); + } else { + this.modal.getRoot()[0].addEventListener(...args); + } + } + + /** + * Get form contents (to be used in ModalForm.setBodyContent()) + * + * @param {String} formDataString form data in format of a query string + * @method getBody + * @private + * @return {Promise} + */ + getBody(formDataString) { + const params = { + formdata: formDataString, + form: this.config.formClass + }; + const pendingPromise = new Pending('core_form/modalform:form_body'); + return Ajax.call([{ + methodname: 'core_form_dynamic_form', + args: params + }])[0] + .then(response => { + pendingPromise.resolve(); + return {html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}; + }); + } + + /** + * On exception during form processing. Caller may override + * + * @param {Object} exception + */ + onSubmitError(exception) { + const event = this.trigger(this.events.ERROR, exception); + if (event.defaultPrevented) { + return; + } + + Notification.exception(exception); + } + + /** + * Notifies listeners that form dirty state should be reset. + * + * @return {Promise} + */ + notifyResetFormChanges() { + return new Promise(resolve => { + Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => { + Event.notifyFormSubmitAjax(this.modal.getRoot().find('form')[0], true); + M.core_formchangechecker.reset_form_dirty_state(); + resolve(); + }); + }); + } + + /** + * Wrapper for Event.notifyFormSubmitAjax that waits for the module to load + * + * We often destroy the form right after calling this function and we need to make sure that it actually + * completes before it, or otherwise it will try to work with a form that does not exist. + * + * @param {Boolean} skipValidation + * @return {Promise} + */ + notifyFormSubmitAjax(skipValidation = false) { + return new Promise(resolve => { + Y.use('event', 'moodle-core-event', 'moodle-core-formchangechecker', () => { + Event.notifyFormSubmitAjax(this.modal.getRoot().find('form')[0], skipValidation); + resolve(); + }); + }); + } + + /** + * Click on a "submit" button that is marked in the form as registerNoSubmitButton() + * + * @param {Element} button button that was pressed + */ + processNoSubmitButton(button) { + this.notifyFormSubmitAjax(true) + .then(() => { + // Add the button name to the form data and submit it. + let formData = this.modal.getRoot().find('form').serialize(); + formData = formData + '&' + encodeURIComponent(button.getAttribute('name')) + '=' + + encodeURIComponent(button.getAttribute('value')); + this.modal.setBodyContent(this.getBody(formData)); + return null; + }) + .catch(null); + } + + /** + * Validate form elements + * @return {Promise} promise that returns true if client-side validation has passed, false if there are errors + */ + validateElements() { + return this.notifyFormSubmitAjax() + .then(() => { + // Now the change events have run, see if there are any "invalid" form fields. + /** @var {jQuery} list of elements with errors */ + const invalid = this.modal.getRoot().find('[aria-invalid="true"], .error'); + + // If we found invalid fields, focus on the first one and do not submit via ajax. + if (invalid.length) { + invalid.first().focus(); + return false; + } + + return true; + }); + } + + /** + * Disable buttons during form submission + */ + disableButtons() { + this.modal.getFooter().find('[data-action]').attr('disabled', true); + } + + /** + * Enable buttons after form submission (on validation error) + */ + enableButtons() { + this.modal.getFooter().find('[data-action]').removeAttr('disabled'); + } + + /** + * Submit the form via AJAX call to the core_form_dynamic_form WS + */ + async submitFormAjax() { + // If we found invalid fields, focus on the first one and do not submit via ajax. + if (!await this.validateElements()) { + this.trigger(this.events.CLIENT_VALIDATION_ERROR, null, false); + return; + } + this.disableButtons(); + + // Convert all the form elements values to a serialised string. + const formData = this.modal.getRoot().find('form').serialize(); + + // Now we can continue... + Ajax.call([{ + methodname: 'core_form_dynamic_form', + args: { + formdata: formData, + form: this.config.formClass + } + }])[0] + .then((response) => { + if (!response.submitted) { + // Form was not submitted because validation failed. + const promise = new Promise( + resolve => resolve({html: response.html, js: Fragment.processCollectedJavascript(response.javascript)})); + this.modal.setBodyContent(promise); + this.enableButtons(); + this.trigger(this.events.SERVER_VALIDATION_ERROR); + } else { + // Form was submitted properly. Hide the modal and execute callback. + const data = JSON.parse(response.data); + const event = this.trigger(this.events.FORM_SUBMITTED, data); + if (!event.defaultPrevented) { + this.modal.hide(); + } + return null; + } + return null; + }) + .catch(this.onSubmitError); + } + + /** + * Set the classes for the 'save' button. + * + * @method setSaveButtonClasses + * @param {(String)} value The 'save' button classes. + */ + setSaveButtonClasses(value) { + const button = this.modal.getFooter().find("[data-action='save']"); + if (!button) { + throw new Error("Unable to find the 'save' button"); + } + button.removeClass().addClass(value); + } +} diff --git a/lib/form/classes/dynamic_form.php b/lib/form/classes/dynamic_form.php new file mode 100644 index 00000000000..ee328457632 --- /dev/null +++ b/lib/form/classes/dynamic_form.php @@ -0,0 +1,146 @@ +. + +namespace core_form; + +use context; +use moodle_url; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once($CFG->libdir . '/formslib.php'); + +/** + * Class modal + * + * Extend this class to create a form that can be used in a modal dialogue. + * + * @package core_form + * @copyright 2020 Marina Glancy + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class dynamic_form extends \moodleform { + + /** + * Constructor for modal forms can not be overridden, however the same form can be used both in AJAX and normally + * + * @param string $action + * @param array $customdata + * @param string $method + * @param string $target + * @param array $attributes + * @param bool $editable + * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST. + * @param bool $isajaxsubmission whether the form is called from WS and it needs to validate user access and set up context + */ + final public function __construct(?string $action = null, + ?array $customdata = null, + string $method = 'post', + string $target = '', + ?array $attributes = [], + bool $editable = true, + ?array $ajaxformdata = null, + bool $isajaxsubmission = false) { + global $PAGE, $CFG; + $this->_ajaxformdata = $ajaxformdata; + if ($isajaxsubmission) { + require_once($CFG->libdir . '/externallib.php'); + // This form was created from the WS that needs to validate user access to it and set page context. + // It has to be done before calling parent constructor because elements definitions may need to use + // format_string functions and other methods that expect the page to be set up. + \external_api::validate_context($this->get_context_for_dynamic_submission()); + $PAGE->set_url($this->get_page_url_for_dynamic_submission()); + $this->check_access_for_dynamic_submission(); + } + $attributes = ['data-random-ids' => 1] + ($attributes ?: []); + parent::__construct($action, $customdata, $method, $target, $attributes, $editable, $ajaxformdata); + } + + /** + * Returns context where this form is used + * + * This context is validated in {@link \external_api::validate_context()} + * + * If context depends on the form data, it is available in $this->_ajaxformdata or + * by calling $this->optional_param() + * + * Example: + * $cmid = $this->optional_param('cmid', 0, PARAM_INT); + * return context_module::instance($cmid); + * + * @return context + */ + abstract protected function get_context_for_dynamic_submission(): context; + + /** + * Checks if current user has access to this form, otherwise throws exception + * + * Sometimes permission check may depend on the action and/or id of the entity. + * If necessary, form data is available in $this->_ajaxformdata or + * by calling $this->optional_param() + * + * Example: + * require_capability('dosomething', $this->get_context_for_dynamic_submission()); + */ + abstract protected function check_access_for_dynamic_submission(): void; + + /** + * Process the form submission, used if form was submitted via AJAX + * + * This method can return scalar values or arrays that can be json-encoded, they will be passed to the caller JS. + * + * Submission data can be accessed as: $this->get_data() + * + * Example: + * $data = $this->get_data(); + * file_postupdate_standard_filemanager($data, ....); + * api::save_entity($data); // Save into the DB, trigger event, etc. + * + * @return mixed + */ + abstract public function process_dynamic_submission(); + + /** + * Load in existing data as form defaults + * + * Can be overridden to retrieve existing values from db by entity id and also + * to preprocess editor and filemanager elements + * + * Example: + * $id = $this->optional_param('id', 0, PARAM_INT); + * $data = api::get_entity($id); // For example, retrieve a row from the DB. + * file_prepare_standard_filemanager($data, ...); + * $this->set_data($data); + */ + abstract public function set_data_for_dynamic_submission(): void; + + /** + * Returns url to set in $PAGE->set_url() when form is being rendered or submitted via AJAX + * + * This is used in the form elements sensitive to the page url, such as Atto autosave in 'editor' + * + * If the form has arguments (such as 'id' of the element being edited), the URL should + * also have respective argument. + * + * Example: + * $id = $this->optional_param('id', 0, PARAM_INT); + * return new moodle_url('/my/page/where/form/is/used.php', ['id' => $id]); + * + * @return moodle_url + */ + abstract protected function get_page_url_for_dynamic_submission(): moodle_url; +} diff --git a/lib/form/classes/external/modal.php b/lib/form/classes/external/modal.php new file mode 100644 index 00000000000..0663123c8f1 --- /dev/null +++ b/lib/form/classes/external/modal.php @@ -0,0 +1,106 @@ +. + +namespace core_form\external; + +use core_search\engine_exception; +use external_api; +use external_function_parameters; +use external_value; + +defined('MOODLE_INTERNAL') || die(); + +require_once($CFG->libdir.'/externallib.php'); + +/** + * Implements the external functions provided by the core_form subsystem. + * + * @copyright 2020 Marina Glancy + * @package core_form + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class dynamic_form extends external_api { + + /** + * Parameters for modal form + * + * @return external_function_parameters + */ + public static function execute_parameters(): external_function_parameters { + return new external_function_parameters([ + 'form' => new external_value(PARAM_RAW_TRIMMED, 'Form class', VALUE_REQUIRED), + 'formdata' => new external_value(PARAM_RAW, 'url-encoded form data', VALUE_REQUIRED), + ]); + } + + /** + * Submit a form from a modal dialogue. + * + * @param string $formclass + * @param string $formdatastr + * @return array + * @throws \moodle_exception + */ + public static function execute(string $formclass, string $formdatastr): array { + global $PAGE, $OUTPUT; + + $params = self::validate_parameters(self::execute_parameters(), [ + 'form' => $formclass, + 'formdata' => $formdatastr, + ]); + $formclass = $params['form']; + parse_str($params['formdata'], $formdata); + + if (!class_exists($formclass) || !is_subclass_of($formclass, \core_form\dynamic_form::class)) { + // For security reason we don't throw exception "class does not exist" but rather an access exception. + throw new \moodle_exception('nopermissionform', 'core_form'); + } + + /** @var \core_form\dynamic_form $form */ + $form = new $formclass(null, null, 'post', '', [], true, $formdata, true); + $form->set_data_for_dynamic_submission(); + if (!$form->is_cancelled() && $form->is_submitted() && $form->is_validated()) { + // Form was properly submitted, process and return results of processing. No need to render it again. + return ['submitted' => true, 'data' => json_encode($form->process_dynamic_submission())]; + } + + // Render actual form. + + // Hack alert: Forcing bootstrap_renderer to initiate moodle page. + $OUTPUT->header(); + + $PAGE->start_collecting_javascript_requirements(); + $data = $form->render(); + $jsfooter = $PAGE->requires->get_end_code(); + $output = ['submitted' => false, 'html' => $data, 'javascript' => $jsfooter]; + return $output; + } + + /** + * Return for modal + * @return \external_single_structure + */ + public static function execute_returns(): \external_single_structure { + return new \external_single_structure( + array( + 'submitted' => new external_value(PARAM_BOOL, 'If form was submitted and validated'), + 'data' => new external_value(PARAM_RAW, 'JSON-encoded return data from form processing method', VALUE_OPTIONAL), + 'html' => new external_value(PARAM_RAW, 'HTML fragment of the form', VALUE_OPTIONAL), + 'javascript' => new external_value(PARAM_RAW, 'JavaScript fragment of the form', VALUE_OPTIONAL) + ) + ); + } +} diff --git a/lib/form/tests/behat/fixtures/repeat_with_delete_form.php b/lib/form/tests/behat/fixtures/repeat_with_delete_form.php new file mode 100644 index 00000000000..b63adbfd0f0 --- /dev/null +++ b/lib/form/tests/behat/fixtures/repeat_with_delete_form.php @@ -0,0 +1,77 @@ +. + +/** + * Test form repeat elements and delete button + * + * @copyright 2021 Marina Glancy + * @package core_form + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once(__DIR__.'/../../../../../config.php'); + +defined('BEHAT_SITE_RUNNING') || die(); + +global $CFG, $PAGE, $OUTPUT; +require_once($CFG->libdir.'/formslib.php'); +$PAGE->set_url('/lib/form/tests/behat/fixtures/repeat_with_delete_form.php'); +require_login(); +$PAGE->set_context(context_system::instance()); + +/** + * Class repeat_with_delete_form + * + * @copyright 2021 Marina Glancy + * @package core_form + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class repeat_with_delete_form extends moodleform { + /** + * Form definition + */ + public function definition() { + $mform = $this->_form; + $repeatcount = $this->_customdata['repeatcount']; + + $repeat = array(); + $repeatopts = array(); + + $repeat[] = $mform->createElement('header', 'testheading', 'Heading {no}'); + + $repeat[] = $mform->createElement('text', 'testtext', 'Test text {no}'); + $repeatopts['testtext']['default'] = 'Testing'; + $repeatopts['testtext']['type'] = PARAM_TEXT; + + $repeat[] = $mform->createElement('submit', 'deleteel', 'Delete option {no}', [], false); + + $this->repeat_elements($repeat, $repeatcount, $repeatopts, 'test_repeat', + 'test_repeat_add', 1, 'Add repeats', true, 'deleteel'); + + $this->add_action_buttons(); + } +} + +$repeatcount = optional_param('test_repeat', 1, PARAM_INT); +$form = new repeat_with_delete_form(null, array('repeatcount' => $repeatcount)); + +echo $OUTPUT->header(); +if ($data = $form->get_data()) { + echo "
".json_encode($data->testtext)."
"; +} else { + $form->display(); +} +echo $OUTPUT->footer(); diff --git a/lib/form/tests/behat/repeat_defaults.feature b/lib/form/tests/behat/repeat_defaults.feature index 25e0385f41a..bc27feab5ed 100644 --- a/lib/form/tests/behat/repeat_defaults.feature +++ b/lib/form/tests/behat/repeat_defaults.feature @@ -1,5 +1,5 @@ @core_form -Feature: Newly created repeat elements have the correct default values +Feature: Repeated elements in moodleforms Scenario: Clicking button to add repeat elements creates repeat elements with the correct default values Given I log in as "admin" @@ -22,3 +22,27 @@ Feature: Newly created repeat elements have the correct default values | testselectyes[1] | Yes | | testselectno[1] | No | | testtext[1] | Testing 123 | + + Scenario: Functionality to delete an option in the repeated elements + Given I log in as "admin" + And I am on fixture page "/lib/form/tests/behat/fixtures/repeat_with_delete_form.php" + And I set the field "Test text 1" to "value 1" + When I press "Add repeats" + Then the following fields match these values: + | Test text 1 | value 1 | + | Test text 2 | Testing | + And I set the field "Test text 2" to "value 2" + And I press "Add repeats" + And the following fields match these values: + | Test text 1 | value 1 | + | Test text 2 | value 2 | + | Test text 3 | Testing | + And I set the field "Test text 3" to "value 3" + And I press "Delete option 2" + And the following fields match these values: + | Test text 1 | value 1 | + | Test text 3 | value 3 | + And I should not see "Test text 2" + And I should not see "Delete option 2" + And I press "Save changes" + And I should see "{\"0\":\"value 1\",\"2\":\"value 3\"}" diff --git a/lib/formslib.php b/lib/formslib.php index 879a2aa619d..5190e548d56 100644 --- a/lib/formslib.php +++ b/lib/formslib.php @@ -519,20 +519,58 @@ abstract class moodleform { return $nosubmit; } + /** + * Returns an element of multi-dimensional array given the list of keys + * + * Example: + * $array['a']['b']['c'] = 13; + * $v = $this->get_array_value_by_keys($array, ['a', 'b', 'c']); + * + * Will result it $v==13 + * + * @param array $array + * @param array $keys + * @return mixed returns null if keys not present + */ + protected function get_array_value_by_keys(array $array, array $keys) { + $value = $array; + foreach ($keys as $key) { + if (array_key_exists($key, $value)) { + $value = $value[$key]; + } else { + return null; + } + } + return $value; + } + /** * Checks if a parameter was passed in the previous form submission * - * @param string $name the name of the page parameter we want + * @param string $name the name of the page parameter we want, for example 'id' or 'element[sub][13]' * @param mixed $default the default value to return if nothing is found * @param string $type expected type of parameter * @return mixed */ public function optional_param($name, $default, $type) { - if (isset($this->_ajaxformdata[$name])) { - return clean_param($this->_ajaxformdata[$name], $type); - } else { - return optional_param($name, $default, $type); + $nameparsed = []; + // Convert element name into a sequence of keys, for example 'element[sub][13]' -> ['element', 'sub', '13']. + parse_str($name . '=1', $nameparsed); + $keys = []; + while (is_array($nameparsed)) { + $key = key($nameparsed); + $keys[] = $key; + $nameparsed = $nameparsed[$key]; } + + // Search for the element first in $this->_ajaxformdata, then in $_POST and then in $_GET. + if (($value = $this->get_array_value_by_keys($this->_ajaxformdata ?? [], $keys)) !== null || + ($value = $this->get_array_value_by_keys($_POST, $keys)) !== null || + ($value = $this->get_array_value_by_keys($_GET, $keys)) !== null) { + return $type == PARAM_RAW ? $value : clean_param($value, $type); + } + + return $default; } /** @@ -1099,11 +1137,14 @@ abstract class moodleform { * @param int $addfieldsno how many fields to add at a time * @param string $addstring name of button, {no} is replaced by no of blanks that will be added. * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false. + * @param string $deletebuttonname if specified, treats the no-submit button with this name as a "delete element" button + * in each of the elements * @return int no of repeats of element in this page */ - function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, - $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){ - if ($addstring===null){ + public function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, + $addfieldsname, $addfieldsno = 5, $addstring = null, $addbuttoninside = false, + $deletebuttonname = '') { + if ($addstring === null) { $addstring = get_string('addfields', 'form', $addfieldsno); } else { $addstring = str_ireplace('{no}', $addfieldsno, $addstring); @@ -1121,7 +1162,18 @@ abstract class moodleform { //value not to be overridden by submitted value $mform->setConstants(array($repeathiddenname=>$repeats)); $namecloned = array(); + $no = 1; for ($i = 0; $i < $repeats; $i++) { + if ($deletebuttonname) { + $mform->registerNoSubmitButton($deletebuttonname . "[$i]"); + $isdeleted = $this->optional_param($deletebuttonname . "[$i]", false, PARAM_RAW) || + $this->optional_param($deletebuttonname . "-hidden[$i]", false, PARAM_RAW); + if ($isdeleted) { + $mform->addElement('hidden', $deletebuttonname . "-hidden[$i]", 1); + $mform->setType($deletebuttonname . "-hidden[$i]", PARAM_INT); + continue; + } + } foreach ($elementobjs as $elementobj){ $elementclone = fullclone($elementobj); $this->repeat_elements_fix_clone($i, $elementclone, $namecloned); @@ -1130,7 +1182,13 @@ abstract class moodleform { foreach ($elementclone->getElements() as $el) { $this->repeat_elements_fix_clone($i, $el, $namecloned); } - $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel())); + $elementclone->setLabel(str_replace('{no}', $no, $elementclone->getLabel())); + } else if ($elementobj instanceof \HTML_QuickForm_submit && $elementobj->getName() == $deletebuttonname) { + // Mark the "Delete" button as no-submit. + $onclick = $elementclone->getAttribute('onclick'); + $skip = 'skipClientValidation = true;'; + $onclick = ($onclick !== null) ? $skip . ' ' . $onclick : $skip; + $elementclone->updateAttributes(['data-skip-validation' => 1, 'data-no-submit' => 1, 'onclick' => $onclick]); } // Mark newly created elements, so they know not to look for any submitted data. @@ -1139,6 +1197,7 @@ abstract class moodleform { } $mform->addElement($elementclone); + $no++; } } for ($i=0; $i<$repeats; $i++) { @@ -1161,24 +1220,22 @@ abstract class moodleform { call_user_func_array(array(&$mform, 'addHelpButton'), $params); break; case 'disabledif' : - foreach ($namecloned as $num => $name){ - if ($params[0] == $name){ - $params[0] = $params[0]."[$i]"; - break; - } - } - $params = array_merge(array($realelementname), $params); - call_user_func_array(array(&$mform, 'disabledIf'), $params); - break; case 'hideif' : + $pos = strpos($params[0], '['); + $ending = ''; + if ($pos !== false) { + $ending = substr($params[0], $pos); + $params[0] = substr($params[0], 0, $pos); + } foreach ($namecloned as $num => $name){ if ($params[0] == $name){ - $params[0] = $params[0]."[$i]"; + $params[0] = $params[0] . "[$i]" . $ending; break; } } $params = array_merge(array($realelementname), $params); - call_user_func_array(array(&$mform, 'hideIf'), $params); + $function = ($option === 'disabledif') ? 'disabledIf' : 'hideIf'; + call_user_func_array(array(&$mform, $function), $params); break; case 'rule' : if (is_string($params)){ @@ -1203,7 +1260,7 @@ abstract class moodleform { } } } - $mform->addElement('submit', $addfieldsname, $addstring); + $mform->addElement('submit', $addfieldsname, $addstring, [], false); if (!$addbuttoninside) { $mform->closeHeaderBefore($addfieldsname); @@ -1432,6 +1489,40 @@ abstract class moodleform { } } + /** + * Used by tests to simulate submitted form data submission via AJAX. + * + * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to + * get_data. + * + * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these + * global arrays after each test. + * + * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST). + * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted. + * @param string $method 'post' or 'get', defaults to 'post'. + * @param null $formidentifier the default is to use the class name for this class but you may need to provide + * a different value here for some forms that are used more than once on the + * same page. + * @return array array to pass to form constructor as $ajaxdata + */ + public static function mock_ajax_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post', + $formidentifier = null) { + $_FILES = $simulatedsubmittedfiles; + if ($formidentifier === null) { + $formidentifier = get_called_class(); + $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information. + } + $simulatedsubmitteddata['_qf__'.$formidentifier] = 1; + $simulatedsubmitteddata['sesskey'] = sesskey(); + if (strtolower($method) === 'get') { + $_GET = ['sesskey' => sesskey()]; + } else { + $_POST = ['sesskey' => sesskey()]; + } + return $simulatedsubmitteddata; + } + /** * Used by tests to generate valid submit keys for moodle forms that are * submitted with ajax data. diff --git a/lib/upgrade.txt b/lib/upgrade.txt index 6d4e6119861..6eb57758737 100644 --- a/lib/upgrade.txt +++ b/lib/upgrade.txt @@ -24,6 +24,8 @@ information provided here is intended especially for developers. * emoji-data has been upgraded to 6.0.0. * The final deprecation of /message/defaultoutputs.php file and admin_page_defaultmessageoutputs. All their settings moved to admin/message.php (see MDL-64495). Please use admin_page_managemessageoutputs class instead. +* Added new class, AMD modules and WS that allow displaying forms in modal popups or load and submit in AJAX requests. + See https://docs.moodle.org/dev/Modal_and_AJAX_forms for more details. === 3.10 === * PHPUnit has been upgraded to 8.5. That comes with a few changes: diff --git a/version.php b/version.php index 2aa5e104ef7..11323a45a90 100644 --- a/version.php +++ b/version.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2021021100.00; // 20201109 = branching date YYYYMMDD - do not modify! +$version = 2021021100.01; // 20201109 = branching date YYYYMMDD - do not modify! // RR = release increments - 00 in DEV branches. // .XX = incremental changes. $release = '3.11dev (Build: 20210211)';// Human-friendly version name