From 377c962f11b568f37df93efe7a8f8d0f6c811f34 Mon Sep 17 00:00:00 2001 From: Laurent David Date: Wed, 14 Dec 2022 10:31:22 +0100 Subject: [PATCH] MDL-75337 core: Single button - API changes * Update component library for new features of single_button and modal * Update core_notification javascript --- .../content/moodle/components/buttons.md | 4 +- .../content/moodle/javascript/confirm.md | 26 ++- .../examples/singlebuttons.php | 59 ++++++ lib/amd/build/modal.min.js | 2 +- lib/amd/build/modal.min.js.map | 2 +- lib/amd/build/modal_delete_cancel.min.js | 10 ++ lib/amd/build/modal_delete_cancel.min.js.map | 1 + lib/amd/build/modal_events.min.js | 2 +- lib/amd/build/modal_events.min.js.map | 2 +- lib/amd/build/modal_factory.min.js | 2 +- lib/amd/build/modal_factory.min.js.map | 2 +- lib/amd/build/notification.min.js | 2 +- lib/amd/build/notification.min.js.map | 2 +- lib/amd/build/utility.min.js | 2 +- lib/amd/build/utility.min.js.map | 2 +- lib/amd/src/modal.js | 24 +++ lib/amd/src/modal_delete_cancel.js | 73 ++++++++ lib/amd/src/modal_events.js | 1 + lib/amd/src/modal_factory.js | 8 +- lib/amd/src/notification.js | 67 ++++++- lib/amd/src/utility.js | 23 ++- lib/outputcomponents.php | 168 ++++++++++++++---- lib/templates/modal_delete_cancel.mustache | 46 +++++ lib/templates/single_button.mustache | 10 +- lib/tests/outputcomponents_test.php | 106 +++++++++-- lib/upgrade.txt | 4 + 26 files changed, 566 insertions(+), 84 deletions(-) create mode 100644 admin/tool/componentlibrary/examples/singlebuttons.php create mode 100644 lib/amd/build/modal_delete_cancel.min.js create mode 100644 lib/amd/build/modal_delete_cancel.min.js.map create mode 100644 lib/amd/src/modal_delete_cancel.js create mode 100644 lib/templates/modal_delete_cancel.mustache diff --git a/admin/tool/componentlibrary/content/moodle/components/buttons.md b/admin/tool/componentlibrary/content/moodle/components/buttons.md index 9a66ee3b5fb..3a07d836d12 100644 --- a/admin/tool/componentlibrary/content/moodle/components/buttons.md +++ b/admin/tool/componentlibrary/content/moodle/components/buttons.md @@ -62,7 +62,7 @@ Outline buttons are used for buttons that controll part of the user interface, l ### Using the single_select renderer -The ```single_select()``` renderer allows you to quickly add a button with an action to a page without having to write a template for the page. Single select buttons are added as miniature forms that can pass custom form data. +The ```single_button()``` renderer allows you to quickly add a button with an action to a page without having to write a template for the page. Single select buttons are added as miniature forms that can pass custom form data. {{< php >}} $url = new moodle_url("$CFG->wwwroot/my/index.php", $params); @@ -70,6 +70,8 @@ The ```single_select()``` renderer allows you to quickly add a button with an ac $PAGE->set_button($resetbutton . $button); {{< / php >}} + + ### Button links Links can be style to look like buttons, the action for this button is to simply navigate to some other page diff --git a/admin/tool/componentlibrary/content/moodle/javascript/confirm.md b/admin/tool/componentlibrary/content/moodle/javascript/confirm.md index 091ebf5bc98..73392b0ec44 100644 --- a/admin/tool/componentlibrary/content/moodle/javascript/confirm.md +++ b/admin/tool/componentlibrary/content/moodle/javascript/confirm.md @@ -16,7 +16,7 @@ to the element that will trigger the confirmation modal. ## Source files -* `lib/amd/src/confirm.js` ({{< jsdoc module="core/confirm" >}}) +* `lib/amd/src/utility.js` ({{< jsdoc module="core/utility" >}}) * `lib/templates/modal.mustache` ## Usage @@ -82,23 +82,33 @@ echo $OUTPUT->single_button('#', get_string('delete'), 'get', [ ### Basic confirmation modal +#### Simple Modal + {{< example >}} - + {{< /example >}} +#### Delete Modal + +{{< example >}} + +{{< /example >}} + + ### Confirmation modal with a toast {{< example >}} - + {{< /example >}} ### Confirmation modal with redirect {{< example >}} - {{< /example >}} diff --git a/admin/tool/componentlibrary/examples/singlebuttons.php b/admin/tool/componentlibrary/examples/singlebuttons.php new file mode 100644 index 00000000000..02ac6316d23 --- /dev/null +++ b/admin/tool/componentlibrary/examples/singlebuttons.php @@ -0,0 +1,59 @@ +. + +/** + * Moodle Component Library + * + * A sample of different singlebuttons + * + * @package tool_componentlibrary + * @copyright 2022 Laurent David + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once(__DIR__ . '/../../../../config.php'); +require_once($CFG->dirroot . '/lib/formslib.php'); + +require_login(); +require_capability('moodle/site:configview', context_system::instance()); + +$repeatcount = optional_param('test_repeat', 1, PARAM_INT); + +$PAGE->set_pagelayout('embedded'); + +$url = new moodle_url('/admin/tool/componentlibrary/examples/singlebuttons.php'); +$PAGE->set_url($url); +$PAGE->set_context(context_system::instance()); + +$PAGE->set_heading('Moodle single buttons'); +$PAGE->set_title('Moodle single buttons'); + +$buttondefinitions = [ + ['label' => 'Standard'], + ['label' => 'Primary', 'type' => single_button::BUTTON_PRIMARY], + ['label' => 'Danger', 'type' => single_button::BUTTON_DANGER], + ['label' => 'Warning', 'type' => single_button::BUTTON_WARNING], + ['label' => 'Success', 'type' => single_button::BUTTON_SUCCESS], + ['label' => 'Info', 'type' => single_button::BUTTON_INFO], + +]; +echo $OUTPUT->header(); +foreach ($buttondefinitions as $def) { + $button = new single_button($url, $def['label'], 'post', $def['type'] ?? + single_button::BUTTON_SECONDARY, $def['attributes'] ?? []); + echo $OUTPUT->render($button); +} +echo $OUTPUT->footer(); diff --git a/lib/amd/build/modal.min.js b/lib/amd/build/modal.min.js index 31249353d3f..aaf69696ab2 100644 --- a/lib/amd/build/modal.min.js +++ b/lib/amd/build/modal.min.js @@ -6,6 +6,6 @@ * @copyright 2016 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define("core/modal",["jquery","core/templates","core/notification","core/key_codes","core/custom_interaction_events","core/modal_backdrop","core_filters/events","core/modal_events","core/local/aria/focuslock","core/pending","core/aria","core/fullscreen"],(function($,Templates,Notification,KeyCodes,CustomEvents,ModalBackdrop,FilterEvents,ModalEvents,FocusLock,Pending,Aria,Fullscreen){var backdropPromise,SELECTORS_CONTAINER='[data-region="modal-container"]',SELECTORS_MODAL='[data-region="modal"]',SELECTORS_HEADER='[data-region="header"]',SELECTORS_TITLE='[data-region="title"]',SELECTORS_BODY='[data-region="body"]',SELECTORS_FOOTER='[data-region="footer"]',SELECTORS_HIDE='[data-action="hide"]',SELECTORS_DIALOG="[role=dialog]",SELECTORS_FORM="form",SELECTORS_MENU_BAR="[role=menubar]",SELECTORS_HAS_Z_INDEX=".moodle-has-zindex",TEMPLATES_LOADING="core/loading",TEMPLATES_BACKDROP="core/modal_backdrop",modalCounter=0,Modal=function(root){this.root=$(root),this.modal=this.root.find(SELECTORS_MODAL),this.header=this.modal.find(SELECTORS_HEADER),this.headerPromise=$.Deferred(),this.title=this.header.find(SELECTORS_TITLE),this.titlePromise=$.Deferred(),this.body=this.modal.find(SELECTORS_BODY),this.bodyPromise=$.Deferred(),this.footer=this.modal.find(SELECTORS_FOOTER),this.footerPromise=$.Deferred(),this.hiddenSiblings=[],this.isAttached=!1,this.bodyJS=null,this.footerJS=null,this.modalCount=modalCounter++,this.attachmentPoint=document.createElement("div"),document.body.append(this.attachmentPoint),this.focusOnClose=null,this.root.is(SELECTORS_CONTAINER)||Notification.exception({message:"Element is not a modal container"}),this.modal.length||Notification.exception({message:"Container does not contain a modal"}),this.header.length||Notification.exception({message:"Modal is missing a header region"}),this.title.length||Notification.exception({message:"Modal header is missing a title region"}),this.body.length||Notification.exception({message:"Modal is missing a body region"}),this.footer.length||Notification.exception({message:"Modal is missing a footer region"}),this.registerEventListeners()};return Modal.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root),this.isAttached||(FocusLock.trapFocus(this.root[0]),this.bodyJS&&(Templates.runTemplateJS(this.bodyJS),this.bodyJS=null),this.footerJS&&(Templates.runTemplateJS(this.footerJS),this.footerJS=null),this.isAttached=!0)},Modal.prototype.countOtherVisibleModals=function(){var count=0;return $("body").find(SELECTORS_CONTAINER).each(function(index,element){element=$(element),!this.root.is(element)&&element.hasClass("show")&&count++}.bind(this)),count},Modal.prototype.getBackdrop=function(){return backdropPromise||(backdropPromise=Templates.render(TEMPLATES_BACKDROP,{}).then((function(html){var element=$(html);return new ModalBackdrop(element)})).fail(Notification.exception)),backdropPromise},Modal.prototype.getRoot=function(){return this.root},Modal.prototype.getModal=function(){return this.modal},Modal.prototype.getTitle=function(){return this.title},Modal.prototype.getBody=function(){return this.body},Modal.prototype.getFooter=function(){return this.footer},Modal.prototype.getTitlePromise=function(){return this.titlePromise},Modal.prototype.getBodyPromise=function(){return this.bodyPromise},Modal.prototype.getFooterPromise=function(){return this.footerPromise},Modal.prototype.getModalCount=function(){return this.modalCount},Modal.prototype.setTitle=function(value){var title=this.getTitle();this.titlePromise=$.Deferred(),this.asyncSet(value,title.html.bind(title)).then(function(){this.titlePromise.resolve(title)}.bind(this)).catch(Notification.exception)},Modal.prototype.setBody=function(value){this.bodyPromise=$.Deferred();var body=this.getBody();if("string"==typeof value)body.html(value),FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),this.bodyPromise.resolve(body);else{var jsPendingId="amd-modal-js-pending-id-"+this.getModalCount();M.util.js_pending(jsPendingId);var contentPromise=null;if(body.css("overflow","hidden"),"pending"==(value=$.when(value)).state()){var height=body.innerHeight();height<100&&(height=100),body.animate({height:height+"px"},150),body.html(""),contentPromise=Templates.render(TEMPLATES_LOADING,{}).then((function(html){var loadingIcon=$(html).hide();return body.html(loadingIcon),loadingIcon.fadeIn(150),$.when(loadingIcon.promise(),value)})).then((function(loadingIcon){return loadingIcon.fadeOut(100).promise()})).then((function(){return value}))}else contentPromise=value;contentPromise.then(function(html,js){var result=null;if(this.isVisible()){body.css("opacity",0);var currentHeight=body.innerHeight();body.html(html),body.css("height","");var newHeight=body.innerHeight();body.css("height",currentHeight+"px"),result=body.animate({height:newHeight+"px",opacity:1},{duration:150,queue:!1}).promise()}else body.html(html);return js&&(this.isAttached?Templates.runTemplateJS(js):this.bodyJS=js),result}.bind(this)).then(function(result){return FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),result}.bind(this)).then(function(){this.bodyPromise.resolve(body)}.bind(this)).fail(Notification.exception).always((function(){body.css("height",""),body.css("overflow",""),body.css("opacity",""),M.util.js_complete(jsPendingId)})).fail(Notification.exception)}},Modal.prototype.setBodyContent=function(promise){return promise.then((_ref=>{let{html:html,js:js}=_ref;return this.setBody($.when(html,js))})).catch((exception=>{throw this.hide(),exception}))},Modal.prototype.setFooter=function(value){this.showFooter(),this.footerPromise=$.Deferred();var footer=this.getFooter();"string"==typeof value?(footer.html(value),this.footerPromise.resolve(footer)):Templates.render(TEMPLATES_LOADING,{}).then((function(html){return footer.html(html),value})).then(function(html,js){return footer.html(html),js&&(this.isAttached?Templates.runTemplateJS(js):this.footerJS=js),footer}.bind(this)).then(function(footer){this.footerPromise.resolve(footer)}.bind(this)).catch(Notification.exception)},Modal.prototype.hasFooterContent=function(){return!!this.getFooter().children().length},Modal.prototype.hideFooter=function(){this.getFooter().addClass("hidden")},Modal.prototype.showFooter=function(){this.getFooter().removeClass("hidden")},Modal.prototype.setLarge=function(){this.isLarge()||this.getModal().addClass("modal-lg")},Modal.prototype.isLarge=function(){return this.getModal().hasClass("modal-lg")},Modal.prototype.setSmall=function(){this.isSmall()||this.getModal().removeClass("modal-lg")},Modal.prototype.isSmall=function(){return!this.getModal().hasClass("modal-lg")},Modal.prototype.setScrollable=function(value){value?this.getModal()[0].classList.add("modal-dialog-scrollable"):this.getModal()[0].classList.remove("modal-dialog-scrollable")},Modal.prototype.calculateZIndex=function(){var items=$(SELECTORS_DIALOG+", "+SELECTORS_MENU_BAR+", "+SELECTORS_HAS_Z_INDEX),zIndex=parseInt(this.root.css("z-index"));return items.each((function(index,item){var itemZIndex=(item=$(item)).css("z-index")?parseInt(item.css("z-index")):0;itemZIndex>zIndex&&(zIndex=itemZIndex)})),zIndex},Modal.prototype.isVisible=function(){return this.root.hasClass("show")},Modal.prototype.hasFocus=function(){var target=$(document.activeElement);return this.root.is(target)||this.root.has(target).length},Modal.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")},Modal.prototype.getAttachmentPoint=function(){return $(Fullscreen.getElement()||this.attachmentPoint)},Modal.prototype.show=function(){if(this.isVisible())return $.Deferred().resolve();var pendingPromise=new Pending("core/modal:show");return this.hasFooterContent()?this.showFooter():this.hideFooter(),this.attachToDOM(),!this.focusOnClose&&document.activeElement&&(this.focusOnClose=document.activeElement),this.getBackdrop().then(function(backdrop){var newIndex=this.calculateZIndex()+2,newBackdropIndex=newIndex-1;this.root.css("z-index",newIndex),backdrop.setZIndex(newBackdropIndex),backdrop.show(),this.root.removeClass("hide").addClass("show"),this.accessibilityShow(),this.getModal().focus(),$("body").addClass("modal-open"),this.root.trigger(ModalEvents.shown,this)}.bind(this)).then(pendingPromise.resolve)},Modal.prototype.hideIfNotForm=function(){0==this.modal.find(SELECTORS_FORM).length&&this.hide()},Modal.prototype.hide=function(){this.getBackdrop().done(function(backdrop){FocusLock.untrapFocus(),this.countOtherVisibleModals()||(backdrop.hide(),$("body").removeClass("modal-open"));var currentIndex=parseInt(this.root.css("z-index"));this.root.css("z-index",""),backdrop.setZIndex(currentIndex-3),this.accessibilityHide(),this.hasTransitions()?this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this)):this.getRoot().removeClass("show").addClass("hide"),$(document.body).find(this.getRoot()).length&&$(document.body).append(this.getRoot()),this.root.trigger(ModalEvents.hidden,this)}.bind(this))},Modal.prototype.destroy=function(){this.hide(),this.root.remove(),this.root.trigger(ModalEvents.destroyed,this),this.attachmentPoint.remove()},Modal.prototype.accessibilityShow=function(){Aria.unhide(this.root.get()),Aria.hideSiblings(this.root.get()[0])},Modal.prototype.accessibilityHide=function(){Aria.unhideSiblings(this.root.get()[0]),Aria.hide(this.root.get())},Modal.prototype.registerEventListeners=function(){this.getRoot().on("keydown",function(e){this.isVisible()&&e.keyCode==KeyCodes.escape&&(this.removeOnClose?this.destroy():this.hide())}.bind(this)),this.getRoot().click(function(e){if(!$(e.target).closest(SELECTORS_MODAL).length&&$(e.target).closest(SELECTORS_CONTAINER).length){var outsideClickEvent=$.Event(ModalEvents.outsideClick);this.getRoot().trigger(outsideClickEvent,this),outsideClickEvent.isDefaultPrevented()||this.hideIfNotForm()}}.bind(this)),CustomEvents.define(this.getModal(),[CustomEvents.events.activate]),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE,function(e,data){this.hide(),data.originalEvent.preventDefault()}.bind(this)),this.getRoot().on(ModalEvents.hidden,(()=>{this.focusOnClose&&this.focusOnClose.focus()}))},Modal.prototype.registerCloseOnCancel=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("cancel"),function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.registerCloseOnSave=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("save"),function(e,data){var saveEvent=$.Event(ModalEvents.save);this.getRoot().trigger(saveEvent,this),saveEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.asyncSet=function(value,setFunction){var p=value;return"object"==typeof value&&value.hasOwnProperty("then")||(p=$.Deferred()).resolve(value),p.then((function(content){setFunction(content)})).fail(Notification.exception),p},Modal.prototype.setButtonText=function(action,value){const button=this.getFooter().find(this.getActionSelector(action));if(!button)throw new Error("Unable to find the '"+action+"' button");return this.asyncSet(value,button.text.bind(button))},Modal.prototype.getActionSelector=function(action){return"[data-action='"+action+"']"},Modal.prototype.setRemoveOnClose=function(remove){this.removeOnClose=remove},Modal.prototype.setReturnElement=function(element){this.focusOnClose=element},Modal})); +define("core/modal",["jquery","core/templates","core/notification","core/key_codes","core/custom_interaction_events","core/modal_backdrop","core_filters/events","core/modal_events","core/local/aria/focuslock","core/pending","core/aria","core/fullscreen"],(function($,Templates,Notification,KeyCodes,CustomEvents,ModalBackdrop,FilterEvents,ModalEvents,FocusLock,Pending,Aria,Fullscreen){var backdropPromise,SELECTORS_CONTAINER='[data-region="modal-container"]',SELECTORS_MODAL='[data-region="modal"]',SELECTORS_HEADER='[data-region="header"]',SELECTORS_TITLE='[data-region="title"]',SELECTORS_BODY='[data-region="body"]',SELECTORS_FOOTER='[data-region="footer"]',SELECTORS_HIDE='[data-action="hide"]',SELECTORS_DIALOG="[role=dialog]",SELECTORS_FORM="form",SELECTORS_MENU_BAR="[role=menubar]",SELECTORS_HAS_Z_INDEX=".moodle-has-zindex",TEMPLATES_LOADING="core/loading",TEMPLATES_BACKDROP="core/modal_backdrop",modalCounter=0,Modal=function(root){this.root=$(root),this.modal=this.root.find(SELECTORS_MODAL),this.header=this.modal.find(SELECTORS_HEADER),this.headerPromise=$.Deferred(),this.title=this.header.find(SELECTORS_TITLE),this.titlePromise=$.Deferred(),this.body=this.modal.find(SELECTORS_BODY),this.bodyPromise=$.Deferred(),this.footer=this.modal.find(SELECTORS_FOOTER),this.footerPromise=$.Deferred(),this.hiddenSiblings=[],this.isAttached=!1,this.bodyJS=null,this.footerJS=null,this.modalCount=modalCounter++,this.attachmentPoint=document.createElement("div"),document.body.append(this.attachmentPoint),this.focusOnClose=null,this.root.is(SELECTORS_CONTAINER)||Notification.exception({message:"Element is not a modal container"}),this.modal.length||Notification.exception({message:"Container does not contain a modal"}),this.header.length||Notification.exception({message:"Modal is missing a header region"}),this.title.length||Notification.exception({message:"Modal header is missing a title region"}),this.body.length||Notification.exception({message:"Modal is missing a body region"}),this.footer.length||Notification.exception({message:"Modal is missing a footer region"}),this.registerEventListeners()};return Modal.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root),this.isAttached||(FocusLock.trapFocus(this.root[0]),this.bodyJS&&(Templates.runTemplateJS(this.bodyJS),this.bodyJS=null),this.footerJS&&(Templates.runTemplateJS(this.footerJS),this.footerJS=null),this.isAttached=!0)},Modal.prototype.countOtherVisibleModals=function(){var count=0;return $("body").find(SELECTORS_CONTAINER).each(function(index,element){element=$(element),!this.root.is(element)&&element.hasClass("show")&&count++}.bind(this)),count},Modal.prototype.getBackdrop=function(){return backdropPromise||(backdropPromise=Templates.render(TEMPLATES_BACKDROP,{}).then((function(html){var element=$(html);return new ModalBackdrop(element)})).fail(Notification.exception)),backdropPromise},Modal.prototype.getRoot=function(){return this.root},Modal.prototype.getModal=function(){return this.modal},Modal.prototype.getTitle=function(){return this.title},Modal.prototype.getBody=function(){return this.body},Modal.prototype.getFooter=function(){return this.footer},Modal.prototype.getTitlePromise=function(){return this.titlePromise},Modal.prototype.getBodyPromise=function(){return this.bodyPromise},Modal.prototype.getFooterPromise=function(){return this.footerPromise},Modal.prototype.getModalCount=function(){return this.modalCount},Modal.prototype.setTitle=function(value){var title=this.getTitle();this.titlePromise=$.Deferred(),this.asyncSet(value,title.html.bind(title)).then(function(){this.titlePromise.resolve(title)}.bind(this)).catch(Notification.exception)},Modal.prototype.setBody=function(value){this.bodyPromise=$.Deferred();var body=this.getBody();if("string"==typeof value)body.html(value),FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),this.bodyPromise.resolve(body);else{var jsPendingId="amd-modal-js-pending-id-"+this.getModalCount();M.util.js_pending(jsPendingId);var contentPromise=null;if(body.css("overflow","hidden"),"pending"==(value=$.when(value)).state()){var height=body.innerHeight();height<100&&(height=100),body.animate({height:height+"px"},150),body.html(""),contentPromise=Templates.render(TEMPLATES_LOADING,{}).then((function(html){var loadingIcon=$(html).hide();return body.html(loadingIcon),loadingIcon.fadeIn(150),$.when(loadingIcon.promise(),value)})).then((function(loadingIcon){return loadingIcon.fadeOut(100).promise()})).then((function(){return value}))}else contentPromise=value;contentPromise.then(function(html,js){var result=null;if(this.isVisible()){body.css("opacity",0);var currentHeight=body.innerHeight();body.html(html),body.css("height","");var newHeight=body.innerHeight();body.css("height",currentHeight+"px"),result=body.animate({height:newHeight+"px",opacity:1},{duration:150,queue:!1}).promise()}else body.html(html);return js&&(this.isAttached?Templates.runTemplateJS(js):this.bodyJS=js),result}.bind(this)).then(function(result){return FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),result}.bind(this)).then(function(){this.bodyPromise.resolve(body)}.bind(this)).fail(Notification.exception).always((function(){body.css("height",""),body.css("overflow",""),body.css("opacity",""),M.util.js_complete(jsPendingId)})).fail(Notification.exception)}},Modal.prototype.setBodyContent=function(promise){return promise.then((_ref=>{let{html:html,js:js}=_ref;return this.setBody($.when(html,js))})).catch((exception=>{throw this.hide(),exception}))},Modal.prototype.setFooter=function(value){this.showFooter(),this.footerPromise=$.Deferred();var footer=this.getFooter();"string"==typeof value?(footer.html(value),this.footerPromise.resolve(footer)):Templates.render(TEMPLATES_LOADING,{}).then((function(html){return footer.html(html),value})).then(function(html,js){return footer.html(html),js&&(this.isAttached?Templates.runTemplateJS(js):this.footerJS=js),footer}.bind(this)).then(function(footer){this.footerPromise.resolve(footer)}.bind(this)).catch(Notification.exception)},Modal.prototype.hasFooterContent=function(){return!!this.getFooter().children().length},Modal.prototype.hideFooter=function(){this.getFooter().addClass("hidden")},Modal.prototype.showFooter=function(){this.getFooter().removeClass("hidden")},Modal.prototype.setLarge=function(){this.isLarge()||this.getModal().addClass("modal-lg")},Modal.prototype.isLarge=function(){return this.getModal().hasClass("modal-lg")},Modal.prototype.setSmall=function(){this.isSmall()||this.getModal().removeClass("modal-lg")},Modal.prototype.isSmall=function(){return!this.getModal().hasClass("modal-lg")},Modal.prototype.setScrollable=function(value){value?this.getModal()[0].classList.add("modal-dialog-scrollable"):this.getModal()[0].classList.remove("modal-dialog-scrollable")},Modal.prototype.calculateZIndex=function(){var items=$(SELECTORS_DIALOG+", "+SELECTORS_MENU_BAR+", "+SELECTORS_HAS_Z_INDEX),zIndex=parseInt(this.root.css("z-index"));return items.each((function(index,item){var itemZIndex=(item=$(item)).css("z-index")?parseInt(item.css("z-index")):0;itemZIndex>zIndex&&(zIndex=itemZIndex)})),zIndex},Modal.prototype.isVisible=function(){return this.root.hasClass("show")},Modal.prototype.hasFocus=function(){var target=$(document.activeElement);return this.root.is(target)||this.root.has(target).length},Modal.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")},Modal.prototype.getAttachmentPoint=function(){return $(Fullscreen.getElement()||this.attachmentPoint)},Modal.prototype.show=function(){if(this.isVisible())return $.Deferred().resolve();var pendingPromise=new Pending("core/modal:show");return this.hasFooterContent()?this.showFooter():this.hideFooter(),this.attachToDOM(),!this.focusOnClose&&document.activeElement&&(this.focusOnClose=document.activeElement),this.getBackdrop().then(function(backdrop){var newIndex=this.calculateZIndex()+2,newBackdropIndex=newIndex-1;this.root.css("z-index",newIndex),backdrop.setZIndex(newBackdropIndex),backdrop.show(),this.root.removeClass("hide").addClass("show"),this.accessibilityShow(),this.getModal().focus(),$("body").addClass("modal-open"),this.root.trigger(ModalEvents.shown,this)}.bind(this)).then(pendingPromise.resolve)},Modal.prototype.hideIfNotForm=function(){0==this.modal.find(SELECTORS_FORM).length&&this.hide()},Modal.prototype.hide=function(){this.getBackdrop().done(function(backdrop){FocusLock.untrapFocus(),this.countOtherVisibleModals()||(backdrop.hide(),$("body").removeClass("modal-open"));var currentIndex=parseInt(this.root.css("z-index"));this.root.css("z-index",""),backdrop.setZIndex(currentIndex-3),this.accessibilityHide(),this.hasTransitions()?this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this)):this.getRoot().removeClass("show").addClass("hide"),$(document.body).find(this.getRoot()).length&&$(document.body).append(this.getRoot()),this.root.trigger(ModalEvents.hidden,this)}.bind(this))},Modal.prototype.destroy=function(){this.hide(),this.root.remove(),this.root.trigger(ModalEvents.destroyed,this),this.attachmentPoint.remove()},Modal.prototype.accessibilityShow=function(){Aria.unhide(this.root.get()),Aria.hideSiblings(this.root.get()[0])},Modal.prototype.accessibilityHide=function(){Aria.unhideSiblings(this.root.get()[0]),Aria.hide(this.root.get())},Modal.prototype.registerEventListeners=function(){this.getRoot().on("keydown",function(e){this.isVisible()&&e.keyCode==KeyCodes.escape&&(this.removeOnClose?this.destroy():this.hide())}.bind(this)),this.getRoot().click(function(e){if(!$(e.target).closest(SELECTORS_MODAL).length&&$(e.target).closest(SELECTORS_CONTAINER).length){var outsideClickEvent=$.Event(ModalEvents.outsideClick);this.getRoot().trigger(outsideClickEvent,this),outsideClickEvent.isDefaultPrevented()||this.hideIfNotForm()}}.bind(this)),CustomEvents.define(this.getModal(),[CustomEvents.events.activate]),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE,function(e,data){this.hide(),data.originalEvent.preventDefault()}.bind(this)),this.getRoot().on(ModalEvents.hidden,(()=>{this.focusOnClose&&this.focusOnClose.focus()}))},Modal.prototype.registerCloseOnCancel=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("cancel"),function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.registerCloseOnSave=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("save"),function(e,data){var saveEvent=$.Event(ModalEvents.save);this.getRoot().trigger(saveEvent,this),saveEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.registerCloseOnDelete=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("delete"),function(e,data){var deleteEvent=$.Event(ModalEvents.delete);this.getRoot().trigger(deleteEvent,this),deleteEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.asyncSet=function(value,setFunction){var p=value;return"object"==typeof value&&value.hasOwnProperty("then")||(p=$.Deferred()).resolve(value),p.then((function(content){setFunction(content)})).fail(Notification.exception),p},Modal.prototype.setButtonText=function(action,value){const button=this.getFooter().find(this.getActionSelector(action));if(!button)throw new Error("Unable to find the '"+action+"' button");return this.asyncSet(value,button.text.bind(button))},Modal.prototype.getActionSelector=function(action){return"[data-action='"+action+"']"},Modal.prototype.setRemoveOnClose=function(remove){this.removeOnClose=remove},Modal.prototype.setReturnElement=function(element){this.focusOnClose=element},Modal})); //# sourceMappingURL=modal.min.js.map \ No newline at end of file diff --git a/lib/amd/build/modal.min.js.map b/lib/amd/build/modal.min.js.map index e33d1d6529f..ed92b07e764 100644 --- a/lib/amd/build/modal.min.js.map +++ b/lib/amd/build/modal.min.js.map @@ -1 +1 @@ -{"version":3,"file":"modal.min.js","sources":["../src/modal.js"],"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 core/modal\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_filters/events',\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 FilterEvents,\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 this.focusOnClose = null;\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 * @fires event:filterContentUpdated\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 FilterEvents.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 FilterEvents.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 .catch(exception => {\n this.hide();\n throw 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 // If the focusOnClose was not set. Set the focus back to triggered element.\n if (!this.focusOnClose && document.activeElement) {\n this.focusOnClose = document.activeElement;\n }\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 this.getRoot().on(ModalEvents.hidden, () => {\n if (this.focusOnClose) {\n // Focus on the element that actually triggers the modal.\n this.focusOnClose.focus();\n }\n });\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 /**\n * Set the return element for the modal.\n *\n * @param {Element|jQuery} element Element to focus when the modal is closed\n */\n Modal.prototype.setReturnElement = function(element) {\n this.focusOnClose = element;\n };\n\n return Modal;\n});\n"],"names":["define","$","Templates","Notification","KeyCodes","CustomEvents","ModalBackdrop","FilterEvents","ModalEvents","FocusLock","Pending","Aria","Fullscreen","backdropPromise","SELECTORS","TEMPLATES","modalCounter","Modal","root","modal","this","find","header","headerPromise","Deferred","title","titlePromise","body","bodyPromise","footer","footerPromise","hiddenSiblings","isAttached","bodyJS","footerJS","modalCount","attachmentPoint","document","createElement","append","focusOnClose","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","_ref","setFooter","showFooter","hasFooterContent","children","hideFooter","addClass","removeClass","setLarge","isLarge","setSmall","isSmall","setScrollable","classList","add","remove","calculateZIndex","items","zIndex","parseInt","item","itemZIndex","hasFocus","target","activeElement","has","hasTransitions","getElement","show","pendingPromise","backdrop","newIndex","newBackdropIndex","setZIndex","accessibilityShow","focus","shown","hideIfNotForm","done","untrapFocus","currentIndex","accessibilityHide","one","hidden","destroy","destroyed","unhide","get","hideSiblings","unhideSiblings","on","e","keyCode","escape","removeOnClose","click","closest","outsideClickEvent","Event","outsideClick","isDefaultPrevented","events","activate","data","originalEvent","preventDefault","registerCloseOnCancel","getActionSelector","cancelEvent","cancel","registerCloseOnSave","saveEvent","save","setFunction","p","hasOwnProperty","content","setButtonText","action","button","Error","text","setRemoveOnClose","setReturnElement"],"mappings":";;;;;;;;AAuBAA,oBAAO,CACH,SACA,iBACA,oBACA,iBACA,iCACA,sBACA,sBACA,oBACA,4BACA,eACA,YACA,oBACD,SACCC,EACAC,UACAC,aACAC,SACAC,aACAC,cACAC,aACAC,YACAC,UACAC,QACAC,KACAC,gBA0BIC,gBAvBAC,oBACW,kCADXA,gBAEO,wBAFPA,iBAGQ,yBAHRA,gBAIO,wBAJPA,eAKM,uBALNA,iBAMQ,yBANRA,eAOM,uBAPNA,iBAQQ,gBARRA,eASM,OATNA,mBAUU,iBAVVA,sBAWa,qBAIbC,kBACS,eADTA,mBAEU,sBAYVC,aAAe,EAOfC,MAAQ,SAASC,WACZA,KAAOjB,EAAEiB,WACTC,MAAQC,KAAKF,KAAKG,KAAKP,sBACvBQ,OA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Y9C,KAAKD,KAAK2J,kBAAkBW,aAEvDC,aACK,IAAIC,MAAM,uBAAyBF,OAAS,mBAG/CtK,KAAKsD,SAASD,MAAOkH,OAAOE,KAAKpI,KAAKkI,UASjD1K,MAAM6B,UAAUiI,kBAAoB,SAASW,cAClC,iBAAmBA,OAAS,MAQvCzK,MAAM6B,UAAUgJ,iBAAmB,SAASnE,aACnCuC,cAAgBvC,QAQzB1G,MAAM6B,UAAUiJ,iBAAmB,SAASxI,cACnCf,aAAee,SAGjBtC"} \ No newline at end of file +{"version":3,"file":"modal.min.js","sources":["../src/modal.js"],"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 core/modal\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_filters/events',\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 FilterEvents,\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 this.focusOnClose = null;\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 * @fires event:filterContentUpdated\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 FilterEvents.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 FilterEvents.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 .catch(exception => {\n this.hide();\n throw 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 // If the focusOnClose was not set. Set the focus back to triggered element.\n if (!this.focusOnClose && document.activeElement) {\n this.focusOnClose = document.activeElement;\n }\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 this.getRoot().on(ModalEvents.hidden, () => {\n if (this.focusOnClose) {\n // Focus on the element that actually triggers the modal.\n this.focusOnClose.focus();\n }\n });\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 /**\n * Register a listener to close the dialogue when the delete button is pressed.\n *\n * @method registerCloseOnDelete\n */\n Modal.prototype.registerCloseOnDelete = function() {\n // Handle the clicking of the Cancel button.\n this.getModal().on(CustomEvents.events.activate, this.getActionSelector('delete'), function(e, data) {\n var deleteEvent = $.Event(ModalEvents.delete);\n this.getRoot().trigger(deleteEvent, this);\n\n if (!deleteEvent.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 /**\n * Set the return element for the modal.\n *\n * @param {Element|jQuery} element Element to focus when the modal is closed\n */\n Modal.prototype.setReturnElement = function(element) {\n this.focusOnClose = element;\n };\n\n return Modal;\n});\n"],"names":["define","$","Templates","Notification","KeyCodes","CustomEvents","ModalBackdrop","FilterEvents","ModalEvents","FocusLock","Pending","Aria","Fullscreen","backdropPromise","SELECTORS","TEMPLATES","modalCounter","Modal","root","modal","this","find","header","headerPromise","Deferred","title","titlePromise","body","bodyPromise","footer","footerPromise","hiddenSiblings","isAttached","bodyJS","footerJS","modalCount","attachmentPoint","document","createElement","append","focusOnClose","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","_ref","setFooter","showFooter","hasFooterContent","children","hideFooter","addClass","removeClass","setLarge","isLarge","setSmall","isSmall","setScrollable","classList","add","remove","calculateZIndex","items","zIndex","parseInt","item","itemZIndex","hasFocus","target","activeElement","has","hasTransitions","getElement","show","pendingPromise","backdrop","newIndex","newBackdropIndex","setZIndex","accessibilityShow","focus","shown","hideIfNotForm","done","untrapFocus","currentIndex","accessibilityHide","one","hidden","destroy","destroyed","unhide","get","hideSiblings","unhideSiblings","on","e","keyCode","escape","removeOnClose","click","closest","outsideClickEvent","Event","outsideClick","isDefaultPrevented","events","activate","data","originalEvent","preventDefault","registerCloseOnCancel","getActionSelector","cancelEvent","cancel","registerCloseOnSave","saveEvent","save","registerCloseOnDelete","deleteEvent","delete","setFunction","p","hasOwnProperty","content","setButtonText","action","button","Error","text","setRemoveOnClose","setReturnElement"],"mappings":";;;;;;;;AAuBAA,oBAAO,CACH,SACA,iB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EAAEqK,MAAM9J,YAAY4K,WAC/BrH,UAAUgB,QAAQoG,UAAW/J,MAE7B+J,UAAUX,uBACXG,KAAKC,cAAcC,iBAEfzJ,KAAK8I,mBACAV,eAEA3D,SAGfpC,KAAKrC,QASXH,MAAM6B,UAAUuI,sBAAwB,gBAE/BrH,WAAW8F,GAAGzJ,aAAaoK,OAAOC,SAAUtJ,KAAK2J,kBAAkB,UAAW,SAAShB,EAAGY,UACvFW,YAAcrL,EAAEqK,MAAM9J,YAAY+K,aACjCxH,UAAUgB,QAAQuG,YAAalK,MAE/BkK,YAAYd,uBACbG,KAAKC,cAAcC,iBAEfzJ,KAAK8I,mBACAV,eAEA3D,SAGfpC,KAAKrC,QAWXH,MAAM6B,UAAU4B,SAAW,SAASD,MAAO+G,iBACnCC,EAAIhH,YACa,iBAAVA,OAAuBA,MAAMiH,eAAe,UACnDD,EAAIxL,EAAEuB,YACJmD,QAAQF,OAGdgH,EAAE7H,MAAK,SAAS+H,SACZH,YAAYG,YAIf7H,KAAK3D,aAAauC,WAEZ+I,GAaXxK,MAAM6B,UAAU8I,cAAgB,SAASC,OAAQpH,aACvCqH,OAAS1K,KAAK+C,YAAY9C,KAAKD,KAAK2J,kBAAkBc,aAEvDC,aACK,IAAIC,MAAM,uBAAyBF,OAAS,mBAG/CzK,KAAKsD,SAASD,MAAOqH,OAAOE,KAAKvI,KAAKqI,UASjD7K,MAAM6B,UAAUiI,kBAAoB,SAASc,cAClC,iBAAmBA,OAAS,MAQvC5K,MAAM6B,UAAUmJ,iBAAmB,SAAStE,aACnCuC,cAAgBvC,QAQzB1G,MAAM6B,UAAUoJ,iBAAmB,SAAS3I,cACnCf,aAAee,SAGjBtC"} \ No newline at end of file diff --git a/lib/amd/build/modal_delete_cancel.min.js b/lib/amd/build/modal_delete_cancel.min.js new file mode 100644 index 00000000000..0e8c1e350ab --- /dev/null +++ b/lib/amd/build/modal_delete_cancel.min.js @@ -0,0 +1,10 @@ +define("core/modal_delete_cancel",["exports","core/modal","core/notification"],(function(_exports,_modal,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} +/** + * Contain the logic for the delete/cancel modal. + * + * @module core/modal_delete_cancel + * @copyright 2022 Laurent David + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_notification=_interopRequireDefault(_notification);class _default extends _modal.default{constructor(root){super(root),this.getFooter().find(this.getActionSelector("delete")).length||_notification.default.exception({message:"No delete button found"}),this.getFooter().find(this.getActionSelector("cancel")).length||_notification.default.exception({message:"No cancel button found"})}registerEventListeners(){super.registerEventListeners(),this.registerCloseOnDelete(),this.registerCloseOnCancel()}setFooter(){_notification.default.exception({message:"Can not change the footer of a delete cancel modal"})}setDeleteButtonText(value){return this.setButtonText("delete",value)}}return _exports.default=_default,_exports.default})); + +//# sourceMappingURL=modal_delete_cancel.min.js.map \ No newline at end of file diff --git a/lib/amd/build/modal_delete_cancel.min.js.map b/lib/amd/build/modal_delete_cancel.min.js.map new file mode 100644 index 00000000000..ea1e045867c --- /dev/null +++ b/lib/amd/build/modal_delete_cancel.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modal_delete_cancel.min.js","sources":["../src/modal_delete_cancel.js"],"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 the delete/cancel modal.\n *\n * @module core/modal_delete_cancel\n * @copyright 2022 Laurent David \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nimport Modal from 'core/modal';\nimport Notification from 'core/notification';\n\n/**\n * The Delete/Cancel Modal.\n *\n * @class\n * @extends module:core/modal\n */\nexport default class extends Modal {\n constructor(root) {\n super(root);\n\n if (!this.getFooter().find(this.getActionSelector('delete')).length) {\n Notification.exception({message: 'No delete button found'});\n }\n\n if (!this.getFooter().find(this.getActionSelector('cancel')).length) {\n Notification.exception({message: 'No cancel button found'});\n }\n }\n\n /**\n * Register all event listeners.\n */\n registerEventListeners() {\n // Call the parent registration.\n super.registerEventListeners();\n\n // Register to close on delete/cancel.\n this.registerCloseOnDelete();\n this.registerCloseOnCancel();\n }\n\n /**\n * Override parent implementation to prevent changing the footer content.\n */\n setFooter() {\n Notification.exception({message: 'Can not change the footer of a delete cancel modal'});\n }\n\n /**\n * Set the title of the delete button.\n *\n * @param {String|Promise} value The button text, or a Promise which will resolve it\n * @returns{Promise}\n */\n setDeleteButtonText(value) {\n return this.setButtonText('delete', value);\n }\n}\n"],"names":["Modal","constructor","root","this","getFooter","find","getActionSelector","length","exception","message","registerEventListeners","registerCloseOnDelete","registerCloseOnCancel","setFooter","setDeleteButtonText","value","setButtonText"],"mappings":";;;;;;;sMA+B6BA,eACzBC,YAAYC,YACFA,MAEDC,KAAKC,YAAYC,KAAKF,KAAKG,kBAAkB,WAAWC,8BAC5CC,UAAU,CAACC,QAAS,2BAGhCN,KAAKC,YAAYC,KAAKF,KAAKG,kBAAkB,WAAWC,8BAC5CC,UAAU,CAACC,QAAS,2BAOzCC,+BAEUA,8BAGDC,6BACAC,wBAMTC,kCACiBL,UAAU,CAACC,QAAS,uDASrCK,oBAAoBC,cACTZ,KAAKa,cAAc,SAAUD"} \ No newline at end of file diff --git a/lib/amd/build/modal_events.min.js b/lib/amd/build/modal_events.min.js index 1408806bdad..738b6249f98 100644 --- a/lib/amd/build/modal_events.min.js +++ b/lib/amd/build/modal_events.min.js @@ -6,6 +6,6 @@ * @copyright 2016 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define("core/modal_events",[],(function(){return{shown:"modal:shown",hidden:"modal:hidden",destroyed:"modal:destroyed",bodyRendered:"modal:bodyRendered",outsideClick:"modal:outsideClick",save:"modal-save-cancel:save",cancel:"modal-save-cancel:cancel"}})); +define("core/modal_events",[],(function(){return{shown:"modal:shown",hidden:"modal:hidden",destroyed:"modal:destroyed",bodyRendered:"modal:bodyRendered",outsideClick:"modal:outsideClick",save:"modal-save-cancel:save",delete:"modal-delete-cancel:delete",cancel:"modal-save-cancel:cancel"}})); //# sourceMappingURL=modal_events.min.js.map \ No newline at end of file diff --git a/lib/amd/build/modal_events.min.js.map b/lib/amd/build/modal_events.min.js.map index 903575909c9..f1e8c99e7dd 100644 --- a/lib/amd/build/modal_events.min.js.map +++ b/lib/amd/build/modal_events.min.js.map @@ -1 +1 @@ -{"version":3,"file":"modal_events.min.js","sources":["../src/modal_events.js"],"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 events a modal can fire.\n *\n * @module core/modal_events\n * @class modal_events\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([], function() {\n return {\n // Default events.\n shown: 'modal:shown',\n hidden: 'modal:hidden',\n destroyed: 'modal:destroyed',\n bodyRendered: 'modal:bodyRendered',\n outsideClick: 'modal:outsideClick',\n // ModalSaveCancel events.\n save: 'modal-save-cancel:save',\n cancel: 'modal-save-cancel:cancel',\n };\n});\n"],"names":["define","shown","hidden","destroyed","bodyRendered","outsideClick","save","cancel"],"mappings":";;;;;;;;AAuBAA,2BAAO,IAAI,iBACA,CAEHC,MAAO,cACPC,OAAQ,eACRC,UAAW,kBACXC,aAAc,qBACdC,aAAc,qBAEdC,KAAM,yBACNC,OAAQ"} \ No newline at end of file +{"version":3,"file":"modal_events.min.js","sources":["../src/modal_events.js"],"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 events a modal can fire.\n *\n * @module core/modal_events\n * @class modal_events\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([], function() {\n return {\n // Default events.\n shown: 'modal:shown',\n hidden: 'modal:hidden',\n destroyed: 'modal:destroyed',\n bodyRendered: 'modal:bodyRendered',\n outsideClick: 'modal:outsideClick',\n // ModalSaveCancel events.\n save: 'modal-save-cancel:save',\n 'delete': 'modal-delete-cancel:delete', // Delete is a reserved word.\n cancel: 'modal-save-cancel:cancel',\n };\n});\n"],"names":["define","shown","hidden","destroyed","bodyRendered","outsideClick","save","cancel"],"mappings":";;;;;;;;AAuBAA,2BAAO,IAAI,iBACA,CAEHC,MAAO,cACPC,OAAQ,eACRC,UAAW,kBACXC,aAAc,qBACdC,aAAc,qBAEdC,KAAM,gCACI,6BACVC,OAAQ"} \ No newline at end of file diff --git a/lib/amd/build/modal_factory.min.js b/lib/amd/build/modal_factory.min.js index 9f2e940ed21..7ead5a15b48 100644 --- a/lib/amd/build/modal_factory.min.js +++ b/lib/amd/build/modal_factory.min.js @@ -5,6 +5,6 @@ * @copyright 2016 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define("core/modal_factory",["jquery","core/modal_events","core/modal_registry","core/modal","core/modal_save_cancel","core/modal_cancel","core/local/modal/alert","core/templates","core/notification","core/custom_interaction_events","core/pending"],(function($,ModalEvents,ModalRegistry,Modal,ModalSaveCancel,ModalCancel,ModalAlert,Templates,Notification,CustomEvents,Pending){var TEMPLATES_DEFAULT="core/modal",TEMPLATES_SAVE_CANCEL="core/modal_save_cancel",TEMPLATES_CANCEL="core/modal_cancel",TEMPLATES_ALERT="core/local/modal/alert",TYPES={DEFAULT:"DEFAULT",SAVE_CANCEL:"SAVE_CANCEL",CANCEL:"CANCEL",ALERT:"ALERT"};ModalRegistry.register(TYPES.DEFAULT,Modal,TEMPLATES_DEFAULT),ModalRegistry.register(TYPES.SAVE_CANCEL,ModalSaveCancel,TEMPLATES_SAVE_CANCEL),ModalRegistry.register(TYPES.CANCEL,ModalCancel,TEMPLATES_CANCEL),ModalRegistry.register(TYPES.ALERT,ModalAlert,TEMPLATES_ALERT);var createFromType=function(registryConf,templateContext){var templateName=registryConf.template,modalPromise=Templates.render(templateName,templateContext).then((function(html){var modalElement=$(html);return function(registryConf,modalElement){return modalElement=$(modalElement),new(0,registryConf.module)(modalElement)}(registryConf,modalElement)})).fail(Notification.exception);return modalPromise};return{create:function(modalConfig,triggerElement){var registryConf,type=modalConfig.type||TYPES.DEFAULT,isLarge=!!modalConfig.large,isScrollable=!modalConfig.hasOwnProperty("scrollable")||modalConfig.scrollable,templateContext={};(registryConf=ModalRegistry.get(type))||Notification.exception({message:"Unable to find modal of type: "+type}),void 0!==modalConfig.templateContext&&(templateContext=modalConfig.templateContext);var modalPromise=createFromType(registryConf,templateContext).then((function(modal){return void 0!==modalConfig.title&&modal.setTitle(modalConfig.title),void 0!==modalConfig.body&&modal.setBody(modalConfig.body),void 0!==modalConfig.footer&&modal.setFooter(modalConfig.footer),modalConfig.buttons&&Object.entries(modalConfig.buttons).forEach((function(_ref){let[key,value]=_ref;modal.setButtonText(key,value)})),isLarge&&modal.setLarge(),void 0!==modalConfig.removeOnClose&&modal.setRemoveOnClose(modalConfig.removeOnClose),modal.setScrollable(isScrollable),modal}));return void 0!==triggerElement&&function(modalPromise,triggerElement,modalConfig){var actualTriggerElement=null,hasPreShowCallback="function"==typeof modalConfig.preShowCallback,triggeredCallback=function(e,data){var pendingPromise=new Pending("core/modal_factory:setUpTrigger:triggeredCallback");actualTriggerElement=$(e.currentTarget),modalPromise.then((function(modal){return hasPreShowCallback&&modalConfig.preShowCallback(actualTriggerElement,modal),modal.show(),modal})).then(pendingPromise.resolve),data.originalEvent.preventDefault()};if(Array.isArray(triggerElement)){var selector=triggerElement[1];triggerElement=triggerElement[0],CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,selector,triggeredCallback)}else CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,triggeredCallback);modalPromise.then((function(modal){return modal.getRoot().on(ModalEvents.hidden,(function(){null!==actualTriggerElement&&actualTriggerElement.focus()})),modal}))}(modalPromise,triggerElement,modalConfig),modalPromise},types:TYPES}})); +define("core/modal_factory",["jquery","core/modal_events","core/modal_registry","core/modal","core/modal_save_cancel","core/modal_delete_cancel","core/modal_cancel","core/local/modal/alert","core/templates","core/notification","core/custom_interaction_events","core/pending"],(function($,ModalEvents,ModalRegistry,Modal,ModalSaveCancel,ModalDeleteCancel,ModalCancel,ModalAlert,Templates,Notification,CustomEvents,Pending){var TEMPLATES_DEFAULT="core/modal",TEMPLATES_SAVE_CANCEL="core/modal_save_cancel",TEMPLATES_DELETE_CANCEL="core/modal_delete_cancel",TEMPLATES_CANCEL="core/modal_cancel",TEMPLATES_ALERT="core/local/modal/alert",TYPES={DEFAULT:"DEFAULT",SAVE_CANCEL:"SAVE_CANCEL",DELETE_CANCEL:"DELETE_CANCEL",CANCEL:"CANCEL",ALERT:"ALERT"};ModalRegistry.register(TYPES.DEFAULT,Modal,TEMPLATES_DEFAULT),ModalRegistry.register(TYPES.SAVE_CANCEL,ModalSaveCancel,TEMPLATES_SAVE_CANCEL),ModalRegistry.register(TYPES.DELETE_CANCEL,ModalDeleteCancel,TEMPLATES_DELETE_CANCEL),ModalRegistry.register(TYPES.CANCEL,ModalCancel,TEMPLATES_CANCEL),ModalRegistry.register(TYPES.ALERT,ModalAlert,TEMPLATES_ALERT);var createFromType=function(registryConf,templateContext){var templateName=registryConf.template,modalPromise=Templates.render(templateName,templateContext).then((function(html){var modalElement=$(html);return function(registryConf,modalElement){return modalElement=$(modalElement),new(0,registryConf.module)(modalElement)}(registryConf,modalElement)})).fail(Notification.exception);return modalPromise};return{create:function(modalConfig,triggerElement){var registryConf,type=modalConfig.type||TYPES.DEFAULT,isLarge=!!modalConfig.large,isScrollable=!modalConfig.hasOwnProperty("scrollable")||modalConfig.scrollable,templateContext={};(registryConf=ModalRegistry.get(type))||Notification.exception({message:"Unable to find modal of type: "+type}),void 0!==modalConfig.templateContext&&(templateContext=modalConfig.templateContext);var modalPromise=createFromType(registryConf,templateContext).then((function(modal){return void 0!==modalConfig.title&&modal.setTitle(modalConfig.title),void 0!==modalConfig.body&&modal.setBody(modalConfig.body),void 0!==modalConfig.footer&&modal.setFooter(modalConfig.footer),modalConfig.buttons&&Object.entries(modalConfig.buttons).forEach((function(_ref){let[key,value]=_ref;modal.setButtonText(key,value)})),isLarge&&modal.setLarge(),void 0!==modalConfig.removeOnClose&&modal.setRemoveOnClose(modalConfig.removeOnClose),modal.setScrollable(isScrollable),modal}));return void 0!==triggerElement&&function(modalPromise,triggerElement,modalConfig){var actualTriggerElement=null,hasPreShowCallback="function"==typeof modalConfig.preShowCallback,triggeredCallback=function(e,data){var pendingPromise=new Pending("core/modal_factory:setUpTrigger:triggeredCallback");actualTriggerElement=$(e.currentTarget),modalPromise.then((function(modal){return hasPreShowCallback&&modalConfig.preShowCallback(actualTriggerElement,modal),modal.show(),modal})).then(pendingPromise.resolve),data.originalEvent.preventDefault()};if(Array.isArray(triggerElement)){var selector=triggerElement[1];triggerElement=triggerElement[0],CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,selector,triggeredCallback)}else CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,triggeredCallback);modalPromise.then((function(modal){return modal.getRoot().on(ModalEvents.hidden,(function(){null!==actualTriggerElement&&actualTriggerElement.focus()})),modal}))}(modalPromise,triggerElement,modalConfig),modalPromise},types:TYPES}})); //# sourceMappingURL=modal_factory.min.js.map \ No newline at end of file diff --git a/lib/amd/build/modal_factory.min.js.map b/lib/amd/build/modal_factory.min.js.map index 2bfff96d792..e9bf1c4121b 100644 --- a/lib/amd/build/modal_factory.min.js.map +++ b/lib/amd/build/modal_factory.min.js.map @@ -1 +1 @@ -{"version":3,"file":"modal_factory.min.js","sources":["../src/modal_factory.js"],"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 * Create a modal.\n *\n * @module core/modal_factory\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/modal_events', 'core/modal_registry', 'core/modal',\n 'core/modal_save_cancel', 'core/modal_cancel', 'core/local/modal/alert',\n 'core/templates', 'core/notification', 'core/custom_interaction_events',\n 'core/pending'],\n function($, ModalEvents, ModalRegistry, Modal, ModalSaveCancel,\n ModalCancel, ModalAlert, Templates, Notification, CustomEvents, Pending) {\n\n // The templates for each type of modal.\n var TEMPLATES = {\n DEFAULT: 'core/modal',\n SAVE_CANCEL: 'core/modal_save_cancel',\n CANCEL: 'core/modal_cancel',\n ALERT: 'core/local/modal/alert',\n };\n\n /**\n * The available types of modals.\n *\n * @constant\n * @static\n * @public\n * @property {String} DEFAULT The default modal\n * @property {String} SAVE_CANCEL A modal which can be used to either save, or cancel.\n * @property {String} CANCEL A modal which displayed a cancel button\n * @property {String} ALERT An information modal which only displays information.\n */\n var TYPES = {\n DEFAULT: 'DEFAULT',\n SAVE_CANCEL: 'SAVE_CANCEL',\n CANCEL: 'CANCEL',\n ALERT: 'ALERT',\n };\n\n // Register the common set of modals.\n ModalRegistry.register(TYPES.DEFAULT, Modal, TEMPLATES.DEFAULT);\n ModalRegistry.register(TYPES.SAVE_CANCEL, ModalSaveCancel, TEMPLATES.SAVE_CANCEL);\n ModalRegistry.register(TYPES.CANCEL, ModalCancel, TEMPLATES.CANCEL);\n ModalRegistry.register(TYPES.ALERT, ModalAlert, TEMPLATES.ALERT);\n\n /**\n * Set up the events required to show the modal and return focus when the modal\n * is closed.\n *\n * @method setUpTrigger\n * @private\n * @param {Promise} modalPromise The modal instance\n * @param {object} triggerElement The jQuery element to open the modal\n * @param {object} modalConfig The modal configuration given to the factory\n */\n var setUpTrigger = function(modalPromise, triggerElement, modalConfig) {\n // The element that actually shows the modal.\n var actualTriggerElement = null;\n // Check if the client has provided a callback function to be called\n // before the modal is displayed.\n var hasPreShowCallback = (typeof modalConfig.preShowCallback == 'function');\n // Function to handle the trigger element being activated.\n var triggeredCallback = function(e, data) {\n var pendingPromise = new Pending('core/modal_factory:setUpTrigger:triggeredCallback');\n actualTriggerElement = $(e.currentTarget);\n modalPromise.then(function(modal) {\n if (hasPreShowCallback) {\n // If the client provided a pre-show callback then execute\n // it now before showing the modal.\n modalConfig.preShowCallback(actualTriggerElement, modal);\n }\n\n modal.show();\n\n return modal;\n })\n .then(pendingPromise.resolve);\n data.originalEvent.preventDefault();\n };\n\n // The trigger element can either be a single element or it can be an\n // element + selector pair to create a delegated event handler to trigger\n // the modal.\n if (Array.isArray(triggerElement)) {\n var selector = triggerElement[1];\n triggerElement = triggerElement[0];\n\n CustomEvents.define(triggerElement, [CustomEvents.events.activate]);\n triggerElement.on(CustomEvents.events.activate, selector, triggeredCallback);\n } else {\n CustomEvents.define(triggerElement, [CustomEvents.events.activate]);\n triggerElement.on(CustomEvents.events.activate, triggeredCallback);\n }\n\n modalPromise.then(function(modal) {\n modal.getRoot().on(ModalEvents.hidden, function() {\n // Focus on the trigger element that actually launched the modal.\n if (actualTriggerElement !== null) {\n actualTriggerElement.focus();\n }\n });\n\n return modal;\n });\n };\n\n /**\n * Create the correct instance of a modal based on the givem type. Sets up\n * the trigger between the modal and the trigger element.\n *\n * @method createFromElement\n * @private\n * @param {object} registryConf A config from the ModalRegistry\n * @param {object} modalElement The modal HTML jQuery object\n * @return {object} Modal instance\n */\n var createFromElement = function(registryConf, modalElement) {\n modalElement = $(modalElement);\n var Module = registryConf.module;\n var modal = new Module(modalElement);\n\n return modal;\n };\n\n /**\n * Create the correct modal instance for the given type, including loading\n * the correct template.\n *\n * @method createFromType\n * @private\n * @param {object} registryConf A config from the ModalRegistry\n * @param {object} templateContext The context to render the template with\n * @returns {promise} Resolved with a Modal instance\n */\n var createFromType = function(registryConf, templateContext) {\n var templateName = registryConf.template;\n\n var modalPromise = Templates.render(templateName, templateContext)\n .then(function(html) {\n var modalElement = $(html);\n return createFromElement(registryConf, modalElement);\n })\n .fail(Notification.exception);\n\n return modalPromise;\n };\n\n /**\n * Create a Modal instance.\n *\n * @method create\n * @param {object} modalConfig The configuration to create the modal instance\n * @param {object} triggerElement The trigger HTML jQuery object\n * @return {promise} Resolved with a Modal instance\n */\n var create = function(modalConfig, triggerElement) {\n var type = modalConfig.type || TYPES.DEFAULT;\n var isLarge = modalConfig.large ? true : false;\n // If 'scrollable' is not configured, set the modal to be scrollable by default.\n var isScrollable = modalConfig.hasOwnProperty('scrollable') ? modalConfig.scrollable : true;\n var registryConf = null;\n var templateContext = {};\n\n registryConf = ModalRegistry.get(type);\n\n if (!registryConf) {\n Notification.exception({message: 'Unable to find modal of type: ' + type});\n }\n\n if (typeof modalConfig.templateContext != 'undefined') {\n templateContext = modalConfig.templateContext;\n }\n\n var modalPromise = createFromType(registryConf, templateContext)\n .then(function(modal) {\n if (typeof modalConfig.title != 'undefined') {\n modal.setTitle(modalConfig.title);\n }\n\n if (typeof modalConfig.body != 'undefined') {\n modal.setBody(modalConfig.body);\n }\n\n if (typeof modalConfig.footer != 'undefined') {\n modal.setFooter(modalConfig.footer);\n }\n\n if (modalConfig.buttons) {\n Object.entries(modalConfig.buttons).forEach(function([key, value]) {\n modal.setButtonText(key, value);\n });\n }\n\n if (isLarge) {\n modal.setLarge();\n }\n\n if (typeof modalConfig.removeOnClose !== 'undefined') {\n // If configured remove the modal when hiding it.\n modal.setRemoveOnClose(modalConfig.removeOnClose);\n }\n\n modal.setScrollable(isScrollable);\n\n return modal;\n });\n\n if (typeof triggerElement != 'undefined') {\n setUpTrigger(modalPromise, triggerElement, modalConfig);\n }\n\n return modalPromise;\n };\n\n return {\n create: create,\n types: TYPES,\n };\n});\n"],"names":["define","$","ModalEvents","ModalRegistry","Modal","ModalSaveCancel","ModalCancel","ModalAlert","Templates","Notification","CustomEvents","Pending","TEMPLATES","TYPES","DEFAULT","SAVE_CANCEL","CANCEL","ALERT","register","createFromType","registryConf","templateContext","templateName","template","modalPromise","render","then","html","modalElement","Module","module","createFromElement","fail","exception","create","modalConfig","triggerElement","type","isLarge","large","isScrollable","hasOwnProperty","scrollable","get","message","modal","title","setTitle","body","setBody","footer","setFooter","buttons","Object","entries","forEach","key","value","setButtonText","setLarge","removeOnClose","setRemoveOnClose","setScrollable","actualTriggerElement","hasPreShowCallback","preShowCallback","triggeredCallback","e","data","pendingPromise","currentTarget","show","resolve","originalEvent","preventDefault","Array","isArray","selector","events","activate","on","getRoot","hidden","focus","setUpTrigger","types"],"mappings":";;;;;;;AAsBAA,4BAAO,CAAC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YAAYe,QAG5Bf,YAAYiB,SACZC,OAAOC,QAAQnB,YAAYiB,SAASG,SAAQ,mBAAUC,IAAKC,YACvDZ,MAAMa,cAAcF,IAAKC,UAI7BnB,SACAO,MAAMc,gBAG+B,IAA9BxB,YAAYyB,eAEnBf,MAAMgB,iBAAiB1B,YAAYyB,eAGvCf,MAAMiB,cAActB,cAEbK,qBAGc,IAAlBT,gBAxJI,SAASZ,aAAcY,eAAgBD,iBAElD4B,qBAAuB,KAGvBC,mBAA4D,mBAA/B7B,YAAY8B,gBAEzCC,kBAAoB,SAASC,EAAGC,UAC5BC,eAAiB,IAAI1D,QAAQ,qDACjCoD,qBAAuB9D,EAAEkE,EAAEG,eAC3B9C,aAAaE,MAAK,SAASmB,cACnBmB,oBAGA7B,YAAY8B,gBAAgBF,qBAAsBlB,OAGtDA,MAAM0B,OAEC1B,SAEVnB,KAAK2C,eAAeG,SACrBJ,KAAKK,cAAcC,qBAMnBC,MAAMC,QAAQxC,gBAAiB,KAC3ByC,SAAWzC,eAAe,GAC9BA,eAAiBA,eAAe,GAEhC1B,aAAaV,OAAOoC,eAAgB,CAAC1B,aAAaoE,OAAOC,WACzD3C,eAAe4C,GAAGtE,aAAaoE,OAAOC,SAAUF,SAAUX,wBAE1DxD,aAAaV,OAAOoC,eAAgB,CAAC1B,aAAaoE,OAAOC,WACzD3C,eAAe4C,GAAGtE,aAAaoE,OAAOC,SAAUb,mBAGpD1C,aAAaE,MAAK,SAASmB,cACvBA,MAAMoC,UAAUD,GAAG9E,YAAYgF,QAAQ,WAEN,OAAzBnB,sBACAA,qBAAqBoB,WAItBtC,SA0GPuC,CAAa5D,aAAcY,eAAgBD,aAGxCX,cAKP6D,MAAOxE"} \ No newline at end of file +{"version":3,"file":"modal_factory.min.js","sources":["../src/modal_factory.js"],"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 * Create a modal.\n *\n * @module core/modal_factory\n * @copyright 2016 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/modal_events', 'core/modal_registry', 'core/modal',\n 'core/modal_save_cancel', 'core/modal_delete_cancel', 'core/modal_cancel', 'core/local/modal/alert',\n 'core/templates', 'core/notification', 'core/custom_interaction_events',\n 'core/pending'],\n function($, ModalEvents, ModalRegistry, Modal, ModalSaveCancel, ModalDeleteCancel,\n ModalCancel, ModalAlert, Templates, Notification, CustomEvents, Pending) {\n\n // The templates for each type of modal.\n var TEMPLATES = {\n DEFAULT: 'core/modal',\n SAVE_CANCEL: 'core/modal_save_cancel',\n DELETE_CANCEL: 'core/modal_delete_cancel',\n CANCEL: 'core/modal_cancel',\n ALERT: 'core/local/modal/alert',\n };\n\n /**\n * The available types of modals.\n *\n * @constant\n * @static\n * @public\n * @property {String} DEFAULT The default modal\n * @property {String} SAVE_CANCEL A modal which can be used to either save, or cancel.\n * @property {String} DELETE_CANCEL A modal which can be used to either delete, or cancel.\n * @property {String} CANCEL A modal which displayed a cancel button\n * @property {String} ALERT An information modal which only displays information.\n */\n var TYPES = {\n DEFAULT: 'DEFAULT',\n SAVE_CANCEL: 'SAVE_CANCEL',\n DELETE_CANCEL: 'DELETE_CANCEL',\n CANCEL: 'CANCEL',\n ALERT: 'ALERT',\n };\n\n // Register the common set of modals.\n ModalRegistry.register(TYPES.DEFAULT, Modal, TEMPLATES.DEFAULT);\n ModalRegistry.register(TYPES.SAVE_CANCEL, ModalSaveCancel, TEMPLATES.SAVE_CANCEL);\n ModalRegistry.register(TYPES.DELETE_CANCEL, ModalDeleteCancel, TEMPLATES.DELETE_CANCEL);\n ModalRegistry.register(TYPES.CANCEL, ModalCancel, TEMPLATES.CANCEL);\n ModalRegistry.register(TYPES.ALERT, ModalAlert, TEMPLATES.ALERT);\n\n /**\n * Set up the events required to show the modal and return focus when the modal\n * is closed.\n *\n * @method setUpTrigger\n * @private\n * @param {Promise} modalPromise The modal instance\n * @param {object} triggerElement The jQuery element to open the modal\n * @param {object} modalConfig The modal configuration given to the factory\n */\n var setUpTrigger = function(modalPromise, triggerElement, modalConfig) {\n // The element that actually shows the modal.\n var actualTriggerElement = null;\n // Check if the client has provided a callback function to be called\n // before the modal is displayed.\n var hasPreShowCallback = (typeof modalConfig.preShowCallback == 'function');\n // Function to handle the trigger element being activated.\n var triggeredCallback = function(e, data) {\n var pendingPromise = new Pending('core/modal_factory:setUpTrigger:triggeredCallback');\n actualTriggerElement = $(e.currentTarget);\n modalPromise.then(function(modal) {\n if (hasPreShowCallback) {\n // If the client provided a pre-show callback then execute\n // it now before showing the modal.\n modalConfig.preShowCallback(actualTriggerElement, modal);\n }\n\n modal.show();\n\n return modal;\n })\n .then(pendingPromise.resolve);\n data.originalEvent.preventDefault();\n };\n\n // The trigger element can either be a single element or it can be an\n // element + selector pair to create a delegated event handler to trigger\n // the modal.\n if (Array.isArray(triggerElement)) {\n var selector = triggerElement[1];\n triggerElement = triggerElement[0];\n\n CustomEvents.define(triggerElement, [CustomEvents.events.activate]);\n triggerElement.on(CustomEvents.events.activate, selector, triggeredCallback);\n } else {\n CustomEvents.define(triggerElement, [CustomEvents.events.activate]);\n triggerElement.on(CustomEvents.events.activate, triggeredCallback);\n }\n\n modalPromise.then(function(modal) {\n modal.getRoot().on(ModalEvents.hidden, function() {\n // Focus on the trigger element that actually launched the modal.\n if (actualTriggerElement !== null) {\n actualTriggerElement.focus();\n }\n });\n\n return modal;\n });\n };\n\n /**\n * Create the correct instance of a modal based on the givem type. Sets up\n * the trigger between the modal and the trigger element.\n *\n * @method createFromElement\n * @private\n * @param {object} registryConf A config from the ModalRegistry\n * @param {object} modalElement The modal HTML jQuery object\n * @return {object} Modal instance\n */\n var createFromElement = function(registryConf, modalElement) {\n modalElement = $(modalElement);\n var Module = registryConf.module;\n var modal = new Module(modalElement);\n\n return modal;\n };\n\n /**\n * Create the correct modal instance for the given type, including loading\n * the correct template.\n *\n * @method createFromType\n * @private\n * @param {object} registryConf A config from the ModalRegistry\n * @param {object} templateContext The context to render the template with\n * @returns {promise} Resolved with a Modal instance\n */\n var createFromType = function(registryConf, templateContext) {\n var templateName = registryConf.template;\n\n var modalPromise = Templates.render(templateName, templateContext)\n .then(function(html) {\n var modalElement = $(html);\n return createFromElement(registryConf, modalElement);\n })\n .fail(Notification.exception);\n\n return modalPromise;\n };\n\n /**\n * Create a Modal instance.\n *\n * @method create\n * @param {object} modalConfig The configuration to create the modal instance\n * @param {object} triggerElement The trigger HTML jQuery object\n * @return {promise} Resolved with a Modal instance\n */\n var create = function(modalConfig, triggerElement) {\n var type = modalConfig.type || TYPES.DEFAULT;\n var isLarge = modalConfig.large ? true : false;\n // If 'scrollable' is not configured, set the modal to be scrollable by default.\n var isScrollable = modalConfig.hasOwnProperty('scrollable') ? modalConfig.scrollable : true;\n var registryConf = null;\n var templateContext = {};\n\n registryConf = ModalRegistry.get(type);\n\n if (!registryConf) {\n Notification.exception({message: 'Unable to find modal of type: ' + type});\n }\n\n if (typeof modalConfig.templateContext != 'undefined') {\n templateContext = modalConfig.templateContext;\n }\n\n var modalPromise = createFromType(registryConf, templateContext)\n .then(function(modal) {\n if (typeof modalConfig.title != 'undefined') {\n modal.setTitle(modalConfig.title);\n }\n\n if (typeof modalConfig.body != 'undefined') {\n modal.setBody(modalConfig.body);\n }\n\n if (typeof modalConfig.footer != 'undefined') {\n modal.setFooter(modalConfig.footer);\n }\n\n if (modalConfig.buttons) {\n Object.entries(modalConfig.buttons).forEach(function([key, value]) {\n modal.setButtonText(key, value);\n });\n }\n\n if (isLarge) {\n modal.setLarge();\n }\n\n if (typeof modalConfig.removeOnClose !== 'undefined') {\n // If configured remove the modal when hiding it.\n modal.setRemoveOnClose(modalConfig.removeOnClose);\n }\n\n modal.setScrollable(isScrollable);\n\n return modal;\n });\n\n if (typeof triggerElement != 'undefined') {\n setUpTrigger(modalPromise, triggerElement, modalConfig);\n }\n\n return modalPromise;\n };\n\n return {\n create: create,\n types: TYPES,\n };\n});\n"],"names":["define","$","ModalEvents","ModalRegistry","Modal","ModalSaveCancel","ModalDeleteCancel","ModalCancel","ModalAlert","Templates","Notification","CustomEvents","Pending","TEMPLATES","TYPES","DEFAULT","SAVE_CANCEL","DELETE_CANCEL","CANCEL","ALERT","register","createFromType","registryConf","templateContext","templateName","template","modalPromise","render","then","html","modalElement","Module","module","createFromElement","fail","exception","create","modalConfig","triggerElement","type","isLarge","large","isScrollable","hasOwnProperty","scrollable","get","message","modal","title","setTitle","body","setBody","footer","setFooter","buttons","Object","entries","forEach","key","value","setButtonText","setLarge","removeOnClose","setRemoveOnClose","setScrollable","actualTriggerElement","hasPreShowCallback","preShowCallback","triggeredCallback","e","data","pendingPromise","currentTarget","show","resolve","originalEvent","preventDefault","Array","isArray","selector","events","activate","on","getRoot","hidden","focus","setUpTrigger","types"],"mappings":";;;;;;;AAsBAA,4BAAO,CAAC,SAAU,oBAAqB,sBAAuB,aACtD,yBAA0B,2BAA4B,oBAAqB,yBAC3E,iBAAkB,oBAAqB,iCACvC,iBACJ,SAASC,EAAGC,YAAaC,cAAeC,MAAOC,gBAAiBC,kBAC5DC,YAAaC,WAAYC,UAAWC,aAAcC,aAAcC,aAGhEC,kBACS,aADTA,sBAEa,yBAFbA,wBAGe,2BAHfA,iBAIQ,oBAJRA,gBAKO,yBAePC,MAAQ,CACRC,QAAS,UACTC,YAAa,cACbC,cAAe,gBACfC,OAAQ,SACRC,MAAO,SAIXhB,cAAciB,SAASN,MAAMC,QAASX,MAAOS,mBAC7CV,cAAciB,SAASN,MAAME,YAAaX,gBAAiBQ,uBAC3DV,cAAciB,SAASN,MAAM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EAAGC,UAC5BC,eAAiB,IAAI3D,QAAQ,qDACjCqD,qBAAuBhE,EAAEoE,EAAEG,eAC3B9C,aAAaE,MAAK,SAASmB,cACnBmB,oBAGA7B,YAAY8B,gBAAgBF,qBAAsBlB,OAGtDA,MAAM0B,OAEC1B,SAEVnB,KAAK2C,eAAeG,SACrBJ,KAAKK,cAAcC,qBAMnBC,MAAMC,QAAQxC,gBAAiB,KAC3ByC,SAAWzC,eAAe,GAC9BA,eAAiBA,eAAe,GAEhC3B,aAAaX,OAAOsC,eAAgB,CAAC3B,aAAaqE,OAAOC,WACzD3C,eAAe4C,GAAGvE,aAAaqE,OAAOC,SAAUF,SAAUX,wBAE1DzD,aAAaX,OAAOsC,eAAgB,CAAC3B,aAAaqE,OAAOC,WACzD3C,eAAe4C,GAAGvE,aAAaqE,OAAOC,SAAUb,mBAGpD1C,aAAaE,MAAK,SAASmB,cACvBA,MAAMoC,UAAUD,GAAGhF,YAAYkF,QAAQ,WAEN,OAAzBnB,sBACAA,qBAAqBoB,WAItBtC,SA0GPuC,CAAa5D,aAAcY,eAAgBD,aAGxCX,cAKP6D,MAAOzE"} \ No newline at end of file diff --git a/lib/amd/build/notification.min.js b/lib/amd/build/notification.min.js index 2ce631fed1b..afb78ff0609 100644 --- a/lib/amd/build/notification.min.js +++ b/lib/amd/build/notification.min.js @@ -1,3 +1,3 @@ -define("core/notification",["exports","core/pending","core/log"],(function(_exports,_pending,_log){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.saveCancelPromise=_exports.saveCancel=_exports.init=_exports.fetchNotifications=_exports.exception=_exports.default=_exports.confirm=_exports.alert=_exports.addNotification=void 0,_pending=_interopRequireDefault(_pending),_log=_interopRequireDefault(_log);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let currentContextId=M.cfg.contextid;const notificationTypes={success:"core/notification_success",info:"core/notification_info",warning:"core/notification_warning",error:"core/notification_error"},Selectors={notificationRegion:"#".concat("user-notifications"),fallbackRegionParents:["#region-main",'[role="main"]',"body"]},fetchNotifications=async()=>(await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/ajax"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/ajax")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/ajax"]))).call([{methodname:"core_fetch_notifications",args:{contextid:currentContextId}}])[0].then(addNotifications);_exports.fetchNotifications=fetchNotifications;const addNotifications=notifications=>{if(!notifications.length)return Promise.resolve();const pendingPromise=new _pending.default("core/notification:addNotifications");return notifications.forEach((notification=>renderNotification(notification.template,notification.variables))),pendingPromise.resolve()},addNotification=notification=>{const pendingPromise=new _pending.default("core/notification:addNotifications");let template=notificationTypes.error;return(notification={closebutton:!0,announce:!0,type:"error",...notification}).template?(template=notification.template,delete notification.template):notification.type&&(void 0!==notificationTypes[notification.type]&&(template=notificationTypes[notification.type]),delete notification.type),renderNotification(template,notification).then(pendingPromise.resolve)};_exports.addNotification=addNotification;const renderNotification=async(template,variables)=>{if(void 0===variables.message||!variables.message)return void _log.default.debug("Notification received without content. Skipping.");const pendingPromise=new _pending.default("core/notification:renderNotification"),Templates=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/templates"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/templates")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/templates"]));Templates.renderForPromise(template,variables).then((_ref=>{let{html:html,js:js=""}=_ref;Templates.prependNodeContents(getNotificationRegion(),html,js)})).then(pendingPromise.resolve).catch(exception)},getNotificationRegion=()=>document.querySelector(Selectors.notificationRegion),alert=async(title,message,cancelText)=>{var pendingPromise=new _pending.default("core/notification:alert");const ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]));return ModalFactory.create({type:ModalFactory.types.ALERT,body:message,title:title,buttons:{cancel:cancelText},removeOnClose:!0}).then((function(modal){return modal.show(),pendingPromise.resolve(),modal}))};_exports.alert=alert;const confirm=(title,question,saveLabel,noLabel,saveCallback,cancelCallback)=>saveCancel(title,question,saveLabel,saveCallback,cancelCallback);_exports.confirm=confirm;const saveCancel=async function(title,question,saveLabel,saveCallback,cancelCallback){let{triggerElement:triggerElement=null}=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const pendingPromise=new _pending.default("core/notification:confirm"),[ModalFactory,ModalEvents]=await Promise.all(["function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]),"function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_events"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_events")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_events"])]);return ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:title,body:question,buttons:{save:saveLabel},removeOnClose:!0}).then((function(modal){return modal.show(),modal.getRoot().on(ModalEvents.save,saveCallback),modal.getRoot().on(ModalEvents.cancel,cancelCallback),modal.getRoot().on(ModalEvents.hidden,(()=>null==triggerElement?void 0:triggerElement.focus())),pendingPromise.resolve(),modal}))};_exports.saveCancel=saveCancel;const saveCancelPromise=function(title,question,saveLabel){let{triggerElement:triggerElement=null}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new Promise(((resolve,reject)=>{saveCancel(title,question,saveLabel,resolve,reject,{triggerElement:triggerElement})}))};_exports.saveCancelPromise=saveCancelPromise;const exception=async ex=>{const pendingPromise=new _pending.default("core/notification:displayException");if(ex.stack||(ex.stack=""),ex.debuginfo&&(ex.stack+=ex.debuginfo+"\n"),!ex.backtrace&&ex.stacktrace&&(ex.backtrace=ex.stacktrace),ex.backtrace){ex.stack+=ex.backtrace;const ln=ex.backtrace.match(/line ([^ ]*) of/),fn=ex.backtrace.match(/ of ([^:]*): /);ln&&ln[1]&&(ex.lineNumber=ln[1]),fn&&fn[1]&&(ex.fileName=fn[1],ex.fileName.length>30&&(ex.fileName="..."+ex.fileName.substr(ex.fileName.length-27)))}void 0===ex.name&&ex.errorcode&&(ex.name=ex.errorcode);(await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/yui"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/yui")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/yui"]))).use("moodle-core-notification-exception",(function(){new M.core.exception(ex).show(),pendingPromise.resolve()}))};_exports.exception=exception;const init=(contextId,notificationList)=>{currentContextId=contextId,(()=>{if(getNotificationRegion())return!1;const newRegion=document.createElement("span");newRegion.id="user-notifications",Selectors.fallbackRegionParents.some((selector=>{const targetRegion=document.querySelector(selector);return!!targetRegion&&(targetRegion.prepend(newRegion),!0)}))})(),addNotifications(notificationList)};_exports.init=init;var _default={init:init,fetchNotifications:fetchNotifications,addNotification:addNotification,alert:alert,confirm:confirm,saveCancel:saveCancel,saveCancelPromise:saveCancelPromise,exception:exception};return _exports.default=_default,_exports.default})); +define("core/notification",["exports","core/pending","core/log"],(function(_exports,_pending,_log){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.saveCancelPromise=_exports.saveCancel=_exports.init=_exports.fetchNotifications=_exports.exception=_exports.deleteCancelPromise=_exports.deleteCancel=_exports.default=_exports.confirm=_exports.alert=_exports.addNotification=void 0,_pending=_interopRequireDefault(_pending),_log=_interopRequireDefault(_log);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let currentContextId=M.cfg.contextid;const notificationTypes={success:"core/notification_success",info:"core/notification_info",warning:"core/notification_warning",error:"core/notification_error"},Selectors={notificationRegion:"#".concat("user-notifications"),fallbackRegionParents:["#region-main",'[role="main"]',"body"]},fetchNotifications=async()=>(await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/ajax"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/ajax")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/ajax"]))).call([{methodname:"core_fetch_notifications",args:{contextid:currentContextId}}])[0].then(addNotifications);_exports.fetchNotifications=fetchNotifications;const addNotifications=notifications=>{if(!notifications.length)return Promise.resolve();const pendingPromise=new _pending.default("core/notification:addNotifications");return notifications.forEach((notification=>renderNotification(notification.template,notification.variables))),pendingPromise.resolve()},addNotification=notification=>{const pendingPromise=new _pending.default("core/notification:addNotifications");let template=notificationTypes.error;return(notification={closebutton:!0,announce:!0,type:"error",...notification}).template?(template=notification.template,delete notification.template):notification.type&&(void 0!==notificationTypes[notification.type]&&(template=notificationTypes[notification.type]),delete notification.type),renderNotification(template,notification).then(pendingPromise.resolve)};_exports.addNotification=addNotification;const renderNotification=async(template,variables)=>{if(void 0===variables.message||!variables.message)return void _log.default.debug("Notification received without content. Skipping.");const pendingPromise=new _pending.default("core/notification:renderNotification"),Templates=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/templates"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/templates")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/templates"]));Templates.renderForPromise(template,variables).then((_ref=>{let{html:html,js:js=""}=_ref;Templates.prependNodeContents(getNotificationRegion(),html,js)})).then(pendingPromise.resolve).catch(exception)},getNotificationRegion=()=>document.querySelector(Selectors.notificationRegion),alert=async(title,message,cancelText)=>{var pendingPromise=new _pending.default("core/notification:alert");const ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]));return ModalFactory.create({type:ModalFactory.types.ALERT,body:message,title:title,buttons:{cancel:cancelText},removeOnClose:!0}).then((function(modal){return modal.show(),pendingPromise.resolve(),modal}))};_exports.alert=alert;const confirm=(title,question,saveLabel,noLabel,saveCallback,cancelCallback)=>saveCancel(title,question,saveLabel,saveCallback,cancelCallback);_exports.confirm=confirm;const saveCancel=async function(title,question,saveLabel,saveCallback,cancelCallback){let{triggerElement:triggerElement=null}=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const pendingPromise=new _pending.default("core/notification:confirm"),[ModalFactory,ModalEvents]=await Promise.all(["function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]),"function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_events"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_events")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_events"])]);return ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:title,body:question,buttons:{save:saveLabel},removeOnClose:!0}).then((function(modal){return modal.show(),modal.getRoot().on(ModalEvents.save,saveCallback),modal.getRoot().on(ModalEvents.cancel,cancelCallback),modal.getRoot().on(ModalEvents.hidden,(()=>null==triggerElement?void 0:triggerElement.focus())),pendingPromise.resolve(),modal}))};_exports.saveCancel=saveCancel;const deleteCancel=async function(title,question,deleteLabel,deleteCallback,cancelCallback){let{triggerElement:triggerElement=null}=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const pendingPromise=new _pending.default("core/notification:confirm"),[ModalFactory,ModalEvents]=await Promise.all(["function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]),"function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_events"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_events")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_events"])]);return ModalFactory.create({type:ModalFactory.types.DELETE_CANCEL,title:title,body:question,buttons:{delete:deleteLabel},removeOnClose:!0}).then((function(modal){return modal.show(),modal.getRoot().on(ModalEvents.delete,deleteCallback),modal.getRoot().on(ModalEvents.cancel,cancelCallback),modal.getRoot().on(ModalEvents.hidden,(()=>null==triggerElement?void 0:triggerElement.focus())),pendingPromise.resolve(),modal}))};_exports.deleteCancel=deleteCancel;const saveCancelPromise=function(title,question,saveLabel){let{triggerElement:triggerElement=null}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new Promise(((resolve,reject)=>{saveCancel(title,question,saveLabel,resolve,reject,{triggerElement:triggerElement})}))};_exports.saveCancelPromise=saveCancelPromise;const deleteCancelPromise=function(title,question,deleteLabel){let{triggerElement:triggerElement=null}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new Promise(((resolve,reject)=>{deleteCancel(title,question,deleteLabel,resolve,reject,{triggerElement:triggerElement})}))};_exports.deleteCancelPromise=deleteCancelPromise;const exception=async ex=>{const pendingPromise=new _pending.default("core/notification:displayException");if(ex.stack||(ex.stack=""),ex.debuginfo&&(ex.stack+=ex.debuginfo+"\n"),!ex.backtrace&&ex.stacktrace&&(ex.backtrace=ex.stacktrace),ex.backtrace){ex.stack+=ex.backtrace;const ln=ex.backtrace.match(/line ([^ ]*) of/),fn=ex.backtrace.match(/ of ([^:]*): /);ln&&ln[1]&&(ex.lineNumber=ln[1]),fn&&fn[1]&&(ex.fileName=fn[1],ex.fileName.length>30&&(ex.fileName="..."+ex.fileName.substr(ex.fileName.length-27)))}void 0===ex.name&&ex.errorcode&&(ex.name=ex.errorcode);(await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/yui"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/yui")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/yui"]))).use("moodle-core-notification-exception",(function(){new M.core.exception(ex).show(),pendingPromise.resolve()}))};_exports.exception=exception;const init=(contextId,notificationList)=>{currentContextId=contextId,(()=>{if(getNotificationRegion())return!1;const newRegion=document.createElement("span");newRegion.id="user-notifications",Selectors.fallbackRegionParents.some((selector=>{const targetRegion=document.querySelector(selector);return!!targetRegion&&(targetRegion.prepend(newRegion),!0)}))})(),addNotifications(notificationList)};_exports.init=init;var _default={init:init,fetchNotifications:fetchNotifications,addNotification:addNotification,alert:alert,confirm:confirm,saveCancel:saveCancel,saveCancelPromise:saveCancelPromise,deleteCancelPromise:deleteCancelPromise,exception:exception};return _exports.default=_default,_exports.default})); //# sourceMappingURL=notification.min.js.map \ No newline at end of file diff --git a/lib/amd/build/notification.min.js.map b/lib/amd/build/notification.min.js.map index a3ee50d1ddc..bf5e49c6424 100644 --- a/lib/amd/build/notification.min.js.map +++ b/lib/amd/build/notification.min.js.map @@ -1 +1 @@ -{"version":3,"file":"notification.min.js","sources":["../src/notification.js"],"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 * Notification manager for in-page notifications in Moodle.\n *\n * @module core/notification\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 2.9\n */\nimport Pending from 'core/pending';\nimport Log from 'core/log';\n\nlet currentContextId = M.cfg.contextid;\n\nconst notificationTypes = {\n success: 'core/notification_success',\n info: 'core/notification_info',\n warning: 'core/notification_warning',\n error: 'core/notification_error',\n};\n\nconst notificationRegionId = 'user-notifications';\n\nconst Selectors = {\n notificationRegion: `#${notificationRegionId}`,\n fallbackRegionParents: [\n '#region-main',\n '[role=\"main\"]',\n 'body',\n ],\n};\n\nconst setupTargetRegion = () => {\n let targetRegion = getNotificationRegion();\n if (targetRegion) {\n return false;\n }\n\n const newRegion = document.createElement('span');\n newRegion.id = notificationRegionId;\n\n return Selectors.fallbackRegionParents.some(selector => {\n const targetRegion = document.querySelector(selector);\n\n if (targetRegion) {\n targetRegion.prepend(newRegion);\n return true;\n }\n\n return false;\n });\n};\n\n/**\n * A notification object displayed to a user.\n *\n * @typedef {Object} Notification\n * @property {string} message The body of the notification\n * @property {string} type The type of notification to add (error, warning, info, success).\n * @property {Boolean} closebutton Whether to show the close button.\n * @property {Boolean} announce Whether to announce to screen readers.\n */\n\n/**\n * Poll the server for any new notifications.\n *\n * @method\n * @returns {Promise}\n */\nexport const fetchNotifications = async() => {\n const Ajax = await import('core/ajax');\n\n return Ajax.call([{\n methodname: 'core_fetch_notifications',\n args: {\n contextid: currentContextId\n }\n }])[0]\n .then(addNotifications);\n};\n\n/**\n * Add all of the supplied notifications.\n *\n * @method\n * @param {Notification[]} notifications The list of notificaitons\n * @returns {Promise}\n */\nconst addNotifications = notifications => {\n if (!notifications.length) {\n return Promise.resolve();\n }\n\n const pendingPromise = new Pending('core/notification:addNotifications');\n notifications.forEach(notification => renderNotification(notification.template, notification.variables));\n\n return pendingPromise.resolve();\n};\n\n/**\n * Add a notification to the page.\n *\n * Note: This does not cause the notification to be added to the session.\n *\n * @method\n * @param {Notification} notification The notification to add.\n * @returns {Promise}\n */\nexport const addNotification = notification => {\n const pendingPromise = new Pending('core/notification:addNotifications');\n\n let template = notificationTypes.error;\n\n notification = {\n closebutton: true,\n announce: true,\n type: 'error',\n ...notification,\n };\n\n if (notification.template) {\n template = notification.template;\n delete notification.template;\n } else if (notification.type) {\n if (typeof notificationTypes[notification.type] !== 'undefined') {\n template = notificationTypes[notification.type];\n }\n delete notification.type;\n }\n\n return renderNotification(template, notification)\n .then(pendingPromise.resolve);\n};\n\nconst renderNotification = async(template, variables) => {\n if (typeof variables.message === 'undefined' || !variables.message) {\n Log.debug('Notification received without content. Skipping.');\n return;\n }\n\n const pendingPromise = new Pending('core/notification:renderNotification');\n const Templates = await import('core/templates');\n\n Templates.renderForPromise(template, variables)\n .then(({html, js = ''}) => {\n Templates.prependNodeContents(getNotificationRegion(), html, js);\n\n return;\n })\n .then(pendingPromise.resolve)\n .catch(exception);\n};\n\nconst getNotificationRegion = () => document.querySelector(Selectors.notificationRegion);\n\n/**\n * Alert dialogue.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} message\n * @param {String|Promise} cancelText\n * @returns {Promise}\n */\nexport const alert = async(title, message, cancelText) => {\n var pendingPromise = new Pending('core/notification:alert');\n\n const ModalFactory = await import('core/modal_factory');\n\n return ModalFactory.create({\n type: ModalFactory.types.ALERT,\n body: message,\n title: title,\n buttons: {\n cancel: cancelText,\n },\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n\n pendingPromise.resolve();\n return modal;\n });\n};\n\n/**\n * The confirm has now been replaced with a save and cancel dialogue.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} question\n * @param {String|Promise} saveLabel\n * @param {String|Promise} noLabel\n * @param {String|Promise} saveCallback\n * @param {String|Promise} cancelCallback\n * @returns {Promise}\n */\nexport const confirm = (title, question, saveLabel, noLabel, saveCallback, cancelCallback) =>\n saveCancel(title, question, saveLabel, saveCallback, cancelCallback);\n\n/**\n * The Save and Cancel dialogue helper.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} question\n * @param {String|Promise} saveLabel\n * @param {String|Promise} saveCallback\n * @param {String|Promise} cancelCallback\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @returns {Promise}\n */\nexport const saveCancel = async(title, question, saveLabel, saveCallback, cancelCallback, {\n triggerElement = null,\n} = {}) => {\n const pendingPromise = new Pending('core/notification:confirm');\n\n const [\n ModalFactory,\n ModalEvents,\n ] = await Promise.all([\n import('core/modal_factory'),\n import('core/modal_events'),\n ]);\n\n return ModalFactory.create({\n type: ModalFactory.types.SAVE_CANCEL,\n title: title,\n body: question,\n buttons: {\n // Note: The noLabel is no longer supported.\n save: saveLabel,\n },\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n\n modal.getRoot().on(ModalEvents.save, saveCallback);\n modal.getRoot().on(ModalEvents.cancel, cancelCallback);\n modal.getRoot().on(ModalEvents.hidden, () => triggerElement?.focus());\n pendingPromise.resolve();\n\n return modal;\n });\n};\n\n/**\n * Add all of the supplied notifications.\n *\n * @param {Promise|String} title The header of the modal\n * @param {Promise|String} question What do we want the user to confirm\n * @param {Promise|String} saveLabel The modal action link text\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @return {Promise}\n */\nexport const saveCancelPromise = (title, question, saveLabel, {\n triggerElement = null,\n} = {}) => new Promise((resolve, reject) => {\n saveCancel(title, question, saveLabel, resolve, reject, {triggerElement});\n});\n\n/**\n * Wrap M.core.exception.\n *\n * @method\n * @param {Error} ex\n */\nexport const exception = async ex => {\n const pendingPromise = new Pending('core/notification:displayException');\n\n // Fudge some parameters.\n if (!ex.stack) {\n ex.stack = '';\n }\n\n if (ex.debuginfo) {\n ex.stack += ex.debuginfo + '\\n';\n }\n\n if (!ex.backtrace && ex.stacktrace) {\n ex.backtrace = ex.stacktrace;\n }\n\n if (ex.backtrace) {\n ex.stack += ex.backtrace;\n const ln = ex.backtrace.match(/line ([^ ]*) of/);\n const fn = ex.backtrace.match(/ of ([^:]*): /);\n if (ln && ln[1]) {\n ex.lineNumber = ln[1];\n }\n if (fn && fn[1]) {\n ex.fileName = fn[1];\n if (ex.fileName.length > 30) {\n ex.fileName = '...' + ex.fileName.substr(ex.fileName.length - 27);\n }\n }\n }\n\n if (typeof ex.name === 'undefined' && ex.errorcode) {\n ex.name = ex.errorcode;\n }\n\n const Y = await import('core/yui');\n Y.use('moodle-core-notification-exception', function() {\n var modal = new M.core.exception(ex);\n\n modal.show();\n\n pendingPromise.resolve();\n });\n};\n\n/**\n * Initialise the page for the suppled context, and displaying the supplied notifications.\n *\n * @method\n * @param {Number} contextId\n * @param {Notification[]} notificationList\n */\nexport const init = (contextId, notificationList) => {\n currentContextId = contextId;\n\n // Setup the message target region if it isn't setup already\n setupTargetRegion();\n\n // Add provided notifications.\n addNotifications(notificationList);\n};\n\n// To maintain backwards compatability we export default here.\nexport default {\n init,\n fetchNotifications,\n addNotification,\n alert,\n confirm,\n saveCancel,\n saveCancelPromise,\n exception,\n};\n"],"names":["currentContextId","M","cfg","contextid","notificationTypes","success","info","warning","error","Selectors","notificationRegion","fallbackRegionParents","fetchNotifications","async","call","methodname","args","then","addNotifications","notifications","length","Promise","resolve","pendingPromise","Pending","forEach","notification","renderNotification","template","variables","addNotification","closebutton","announce","type","message","debug","Templates","renderForPromise","_ref","html","js","prependNodeContents","getNotificationRegion","catch","exception","document","querySelector","alert","title","cancelText","ModalFactory","create","types","ALERT","body","buttons","cancel","removeOnClose","modal","show","confirm","question","saveLabel","noLabel","saveCallback","cancelCallback","saveCancel","triggerElement","ModalEvents","all","SAVE_CANCEL","save","getRoot","on","hidden","focus","saveCancelPromise","reject","ex","stack","debuginfo","backtrace","stacktrace","ln","match","fn","lineNumber","fileName","substr","name","errorcode","use","core","init","contextId","notificationList","newRegion","createElement","id","some","selector","targetRegion","prepend","setupTargetRegion"],"mappings":"4oBA0BIA,iBAAmBC,EAAEC,IAAIC,gBAEvBC,kBAAoB,CACtBC,QAAU,4BACVC,KAAU,yBACVC,QAAU,4BACVC,MAAU,2BAKRC,UAAY,CACdC,8BAHyB,sBAIzBC,sBAAuB,CACnB,eACA,gBACA,SAyCKC,mBAAqBC,8lBAGlBC,KAAK,CAAC,CACdC,WAAY,2BACZC,KAAM,CACFb,UAAWH,qBAEf,GACHiB,KAAKC,uEAUJA,iBAAmBC,oBAChBA,cAAcC,cACRC,QAAQC,gBAGbC,eAAiB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eAAeD,iDAWVuE,KAAO,CAACC,UAAWC,oBAC5B/F,iBAAmB8F,UApSG,SACHpD,+BAER,QAGLsD,UAAYnD,SAASoD,cAAc,QACzCD,UAAUE,GAlBe,qBAoBlBzF,UAAUE,sBAAsBwF,MAAKC,iBAClCC,aAAexD,SAASC,cAAcsD,kBAExCC,eACAA,aAAaC,QAAQN,YACd,OAyRfO,GAGArF,iBAAiB6E,mDAIN,CACXF,KAAAA,KACAjF,mBAAAA,mBACAkB,gBAAAA,gBACAiB,MAAAA,MACAa,QAAAA,QACAM,WAAAA,WACAU,kBAAAA,kBACAhC,UAAAA"} \ No newline at end of file +{"version":3,"file":"notification.min.js","sources":["../src/notification.js"],"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 * Notification manager for in-page notifications in Moodle.\n *\n * @module core/notification\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 2.9\n */\nimport Pending from 'core/pending';\nimport Log from 'core/log';\n\nlet currentContextId = M.cfg.contextid;\n\nconst notificationTypes = {\n success: 'core/notification_success',\n info: 'core/notification_info',\n warning: 'core/notification_warning',\n error: 'core/notification_error',\n};\n\nconst notificationRegionId = 'user-notifications';\n\nconst Selectors = {\n notificationRegion: `#${notificationRegionId}`,\n fallbackRegionParents: [\n '#region-main',\n '[role=\"main\"]',\n 'body',\n ],\n};\n\nconst setupTargetRegion = () => {\n let targetRegion = getNotificationRegion();\n if (targetRegion) {\n return false;\n }\n\n const newRegion = document.createElement('span');\n newRegion.id = notificationRegionId;\n\n return Selectors.fallbackRegionParents.some(selector => {\n const targetRegion = document.querySelector(selector);\n\n if (targetRegion) {\n targetRegion.prepend(newRegion);\n return true;\n }\n\n return false;\n });\n};\n\n/**\n * A notification object displayed to a user.\n *\n * @typedef {Object} Notification\n * @property {string} message The body of the notification\n * @property {string} type The type of notification to add (error, warning, info, success).\n * @property {Boolean} closebutton Whether to show the close button.\n * @property {Boolean} announce Whether to announce to screen readers.\n */\n\n/**\n * Poll the server for any new notifications.\n *\n * @method\n * @returns {Promise}\n */\nexport const fetchNotifications = async() => {\n const Ajax = await import('core/ajax');\n\n return Ajax.call([{\n methodname: 'core_fetch_notifications',\n args: {\n contextid: currentContextId\n }\n }])[0]\n .then(addNotifications);\n};\n\n/**\n * Add all of the supplied notifications.\n *\n * @method\n * @param {Notification[]} notifications The list of notificaitons\n * @returns {Promise}\n */\nconst addNotifications = notifications => {\n if (!notifications.length) {\n return Promise.resolve();\n }\n\n const pendingPromise = new Pending('core/notification:addNotifications');\n notifications.forEach(notification => renderNotification(notification.template, notification.variables));\n\n return pendingPromise.resolve();\n};\n\n/**\n * Add a notification to the page.\n *\n * Note: This does not cause the notification to be added to the session.\n *\n * @method\n * @param {Notification} notification The notification to add.\n * @returns {Promise}\n */\nexport const addNotification = notification => {\n const pendingPromise = new Pending('core/notification:addNotifications');\n\n let template = notificationTypes.error;\n\n notification = {\n closebutton: true,\n announce: true,\n type: 'error',\n ...notification,\n };\n\n if (notification.template) {\n template = notification.template;\n delete notification.template;\n } else if (notification.type) {\n if (typeof notificationTypes[notification.type] !== 'undefined') {\n template = notificationTypes[notification.type];\n }\n delete notification.type;\n }\n\n return renderNotification(template, notification)\n .then(pendingPromise.resolve);\n};\n\nconst renderNotification = async(template, variables) => {\n if (typeof variables.message === 'undefined' || !variables.message) {\n Log.debug('Notification received without content. Skipping.');\n return;\n }\n\n const pendingPromise = new Pending('core/notification:renderNotification');\n const Templates = await import('core/templates');\n\n Templates.renderForPromise(template, variables)\n .then(({html, js = ''}) => {\n Templates.prependNodeContents(getNotificationRegion(), html, js);\n\n return;\n })\n .then(pendingPromise.resolve)\n .catch(exception);\n};\n\nconst getNotificationRegion = () => document.querySelector(Selectors.notificationRegion);\n\n/**\n * Alert dialogue.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} message\n * @param {String|Promise} cancelText\n * @returns {Promise}\n */\nexport const alert = async(title, message, cancelText) => {\n var pendingPromise = new Pending('core/notification:alert');\n\n const ModalFactory = await import('core/modal_factory');\n\n return ModalFactory.create({\n type: ModalFactory.types.ALERT,\n body: message,\n title: title,\n buttons: {\n cancel: cancelText,\n },\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n\n pendingPromise.resolve();\n return modal;\n });\n};\n\n/**\n * The confirm has now been replaced with a save and cancel dialogue.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} question\n * @param {String|Promise} saveLabel\n * @param {String|Promise} noLabel\n * @param {String|Promise} saveCallback\n * @param {String|Promise} cancelCallback\n * @returns {Promise}\n */\nexport const confirm = (title, question, saveLabel, noLabel, saveCallback, cancelCallback) =>\n saveCancel(title, question, saveLabel, saveCallback, cancelCallback);\n\n/**\n * The Save and Cancel dialogue helper.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} question\n * @param {String|Promise} saveLabel\n * @param {String|Promise} saveCallback\n * @param {String|Promise} cancelCallback\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @returns {Promise}\n */\nexport const saveCancel = async(title, question, saveLabel, saveCallback, cancelCallback, {\n triggerElement = null,\n} = {}) => {\n const pendingPromise = new Pending('core/notification:confirm');\n\n const [\n ModalFactory,\n ModalEvents,\n ] = await Promise.all([\n import('core/modal_factory'),\n import('core/modal_events'),\n ]);\n\n return ModalFactory.create({\n type: ModalFactory.types.SAVE_CANCEL,\n title: title,\n body: question,\n buttons: {\n // Note: The noLabel is no longer supported.\n save: saveLabel,\n },\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n\n modal.getRoot().on(ModalEvents.save, saveCallback);\n modal.getRoot().on(ModalEvents.cancel, cancelCallback);\n modal.getRoot().on(ModalEvents.hidden, () => triggerElement?.focus());\n pendingPromise.resolve();\n\n return modal;\n });\n};\n\n/**\n * The Delete and Cancel dialogue helper.\n *\n * @method\n * @param {String|Promise} title\n * @param {String|Promise} question\n * @param {String|Promise} deleteLabel\n * @param {String|Promise} deleteCallback\n * @param {String|Promise} cancelCallback\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @returns {Promise}\n */\nexport const deleteCancel = async(title, question, deleteLabel, deleteCallback, cancelCallback, {\n triggerElement = null,\n} = {}) => {\n const pendingPromise = new Pending('core/notification:confirm');\n\n const [\n ModalFactory,\n ModalEvents,\n ] = await Promise.all([\n import('core/modal_factory'),\n import('core/modal_events'),\n ]);\n\n return ModalFactory.create({\n type: ModalFactory.types.DELETE_CANCEL,\n title: title,\n body: question,\n buttons: {\n 'delete': deleteLabel\n },\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n\n modal.getRoot().on(ModalEvents.delete, deleteCallback);\n modal.getRoot().on(ModalEvents.cancel, cancelCallback);\n modal.getRoot().on(ModalEvents.hidden, () => triggerElement?.focus());\n pendingPromise.resolve();\n\n return modal;\n });\n};\n\n\n/**\n * Add all of the supplied notifications.\n *\n * @param {Promise|String} title The header of the modal\n * @param {Promise|String} question What do we want the user to confirm\n * @param {Promise|String} saveLabel The modal action link text\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @return {Promise}\n */\nexport const saveCancelPromise = (title, question, saveLabel, {\n triggerElement = null,\n} = {}) => new Promise((resolve, reject) => {\n saveCancel(title, question, saveLabel, resolve, reject, {triggerElement});\n});\n\n/**\n * Add all of the supplied notifications.\n *\n * @param {Promise|String} title The header of the modal\n * @param {Promise|String} question What do we want the user to confirm\n * @param {Promise|String} deleteLabel The modal action link text\n * @param {Object} options\n * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden)\n * @return {Promise}\n */\nexport const deleteCancelPromise = (title, question, deleteLabel, {\n triggerElement = null,\n} = {}) => new Promise((resolve, reject) => {\n deleteCancel(title, question, deleteLabel, resolve, reject, {triggerElement});\n});\n\n/**\n * Wrap M.core.exception.\n *\n * @method\n * @param {Error} ex\n */\nexport const exception = async ex => {\n const pendingPromise = new Pending('core/notification:displayException');\n\n // Fudge some parameters.\n if (!ex.stack) {\n ex.stack = '';\n }\n\n if (ex.debuginfo) {\n ex.stack += ex.debuginfo + '\\n';\n }\n\n if (!ex.backtrace && ex.stacktrace) {\n ex.backtrace = ex.stacktrace;\n }\n\n if (ex.backtrace) {\n ex.stack += ex.backtrace;\n const ln = ex.backtrace.match(/line ([^ ]*) of/);\n const fn = ex.backtrace.match(/ of ([^:]*): /);\n if (ln && ln[1]) {\n ex.lineNumber = ln[1];\n }\n if (fn && fn[1]) {\n ex.fileName = fn[1];\n if (ex.fileName.length > 30) {\n ex.fileName = '...' + ex.fileName.substr(ex.fileName.length - 27);\n }\n }\n }\n\n if (typeof ex.name === 'undefined' && ex.errorcode) {\n ex.name = ex.errorcode;\n }\n\n const Y = await import('core/yui');\n Y.use('moodle-core-notification-exception', function() {\n var modal = new M.core.exception(ex);\n\n modal.show();\n\n pendingPromise.resolve();\n });\n};\n\n/**\n * Initialise the page for the suppled context, and displaying the supplied notifications.\n *\n * @method\n * @param {Number} contextId\n * @param {Notification[]} notificationList\n */\nexport const init = (contextId, notificationList) => {\n currentContextId = contextId;\n\n // Setup the message target region if it isn't setup already.\n setupTargetRegion();\n\n // Add provided notifications.\n addNotifications(notificationList);\n};\n\n// To maintain backwards compatability we export default here.\nexport default {\n init,\n fetchNotifications,\n addNotification,\n alert,\n confirm,\n saveCancel,\n saveCancelPromise,\n deleteCancelPromise,\n exception,\n};\n"],"names":["currentContextId","M","cfg","contextid","notificationTypes","success","info","warning","error","Selectors","notificationRegion","fallbackRegionParents","fetchNotifications","async","call","methodname","args","then","addNotifications","notifications","length","Promise","resolve","pendingPromise","Pending","forEach","notification","renderNotification","template","variables","addNotification","closebutton","announce","type","message","debug","Templates","renderForPromise","_ref","html","js","prependNodeContents","getNotificationRegion","catch","exception","document","querySelector","alert","title","cancelText","ModalFactory","create","types","ALERT","body","buttons","cancel","removeOnClose","modal","show","confirm","question","saveLabel","noLabel","saveCallback","cancelCallback","saveCancel","triggerElement","ModalEvents","all","SAVE_CANCEL","save","getRoot","on","hidden","focus","deleteCancel","deleteLabel","deleteCallback","DELETE_CANCEL","delete","saveCancelPromise","reject","deleteCancelPromise","ex","stack","debuginfo","backtrace","stacktrace","ln","match","fn","lineNumber","fileName","substr","name","errorcode","use","core","init","contextId","notificationList","newRegion","createElement","id","some","selector","targetRegion","prepend","setupTargetRegion"],"mappings":"+rBA0BIA,iBAAmBC,EAAEC,IAAIC,gBAEvBC,kBAAoB,CACtBC,QAAU,4BACVC,KAAU,yBACVC,QAAU,4BACVC,MAAU,2BAKRC,UAAY,CACdC,8BAHyB,sBAIzBC,sBAAuB,CACnB,eACA,gBACA,SAyCKC,mBAAqBC,8lBAGlBC,KAAK,CAAC,CACdC,WAAY,2BACZC,KAAM,CACFb,UAAWH,qBAEf,GACHiB,KAAKC,uEAUJA,iBAAmBC,oBAChBA,cAAcC,cACRC,QAAQC,gBAGbC,eAAiB,IAAIC,iBAAQ,6CACnCL,cAAcM,SAAQC,cAAgBC,mBAAmBD,aAAaE,SAAUF,aAAaG,aAEtFN,eAAeD,WAYbQ,gBAAkBJ,qBACrBH,eAAiB,IAAIC,iBAAQ,0CAE/BI,SAAWxB,kBAAkBI,aAEjCkB,aAAe,CACXK,aAAgB,EAChBC,UAAgB,EAChBC,KAAgB,WACbP,eAGUE,UACbA,SAAWF,aAAaE,gBACjBF,aAAaE,UACbF,aAAaO,YACgC,IAAzC7B,kBAAkBsB,aAAaO,QACtCL,SAAWxB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AC1BD,IAAMA,GAAG,KACTL,GAAGQ,WAAaH,GAAG,IAEnBE,IAAMA,GAAG,KACTP,GAAGS,SAAWF,GAAG,GACbP,GAAGS,SAASzE,OAAS,KACrBgE,GAAGS,SAAW,MAAQT,GAAGS,SAASC,OAAOV,GAAGS,SAASzE,OAAS,WAKnD,IAAZgE,GAAGW,MAAwBX,GAAGY,YACrCZ,GAAGW,KAAOX,GAAGY,6lBAIfC,IAAI,sCAAsC,WAC5B,IAAIhG,EAAEiG,KAAKtD,UAAUwC,IAE3BzB,OAENpC,eAAeD,iDAWV6E,KAAO,CAACC,UAAWC,oBAC5BrG,iBAAmBoG,UApWG,SACH1D,+BAER,QAGL4D,UAAYzD,SAAS0D,cAAc,QACzCD,UAAUE,GAlBe,qBAoBlB/F,UAAUE,sBAAsB8F,MAAKC,iBAClCC,aAAe9D,SAASC,cAAc4D,kBAExCC,eACAA,aAAaC,QAAQN,YACd,OAyVfO,GAGA3F,iBAAiBmF,mDAIN,CACXF,KAAAA,KACAvF,mBAAAA,mBACAkB,gBAAAA,gBACAiB,MAAAA,MACAa,QAAAA,QACAM,WAAAA,WACAe,kBAAAA,kBACAE,oBAAAA,oBACAvC,UAAAA"} \ No newline at end of file diff --git a/lib/amd/build/utility.min.js b/lib/amd/build/utility.min.js index afe04bbc7fd..2c85e2d66d0 100644 --- a/lib/amd/build/utility.min.js +++ b/lib/amd/build/utility.min.js @@ -1,3 +1,3 @@ -define("core/utility",["core/str","core/pending","core/toast","core/notification"],(function(Str,_pending,_toast,_notification){var obj;Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}let registered=!1;const getModalString=(dataset,type,field)=>dataset["".concat(type).concat(field,"Str")]?Str.get_string.apply(null,JSON.parse(dataset["".concat(type).concat(field,"Str")])):Promise.resolve(dataset["".concat(type).concat(field)]),displayConfirmation=(source,type)=>(0,_notification.saveCancelPromise)(getModalString(source.dataset,type,"Title"),getModalString(source.dataset,type,"Content"),getModalString(source.dataset,type,"YesButton")).then((()=>{if("true"===source.dataset["".concat(type,"Toast")]){const stringForToast=getModalString(source.dataset,type,"ToastConfirmation");"string"==typeof stringForToast?(0,_toast.add)(stringForToast):stringForToast.then((str=>(0,_toast.add)(str))).catch((e=>(0,_notification.exception)(e)))}window.location.href=source.dataset["".concat(type,"Destination")]})).catch((()=>{}));registered||((()=>{document.addEventListener("click",(e=>{const confirmRequest=e.target.closest('[data-confirmation="modal"]');confirmRequest&&(e.preventDefault(),displayConfirmation(confirmRequest,"confirmation"));const modalConfirmation=e.target.closest('[data-modal="confirmation"]');modalConfirmation&&(e.preventDefault(),displayConfirmation(modalConfirmation,"modal"));const alertRequest=e.target.closest('[data-modal="alert"]');alertRequest&&(e.preventDefault(),(async(title,content)=>{const pendingPromise=new _pending.default("core/confirm:alert"),ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]));ModalFactory.create({type:ModalFactory.types.ALERT,title:title,body:content,removeOnClose:!0}).then((function(modal){return modal.show(),pendingPromise.resolve(),modal}))})(getModalString(alertRequest.dataset,"modal","Title"),getModalString(alertRequest.dataset,"modal","Content")))}))})(),registered=!0)})); +define("core/utility",["core/str","core/pending","core/toast","core/notification"],(function(Str,_pending,_toast,_notification){var obj;Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}let registered=!1;const getModalString=(dataset,type,field)=>dataset["".concat(type).concat(field,"Str")]?Str.get_string.apply(null,JSON.parse(dataset["".concat(type).concat(field,"Str")])):Promise.resolve(dataset["".concat(type).concat(field)]),displayConfirmation=(source,type)=>{let confirmationPromise=null;return confirmationPromise="".concat(type,"Type")in source.dataset&&"delete"===source.dataset["".concat(type,"Type")]?(0,_notification.deleteCancelPromise)(getModalString(source.dataset,type,"Title"),getModalString(source.dataset,type,"Content"),getModalString(source.dataset,type,"YesButton")):(0,_notification.saveCancelPromise)(getModalString(source.dataset,type,"Title"),getModalString(source.dataset,type,"Content"),getModalString(source.dataset,type,"YesButton")),confirmationPromise.then((()=>{if("true"===source.dataset["".concat(type,"Toast")]){const stringForToast=getModalString(source.dataset,type,"ToastConfirmation");"string"==typeof stringForToast?(0,_toast.add)(stringForToast):stringForToast.then((str=>(0,_toast.add)(str))).catch((e=>(0,_notification.exception)(e)))}window.location.href=source.dataset["".concat(type,"Destination")]})).catch((()=>{}))};registered||((()=>{document.addEventListener("click",(e=>{const confirmRequest=e.target.closest('[data-confirmation="modal"]');confirmRequest&&(e.preventDefault(),displayConfirmation(confirmRequest,"confirmation"));const modalConfirmation=e.target.closest('[data-modal="confirmation"]');modalConfirmation&&(e.preventDefault(),displayConfirmation(modalConfirmation,"modal"));const alertRequest=e.target.closest('[data-modal="alert"]');alertRequest&&(e.preventDefault(),(async(title,content)=>{const pendingPromise=new _pending.default("core/confirm:alert"),ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]));ModalFactory.create({type:ModalFactory.types.ALERT,title:title,body:content,removeOnClose:!0}).then((function(modal){return modal.show(),pendingPromise.resolve(),modal}))})(getModalString(alertRequest.dataset,"modal","Title"),getModalString(alertRequest.dataset,"modal","Content")))}))})(),registered=!0)})); //# sourceMappingURL=utility.min.js.map \ No newline at end of file diff --git a/lib/amd/build/utility.min.js.map b/lib/amd/build/utility.min.js.map index 5d933cf94fa..e65990969f5 100644 --- a/lib/amd/build/utility.min.js.map +++ b/lib/amd/build/utility.min.js.map @@ -1 +1 @@ -{"version":3,"file":"utility.min.js","sources":["../src/utility.js"],"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 * Javascript handling for HTML attributes. This module gets autoloaded on page load.\n *\n * With the appropriate HTML attributes, various functionalities defined in this module can be used such as a displaying\n * an alert or a confirmation modal, etc.\n *\n * @module core/utility\n * @copyright 2021 Andrew Nicols \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 4.0\n *\n * @example Calling the confirmation modal to delete a block\n *\n * // The following is an example of how to use this module via an indirect PHP call with a button.\n *\n * $controls[] = new action_menu_link_secondary(\n * $deleteactionurl,\n * new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),\n * $str,\n * [\n * 'class' => 'editing_delete',\n * 'data-modal' => 'confirmation', // Needed so this module will pick it up in the click handler.\n * 'data-modal-title-str' => json_encode(['deletecheck_modal', 'block']),\n * 'data-modal-content-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),\n * 'data-modal-yes-button-str' => json_encode(['delete', 'core']),\n * 'data-modal-toast' => 'true', // Can be set to inform the user that their action was a success.\n * 'data-modal-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),\n * 'data-modal-destination' => $deleteconfirmationurl->out(false), // Where do you want to direct the user?\n * ]\n * );\n */\n\nimport * as Str from 'core/str';\nimport Pending from 'core/pending';\nimport {add as addToast} from 'core/toast';\nimport {saveCancelPromise, exception} from 'core/notification';\n\n// We want to ensure that we only initialize the listeners only once.\nlet registered = false;\n\n/**\n * Either fetch the string or return it from the dom node.\n *\n * @method getConfirmationString\n * @private\n * @param {HTMLElement} dataset The page element to fetch dataset items in\n * @param {String} type The type of string to fetch\n * @param {String} field The dataset field name to fetch the contents of\n * @return {Promise}\n *\n */\nconst getModalString = (dataset, type, field) => {\n if (dataset[`${type}${field}Str`]) {\n return Str.get_string.apply(null, JSON.parse(dataset[`${type}${field}Str`]));\n }\n return Promise.resolve(dataset[`${type}${field}`]);\n};\n\n/**\n * Display a save/cancel confirmation.\n *\n * @private\n * @param {HTMLElement} source The title of the confirmation\n * @param {String} type The content of the confirmation\n * @returns {Promise}\n */\nconst displayConfirmation = (source, type) => {\n return saveCancelPromise(\n getModalString(source.dataset, type, 'Title'),\n getModalString(source.dataset, type, 'Content'),\n getModalString(source.dataset, type, 'YesButton'),\n )\n .then(() => {\n if (source.dataset[`${type}Toast`] === 'true') {\n const stringForToast = getModalString(source.dataset, type, 'ToastConfirmation');\n if (typeof stringForToast === \"string\") {\n addToast(stringForToast);\n } else {\n stringForToast.then(str => addToast(str)).catch(e => exception(e));\n }\n }\n window.location.href = source.dataset[`${type}Destination`];\n return;\n }).catch(() => {\n return;\n });\n};\n\n/**\n * Display an alert and return the promise from it.\n *\n * @private\n * @param {String} title The title of the alert\n * @param {String} content The content of the alert\n * @returns {Promise}\n */\nconst displayAlert = async(title, content) => {\n const pendingPromise = new Pending('core/confirm:alert');\n\n const ModalFactory = await import('core/modal_factory');\n\n return ModalFactory.create({\n type: ModalFactory.types.ALERT,\n title: title,\n body: content,\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n pendingPromise.resolve();\n\n return modal;\n });\n};\n\n/**\n * Set up the listeners for the confirmation modal widget within the page.\n *\n * @method registerConfirmationListeners\n * @private\n */\nconst registerConfirmationListeners = () => {\n document.addEventListener('click', e => {\n const confirmRequest = e.target.closest('[data-confirmation=\"modal\"]');\n if (confirmRequest) {\n e.preventDefault();\n displayConfirmation(confirmRequest, 'confirmation');\n }\n\n const modalConfirmation = e.target.closest('[data-modal=\"confirmation\"]');\n if (modalConfirmation) {\n e.preventDefault();\n displayConfirmation(modalConfirmation, 'modal');\n }\n\n const alertRequest = e.target.closest('[data-modal=\"alert\"]');\n if (alertRequest) {\n e.preventDefault();\n displayAlert(\n getModalString(alertRequest.dataset, 'modal', 'Title'),\n getModalString(alertRequest.dataset, 'modal', 'Content'),\n );\n }\n });\n};\n\nif (!registered) {\n registerConfirmationListeners();\n registered = true;\n}\n"],"names":["registered","getModalString","dataset","type","field","Str","get_string","apply","JSON","parse","Promise","resolve","displayConfirmation","source","then","stringForToast","str","catch","e","window","location","href","document","addEventListener","confirmRequest","target","closest","preventDefault","modalConfirmation","alertRequest","async","title","content","pendingPromise","Pending","ModalFactory","create","types","ALERT","body","removeOnClose","modal","show","displayAlert","registerConfirmationListeners"],"mappings":"iwCAqDIA,YAAa,QAaXC,eAAiB,CAACC,QAASC,KAAMC,QAC/BF,kBAAWC,aAAOC,cACXC,IAAIC,WAAWC,MAAM,KAAMC,KAAKC,MAAMP,kBAAWC,aAAOC,gBAE5DM,QAAQC,QAAQT,kBAAWC,aAAOC,SAWvCQ,oBAAsB,CAACC,OAAQV,QAC1B,mCACHF,eAAeY,OAAOX,QAASC,KAAM,SACrCF,eAAeY,OAAOX,QAASC,KAAM,WACrCF,eAAeY,OAAOX,QAASC,KAAM,cAExCW,MAAK,QACqC,SAAnCD,OAAOX,kBAAWC,eAAyB,OACrCY,eAAiBd,eAAeY,OAAOX,QAASC,KAAM,qBAC9B,iBAAnBY,8BACEA,gBAETA,eAAeD,MAAKE,MAAO,cAASA,OAAMC,OAAMC,IAAK,2BAAUA,KAGvEC,OAAOC,SAASC,KAAOR,OAAOX,kBAAWC,wBAE1Cc,OAAM,SA+DRjB,aAzBiC,MAClCsB,SAASC,iBAAiB,SAASL,UACzBM,eAAiBN,EAAEO,OAAOC,QAAQ,+BACpCF,iBACAN,EAAES,iBACFf,oBAAoBY,eAAgB,uBAGlCI,kBAAoBV,EAAEO,OAAOC,QAAQ,+BACvCE,oBACAV,EAAES,iBACFf,oBAAoBgB,kBAAmB,gBAGrCC,aAAeX,EAAEO,OAAOC,QAAQ,wBAClCG,eACAX,EAAES,iBAzCOG,OAAMC,MAAOC,iBACxBC,eAAiB,IAAIC,iBAAQ,sBAE7BC,2nBAECA,aAAaC,OAAO,CACvBjC,KAAMgC,aAAaE,MAAMC,MACzBP,MAAOA,MACPQ,KAAMP,QACNQ,eAAe,IAElB1B,MAAK,SAAS2B,cACXA,MAAMC,OACNT,eAAetB,UAER8B,UA2BHE,CACI1C,eAAe4B,aAAa3B,QAAS,QAAS,SAC9CD,eAAe4B,aAAa3B,QAAS,QAAS,iBAO1D0C,GACA5C,YAAa"} \ No newline at end of file +{"version":3,"file":"utility.min.js","sources":["../src/utility.js"],"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 * Javascript handling for HTML attributes. This module gets autoloaded on page load.\n *\n * With the appropriate HTML attributes, various functionalities defined in this module can be used such as a displaying\n * an alert or a confirmation modal, etc.\n *\n * @module core/utility\n * @copyright 2021 Andrew Nicols \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since 4.0\n *\n * @example Calling the confirmation modal to delete a block\n *\n * // The following is an example of how to use this module via an indirect PHP call with a button.\n *\n * $controls[] = new action_menu_link_secondary(\n * $deleteactionurl,\n * new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),\n * $str,\n * [\n * 'class' => 'editing_delete',\n * 'data-modal' => 'confirmation', // Needed so this module will pick it up in the click handler.\n * 'data-modal-title-str' => json_encode(['deletecheck_modal', 'block']),\n * 'data-modal-content-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),\n * 'data-modal-yes-button-str' => json_encode(['delete', 'core']),\n * 'data-modal-toast' => 'true', // Can be set to inform the user that their action was a success.\n * 'data-modal-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),\n * 'data-modal-destination' => $deleteconfirmationurl->out(false), // Where do you want to direct the user?\n * ]\n * );\n */\n\nimport * as Str from 'core/str';\nimport Pending from 'core/pending';\nimport {add as addToast} from 'core/toast';\nimport {saveCancelPromise, deleteCancelPromise, exception} from 'core/notification';\n\n// We want to ensure that we only initialize the listeners only once.\nlet registered = false;\n\n/**\n * Either fetch the string or return it from the dom node.\n *\n * @method getConfirmationString\n * @private\n * @param {HTMLElement} dataset The page element to fetch dataset items in\n * @param {String} type The type of string to fetch\n * @param {String} field The dataset field name to fetch the contents of\n * @return {Promise}\n *\n */\nconst getModalString = (dataset, type, field) => {\n if (dataset[`${type}${field}Str`]) {\n return Str.get_string.apply(null, JSON.parse(dataset[`${type}${field}Str`]));\n }\n return Promise.resolve(dataset[`${type}${field}`]);\n};\n\n/**\n * Display a save/cancel confirmation.\n *\n * @private\n * @param {HTMLElement} source The title of the confirmation\n * @param {String} type The content of the confirmation\n * @returns {Promise}\n */\nconst displayConfirmation = (source, type) => {\n let confirmationPromise = null;\n if (`${type}Type` in source.dataset && source.dataset[`${type}Type`] === 'delete') {\n confirmationPromise = deleteCancelPromise(\n getModalString(source.dataset, type, 'Title'),\n getModalString(source.dataset, type, 'Content'),\n getModalString(source.dataset, type, 'YesButton'),\n );\n } else {\n confirmationPromise = saveCancelPromise(\n getModalString(source.dataset, type, 'Title'),\n getModalString(source.dataset, type, 'Content'),\n getModalString(source.dataset, type, 'YesButton'),\n );\n }\n return confirmationPromise.then(() => {\n if (source.dataset[`${type}Toast`] === 'true') {\n const stringForToast = getModalString(source.dataset, type, 'ToastConfirmation');\n if (typeof stringForToast === \"string\") {\n addToast(stringForToast);\n } else {\n stringForToast.then(str => addToast(str)).catch(e => exception(e));\n }\n }\n window.location.href = source.dataset[`${type}Destination`];\n return;\n }).catch(() => {\n return;\n });\n};\n\n/**\n * Display an alert and return the promise from it.\n *\n * @private\n * @param {String} title The title of the alert\n * @param {String} content The content of the alert\n * @returns {Promise}\n */\nconst displayAlert = async(title, content) => {\n const pendingPromise = new Pending('core/confirm:alert');\n\n const ModalFactory = await import('core/modal_factory');\n\n return ModalFactory.create({\n type: ModalFactory.types.ALERT,\n title: title,\n body: content,\n removeOnClose: true,\n })\n .then(function(modal) {\n modal.show();\n pendingPromise.resolve();\n\n return modal;\n });\n};\n\n/**\n * Set up the listeners for the confirmation modal widget within the page.\n *\n * @method registerConfirmationListeners\n * @private\n */\nconst registerConfirmationListeners = () => {\n document.addEventListener('click', e => {\n const confirmRequest = e.target.closest('[data-confirmation=\"modal\"]');\n if (confirmRequest) {\n e.preventDefault();\n displayConfirmation(confirmRequest, 'confirmation');\n }\n\n const modalConfirmation = e.target.closest('[data-modal=\"confirmation\"]');\n if (modalConfirmation) {\n e.preventDefault();\n displayConfirmation(modalConfirmation, 'modal');\n }\n\n const alertRequest = e.target.closest('[data-modal=\"alert\"]');\n if (alertRequest) {\n e.preventDefault();\n displayAlert(\n getModalString(alertRequest.dataset, 'modal', 'Title'),\n getModalString(alertRequest.dataset, 'modal', 'Content'),\n );\n }\n });\n};\n\nif (!registered) {\n registerConfirmationListeners();\n registered = true;\n}\n"],"names":["registered","getModalString","dataset","type","field","Str","get_string","apply","JSON","parse","Promise","resolve","displayConfirmation","source","confirmationPromise","then","stringForToast","str","catch","e","window","location","href","document","addEventListener","confirmRequest","target","closest","preventDefault","modalConfirmation","alertRequest","async","title","content","pendingPromise","Pending","ModalFactory","create","types","ALERT","body","removeOnClose","modal","show","displayAlert","registerConfirmationListeners"],"mappings":"iwCAqDIA,YAAa,QAaXC,eAAiB,CAACC,QAASC,KAAMC,QAC/BF,kBAAWC,aAAOC,cACXC,IAAIC,WAAWC,MAAM,KAAMC,KAAKC,MAAMP,kBAAWC,aAAOC,gBAE5DM,QAAQC,QAAQT,kBAAWC,aAAOC,SAWvCQ,oBAAsB,CAACC,OAAQV,YAC7BW,oBAAsB,YAEtBA,oBADA,UAAGX,eAAcU,OAAOX,SAA6C,WAAlCW,OAAOX,kBAAWC,eAC/B,qCAClBF,eAAeY,OAAOX,QAASC,KAAM,SACrCF,eAAeY,OAAOX,QAASC,KAAM,WACrCF,eAAeY,OAAOX,QAASC,KAAM,eAGnB,mCAClBF,eAAeY,OAAOX,QAASC,KAAM,SACrCF,eAAeY,OAAOX,QAASC,KAAM,WACrCF,eAAeY,OAAOX,QAASC,KAAM,cAGtCW,oBAAoBC,MAAK,QACW,SAAnCF,OAAOX,kBAAWC,eAAyB,OACrCa,eAAiBf,eAAeY,OAAOX,QAASC,KAAM,qBAC9B,iBAAnBa,8BACEA,gBAETA,eAAeD,MAAKE,MAAO,cAASA,OAAMC,OAAMC,IAAK,2BAAUA,KAGvEC,OAAOC,SAASC,KAAOT,OAAOX,kBAAWC,wBAE1Ce,OAAM,UA+DRlB,aAzBiC,MAClCuB,SAASC,iBAAiB,SAASL,UACzBM,eAAiBN,EAAEO,OAAOC,QAAQ,+BACpCF,iBACAN,EAAES,iBACFhB,oBAAoBa,eAAgB,uBAGlCI,kBAAoBV,EAAEO,OAAOC,QAAQ,+BACvCE,oBACAV,EAAES,iBACFhB,oBAAoBiB,kBAAmB,gBAGrCC,aAAeX,EAAEO,OAAOC,QAAQ,wBAClCG,eACAX,EAAES,iBAzCOG,OAAMC,MAAOC,iBACxBC,eAAiB,IAAIC,iBAAQ,sBAE7BC,2nBAECA,aAAaC,OAAO,CACvBlC,KAAMiC,aAAaE,MAAMC,MACzBP,MAAOA,MACPQ,KAAMP,QACNQ,eAAe,IAElB1B,MAAK,SAAS2B,cACXA,MAAMC,OACNT,eAAevB,UAER+B,UA2BHE,CACI3C,eAAe6B,aAAa5B,QAAS,QAAS,SAC9CD,eAAe6B,aAAa5B,QAAS,QAAS,iBAO1D2C,GACA7C,YAAa"} \ No newline at end of file diff --git a/lib/amd/src/modal.js b/lib/amd/src/modal.js index 17617c1d836..8a1fdd725ae 100644 --- a/lib/amd/src/modal.js +++ b/lib/amd/src/modal.js @@ -911,6 +911,30 @@ define([ }.bind(this)); }; + + /** + * Register a listener to close the dialogue when the delete button is pressed. + * + * @method registerCloseOnDelete + */ + Modal.prototype.registerCloseOnDelete = function() { + // Handle the clicking of the Cancel button. + this.getModal().on(CustomEvents.events.activate, this.getActionSelector('delete'), function(e, data) { + var deleteEvent = $.Event(ModalEvents.delete); + this.getRoot().trigger(deleteEvent, this); + + if (!deleteEvent.isDefaultPrevented()) { + data.originalEvent.preventDefault(); + + if (this.removeOnClose) { + this.destroy(); + } else { + this.hide(); + } + } + }.bind(this)); + }; + /** * Set or resolve and set the value using the function. * diff --git a/lib/amd/src/modal_delete_cancel.js b/lib/amd/src/modal_delete_cancel.js new file mode 100644 index 00000000000..611a87f0f69 --- /dev/null +++ b/lib/amd/src/modal_delete_cancel.js @@ -0,0 +1,73 @@ +// 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 . + +/** + * Contain the logic for the delete/cancel modal. + * + * @module core/modal_delete_cancel + * @copyright 2022 Laurent David + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +import Modal from 'core/modal'; +import Notification from 'core/notification'; + +/** + * The Delete/Cancel Modal. + * + * @class + * @extends module:core/modal + */ +export default class extends Modal { + constructor(root) { + super(root); + + if (!this.getFooter().find(this.getActionSelector('delete')).length) { + Notification.exception({message: 'No delete button found'}); + } + + if (!this.getFooter().find(this.getActionSelector('cancel')).length) { + Notification.exception({message: 'No cancel button found'}); + } + } + + /** + * Register all event listeners. + */ + registerEventListeners() { + // Call the parent registration. + super.registerEventListeners(); + + // Register to close on delete/cancel. + this.registerCloseOnDelete(); + this.registerCloseOnCancel(); + } + + /** + * Override parent implementation to prevent changing the footer content. + */ + setFooter() { + Notification.exception({message: 'Can not change the footer of a delete cancel modal'}); + } + + /** + * Set the title of the delete button. + * + * @param {String|Promise} value The button text, or a Promise which will resolve it + * @returns{Promise} + */ + setDeleteButtonText(value) { + return this.setButtonText('delete', value); + } +} diff --git a/lib/amd/src/modal_events.js b/lib/amd/src/modal_events.js index 0820e989cc9..af2fc60570a 100644 --- a/lib/amd/src/modal_events.js +++ b/lib/amd/src/modal_events.js @@ -31,6 +31,7 @@ define([], function() { outsideClick: 'modal:outsideClick', // ModalSaveCancel events. save: 'modal-save-cancel:save', + 'delete': 'modal-delete-cancel:delete', // Delete is a reserved word. cancel: 'modal-save-cancel:cancel', }; }); diff --git a/lib/amd/src/modal_factory.js b/lib/amd/src/modal_factory.js index 662448c3035..3295da4e489 100644 --- a/lib/amd/src/modal_factory.js +++ b/lib/amd/src/modal_factory.js @@ -21,16 +21,17 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define(['jquery', 'core/modal_events', 'core/modal_registry', 'core/modal', - 'core/modal_save_cancel', 'core/modal_cancel', 'core/local/modal/alert', + 'core/modal_save_cancel', 'core/modal_delete_cancel', 'core/modal_cancel', 'core/local/modal/alert', 'core/templates', 'core/notification', 'core/custom_interaction_events', 'core/pending'], - function($, ModalEvents, ModalRegistry, Modal, ModalSaveCancel, + function($, ModalEvents, ModalRegistry, Modal, ModalSaveCancel, ModalDeleteCancel, ModalCancel, ModalAlert, Templates, Notification, CustomEvents, Pending) { // The templates for each type of modal. var TEMPLATES = { DEFAULT: 'core/modal', SAVE_CANCEL: 'core/modal_save_cancel', + DELETE_CANCEL: 'core/modal_delete_cancel', CANCEL: 'core/modal_cancel', ALERT: 'core/local/modal/alert', }; @@ -43,12 +44,14 @@ define(['jquery', 'core/modal_events', 'core/modal_registry', 'core/modal', * @public * @property {String} DEFAULT The default modal * @property {String} SAVE_CANCEL A modal which can be used to either save, or cancel. + * @property {String} DELETE_CANCEL A modal which can be used to either delete, or cancel. * @property {String} CANCEL A modal which displayed a cancel button * @property {String} ALERT An information modal which only displays information. */ var TYPES = { DEFAULT: 'DEFAULT', SAVE_CANCEL: 'SAVE_CANCEL', + DELETE_CANCEL: 'DELETE_CANCEL', CANCEL: 'CANCEL', ALERT: 'ALERT', }; @@ -56,6 +59,7 @@ define(['jquery', 'core/modal_events', 'core/modal_registry', 'core/modal', // Register the common set of modals. ModalRegistry.register(TYPES.DEFAULT, Modal, TEMPLATES.DEFAULT); ModalRegistry.register(TYPES.SAVE_CANCEL, ModalSaveCancel, TEMPLATES.SAVE_CANCEL); + ModalRegistry.register(TYPES.DELETE_CANCEL, ModalDeleteCancel, TEMPLATES.DELETE_CANCEL); ModalRegistry.register(TYPES.CANCEL, ModalCancel, TEMPLATES.CANCEL); ModalRegistry.register(TYPES.ALERT, ModalAlert, TEMPLATES.ALERT); diff --git a/lib/amd/src/notification.js b/lib/amd/src/notification.js index 639ba420561..2aaf3fba926 100644 --- a/lib/amd/src/notification.js +++ b/lib/amd/src/notification.js @@ -261,6 +261,54 @@ export const saveCancel = async(title, question, saveLabel, saveCallback, cancel }); }; +/** + * The Delete and Cancel dialogue helper. + * + * @method + * @param {String|Promise} title + * @param {String|Promise} question + * @param {String|Promise} deleteLabel + * @param {String|Promise} deleteCallback + * @param {String|Promise} cancelCallback + * @param {Object} options + * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden) + * @returns {Promise} + */ +export const deleteCancel = async(title, question, deleteLabel, deleteCallback, cancelCallback, { + triggerElement = null, +} = {}) => { + const pendingPromise = new Pending('core/notification:confirm'); + + const [ + ModalFactory, + ModalEvents, + ] = await Promise.all([ + import('core/modal_factory'), + import('core/modal_events'), + ]); + + return ModalFactory.create({ + type: ModalFactory.types.DELETE_CANCEL, + title: title, + body: question, + buttons: { + 'delete': deleteLabel + }, + removeOnClose: true, + }) + .then(function(modal) { + modal.show(); + + modal.getRoot().on(ModalEvents.delete, deleteCallback); + modal.getRoot().on(ModalEvents.cancel, cancelCallback); + modal.getRoot().on(ModalEvents.hidden, () => triggerElement?.focus()); + pendingPromise.resolve(); + + return modal; + }); +}; + + /** * Add all of the supplied notifications. * @@ -277,6 +325,22 @@ export const saveCancelPromise = (title, question, saveLabel, { saveCancel(title, question, saveLabel, resolve, reject, {triggerElement}); }); +/** + * Add all of the supplied notifications. + * + * @param {Promise|String} title The header of the modal + * @param {Promise|String} question What do we want the user to confirm + * @param {Promise|String} deleteLabel The modal action link text + * @param {Object} options + * @param {HTMLElement} [options.triggerElement=null] The element that triggered the modal (will receive the focus after hidden) + * @return {Promise} + */ +export const deleteCancelPromise = (title, question, deleteLabel, { + triggerElement = null, +} = {}) => new Promise((resolve, reject) => { + deleteCancel(title, question, deleteLabel, resolve, reject, {triggerElement}); +}); + /** * Wrap M.core.exception. * @@ -338,7 +402,7 @@ export const exception = async ex => { export const init = (contextId, notificationList) => { currentContextId = contextId; - // Setup the message target region if it isn't setup already + // Setup the message target region if it isn't setup already. setupTargetRegion(); // Add provided notifications. @@ -354,5 +418,6 @@ export default { confirm, saveCancel, saveCancelPromise, + deleteCancelPromise, exception, }; diff --git a/lib/amd/src/utility.js b/lib/amd/src/utility.js index 66027496b44..1cfa1a2ca4f 100644 --- a/lib/amd/src/utility.js +++ b/lib/amd/src/utility.js @@ -48,7 +48,7 @@ import * as Str from 'core/str'; import Pending from 'core/pending'; import {add as addToast} from 'core/toast'; -import {saveCancelPromise, exception} from 'core/notification'; +import {saveCancelPromise, deleteCancelPromise, exception} from 'core/notification'; // We want to ensure that we only initialize the listeners only once. let registered = false; @@ -80,12 +80,21 @@ const getModalString = (dataset, type, field) => { * @returns {Promise} */ const displayConfirmation = (source, type) => { - return saveCancelPromise( - getModalString(source.dataset, type, 'Title'), - getModalString(source.dataset, type, 'Content'), - getModalString(source.dataset, type, 'YesButton'), - ) - .then(() => { + let confirmationPromise = null; + if (`${type}Type` in source.dataset && source.dataset[`${type}Type`] === 'delete') { + confirmationPromise = deleteCancelPromise( + getModalString(source.dataset, type, 'Title'), + getModalString(source.dataset, type, 'Content'), + getModalString(source.dataset, type, 'YesButton'), + ); + } else { + confirmationPromise = saveCancelPromise( + getModalString(source.dataset, type, 'Title'), + getModalString(source.dataset, type, 'Content'), + getModalString(source.dataset, type, 'YesButton'), + ); + } + return confirmationPromise.then(() => { if (source.dataset[`${type}Toast`] === 'true') { const stringForToast = getModalString(source.dataset, type, 'ToastConfirmation'); if (typeof stringForToast === "string") { diff --git a/lib/outputcomponents.php b/lib/outputcomponents.php index ecc89afcacf..13b04ed15ae 100644 --- a/lib/outputcomponents.php +++ b/lib/outputcomponents.php @@ -223,14 +223,14 @@ class user_picture implements renderable { if (!property_exists($user, $field)) { $needrec = true; debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. ' - .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER); + .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER); break; } } if ($needrec) { $this->user = $DB->get_record('user', array('id' => $user->id), - implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST); + implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST); } else { $this->user = clone($user); } @@ -387,7 +387,7 @@ class user_picture implements renderable { } // Set the image URL to the URL for the uploaded file and return. $url = moodle_url::make_pluginfile_url( - $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken); + $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken); $url->param('rev', $this->user->picture); return $url; } @@ -789,6 +789,43 @@ class pix_emoticon extends pix_icon implements renderable { */ class single_button implements renderable { + /** + * Possible button types. From boostrap. + */ + const BUTTON_TYPES = [ + self::BUTTON_PRIMARY, + self::BUTTON_SECONDARY, + self::BUTTON_SUCCESS, + self::BUTTON_DANGER, + self::BUTTON_WARNING, + self::BUTTON_INFO + ]; + + /** + * Possible button types - Primary. + */ + const BUTTON_PRIMARY = 'primary'; + /** + * Possible button types - Secondary. + */ + const BUTTON_SECONDARY = 'secondary'; + /** + * Possible button types - Danger. + */ + const BUTTON_DANGER = 'danger'; + /** + * Possible button types - Success. + */ + const BUTTON_SUCCESS = 'success'; + /** + * Possible button types - Warning. + */ + const BUTTON_WARNING = 'warning'; + /** + * Possible button types - Info. + */ + const BUTTON_INFO = 'info'; + /** * @var moodle_url Target url */ @@ -810,9 +847,15 @@ class single_button implements renderable { public $class = 'singlebutton'; /** - * @var bool True if button is primary button. Used for styling. + * @var string Type of button (from defined types). Used for styling. */ - public $primary = false; + protected $type; + + /** + * @var bool True if button is primary button. Used for styling. + * @deprecated since Moodle 4.2 + */ + private $primary = false; /** * @var bool True if button disabled, false if normal @@ -851,17 +894,24 @@ class single_button implements renderable { /** * Constructor + * * @param moodle_url $url * @param string $label button text * @param string $method get or post submit method - * @param bool $primary whether this is a primary button, used for styling + * @param string $type whether this is a primary button or another type, used for styling * @param array $attributes Attributes for the HTML button tag */ - public function __construct(moodle_url $url, $label, $method='post', $primary=false, $attributes = []) { - $this->url = clone($url); - $this->label = $label; + public function __construct(moodle_url $url, $label, $method = 'post', $type = self::BUTTON_SECONDARY, + $attributes = []) { + if (is_bool($type)) { + debugging('The boolean $primary is deprecated and replaced by $type, + use single_button::BUTTON_PRIMARY or self::BUTTON_SECONDARY instead'); + $type = $type ? self::BUTTON_PRIMARY : self::BUTTON_SECONDARY; + } + $this->url = clone($url); + $this->label = $label; $this->method = $method; - $this->primary = $primary; + $this->type = $type; $this->attributes = $attributes; } @@ -894,6 +944,49 @@ class single_button implements renderable { $this->attributes[$name] = $value; } + /** + * Magic setter method. + * + * This method manages access to some properties and will display deprecation message when accessing 'primary' property. + * + * @param string $name + * @param mixed $value + */ + public function __set($name, $value) { + switch ($name) { + case 'primary': + debugging('The primary field is deprecated, use the type field instead'); + // Here just in case we modified the primary field from outside {@see \mod_quiz_renderer::summary_page_controls}. + $this->type = $value ? self::BUTTON_PRIMARY : self::BUTTON_SECONDARY; + break; + case 'type': + $this->type = in_array($value, self::BUTTON_TYPES) ? $value : self::BUTTON_SECONDARY; + break; + default: + $this->$name = $value; + } + } + + /** + * Magic method getter. + * + * This method manages access to some properties and will display deprecation message when accessing 'primary' property. + * + * @param string $name + * @return mixed + */ + public function __get($name) { + switch ($name) { + case 'primary': + debugging('The primary field is deprecated, use type field instead'); + return $this->type == self::BUTTON_PRIMARY; + case 'type': + return $this->type; + default: + return $this->$name; + } + } + /** * Export data. * @@ -912,8 +1005,7 @@ class single_button implements renderable { $data->classes = $this->class; $data->disabled = $this->disabled; $data->tooltip = $this->tooltip; - $data->primary = $this->primary; - + $data->type = $this->type; $data->attributes = []; foreach ($this->attributes as $key => $value) { $data->attributes[] = ['name' => $key, 'value' => $value]; @@ -1401,8 +1493,8 @@ class url_select implements renderable, templatable { $value = key($nothing); $name = reset($nothing); $flattened = [ - $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value] - ] + $flattened; + $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value] + ] + $flattened; } // Make non-associative array. @@ -1525,10 +1617,10 @@ class action_link implements renderable { * @param pix_icon $icon optional pix_icon to render with the link text */ public function __construct(moodle_url $url, - $text, - component_action $action=null, - array $attributes=null, - pix_icon $icon=null) { + $text, + component_action $action=null, + array $attributes=null, + pix_icon $icon=null) { $this->url = clone($url); $this->text = $text; if (empty($attributes['id'])) { @@ -1790,7 +1882,7 @@ class html_writer { * @return string html fragment */ public static function checkbox($name, $value, $checked = true, $label = '', - array $attributes = null, array $labelattributes = null) { + array $attributes = null, array $labelattributes = null) { $attributes = (array) $attributes; $output = ''; @@ -2143,12 +2235,12 @@ class html_writer { // explicitly assigned properties override those defined via $table->attributes $table->attributes['class'] = trim($table->attributes['class']); $attributes = array_merge($table->attributes, array( - 'id' => $table->id, - 'width' => $table->width, - 'summary' => $table->summary, - 'cellpadding' => $table->cellpadding, - 'cellspacing' => $table->cellspacing, - )); + 'id' => $table->id, + 'width' => $table->width, + 'summary' => $table->summary, + 'cellpadding' => $table->cellpadding, + 'cellspacing' => $table->cellspacing, + )); $output = html_writer::start_tag('table', $attributes) . "\n"; $countcols = 0; @@ -2261,9 +2353,9 @@ class html_writer { // Explicitly assigned properties should override those defined in the attributes. $row->attributes['class'] = trim($row->attributes['class']); $trattributes = array_merge($row->attributes, array( - 'id' => $row->id, - 'style' => $row->style, - )); + 'id' => $row->id, + 'style' => $row->style, + )); $output .= html_writer::start_tag('tr', $trattributes) . "\n"; $keys2 = array_keys($row->cells); $lastkey = end($keys2); @@ -2300,13 +2392,13 @@ class html_writer { $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : ''; $cell->attributes['class'] = trim($cell->attributes['class']); $tdattributes = array_merge($cell->attributes, array( - 'style' => $tdstyle . $cell->style, - 'colspan' => $cell->colspan, - 'rowspan' => $cell->rowspan, - 'id' => $cell->id, - 'abbr' => $cell->abbr, - 'scope' => $cell->scope, - )); + 'style' => $tdstyle . $cell->style, + 'colspan' => $cell->colspan, + 'rowspan' => $cell->rowspan, + 'id' => $cell->id, + 'abbr' => $cell->abbr, + 'scope' => $cell->scope, + )); $tagtype = 'td'; if ($cell->header === true) { $tagtype = 'th'; @@ -3516,7 +3608,7 @@ class custom_menu_item implements renderable, templatable { * @param array $attributes Array of other HTML attributes for the custom menu item. */ public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null, - array $attributes = []) { + array $attributes = []) { $this->text = $text; $this->url = $url; $this->title = $title; @@ -4069,7 +4161,7 @@ class context_header implements renderable { } // Add the bootstrap 'btn' class for formatting. $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'], - array('class' => $class)); + array('class' => $class)); } } } @@ -5042,7 +5134,7 @@ class progress_bar implements renderable, templatable { if (empty($this->time_start)) { throw new coding_exception('You must call create() (or use the $autostart ' . - 'argument to the constructor) before you try updating the progress bar.'); + 'argument to the constructor) before you try updating the progress bar.'); } $estimate = $this->estimate($percent); diff --git a/lib/templates/modal_delete_cancel.mustache b/lib/templates/modal_delete_cancel.mustache new file mode 100644 index 00000000000..5814534403d --- /dev/null +++ b/lib/templates/modal_delete_cancel.mustache @@ -0,0 +1,46 @@ +{{! + 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 . +}} +{{! + @template core/modal_delete_cancel + + Moodle modal template with delete and cancel buttons. + + The purpose of this template is to render a modal. + + Classes required for JS: + * none + + Data attributes required for JS: + * none + + Context variables required for this template: + * title A cleaned string (use clean_text()) to display. + * body HTML content for the boday + + Example context (json): + { + "title": "Example delete cancel modal", + "body": "Some example content for the body" + } +}} + +{{< core/modal }} + {{$footer}} + + + {{/footer}} +{{/ core/modal }} diff --git a/lib/templates/single_button.mustache b/lib/templates/single_button.mustache index 7937a7007e6..feb068d93f5 100644 --- a/lib/templates/single_button.mustache +++ b/lib/templates/single_button.mustache @@ -31,16 +31,18 @@ * url - the action url to submit to * formid - optional id value for the form * params - array of params with name and value attributes - * primary - true if this is a primary action button * id - id for the element + * type - type for the element * tooltip - tooltip text for the button * disabled - true if this element is disabled * label - text to show on the button Example context (json): - { "method" : "get", + { + "method" : "get", + "id": "buttonid-123", + "type": "primary", "url" : "#", - "primary" : true, "tooltip" : "This is a tooltip", "label" : "This is a the button text", "attributes": [ @@ -56,7 +58,7 @@ {{#params}} {{/params}} -