// JS module 'local_performance_review/index' cannot be loaded, or does not contain a javascript module in AMD format. "define()" not found. // JS module 'local_pre_registration/checkout_form_validation' cannot be loaded, or does not contain a javascript module in AMD format. "define()" not found. /** * Expose the M.cfg global variable. * * @module core/config * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/config",(function(){return M.cfg})); define("core/local/repository/dynamic_tabs",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle dynamic tabs AJAX requests * * @module core/local/repository/dynamic_tabs * @copyright 2021 David Matamoros * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getContent=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.getContent=(tab,jsondata)=>{const request={methodname:"core_dynamic_tabs_get_content",args:{tab:tab,jsondata:jsondata}};return _ajax.default.call([request])[0]}})); define("core/local/modal/alert",["exports","core/modal"],(function(_exports,_modal){var obj; /** * Alert modal. * * @module core/modal_alert * @copyright 2020 Andrew Nicols * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=(obj=_modal)&&obj.__esModule?obj:{default:obj};class _default extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnCancel()}}return _exports.default=_default,_exports.default})); define("core/local/reactive/debug",["exports","core/local/reactive/reactive","core/log"],(function(_exports,_reactive,_log){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Reactive module debug tools. * * @module core/reactive/local/reactive/debug * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initDebug=void 0,_reactive=_interopRequireDefault(_reactive),_log=_interopRequireDefault(_log);const reactiveInstances={},reactiveDebuggers={}; /** * Reactive module debug tools. * * If debug is enabled, this reactive module will spy all the reactive instances and keep a record * of the changes and components they have. * * It is important to note that the Debug class is also a Reactive module. The debug instance keeps * the reactive instances data as its own state. This way it is possible to implement development tools * that whatches this data. * * @class core/reactive/local/reactive/debug/Debug * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class Debug extends _reactive.default{setInitialState(stateData){super.setInitialState(stateData),_log.default.debug('Debug module "M.reactive" loaded.')}get list(){return JSON.parse(JSON.stringify(this.state.reactives))}registerNewInstance(instance){var _instance$name;let name=null!==(_instance$name=instance.name)&&void 0!==_instance$name?_instance$name:"instance".concat(this.state.reactives.length);name=name.replace(/\W/g,""),_log.default.debug('Registering new reactive instance "M.reactive.'.concat(name,'"')),reactiveInstances[name]=instance,reactiveDebuggers[name]=new DebugInstance(reactiveInstances[name]),this.dispatch("putInstance",name,instance);const refreshMethod=()=>{this.dispatch("putInstance",name,instance)};instance.target.addEventListener("readmode:on",refreshMethod),instance.target.addEventListener("readmode:off",refreshMethod),instance.target.addEventListener("registerComponent:success",refreshMethod),instance.target.addEventListener("transaction:end",refreshMethod);instance.target.addEventListener("transaction:start",(_ref=>{let{detail:detail}=_ref;const changes=null==detail?void 0:detail.changes;this.dispatch("lastTransaction",name,changes)}))}debug(name){return reactiveDebuggers[name]}}class Mutations{putInstance(stateManager,name,instance){const state=stateManager.state;stateManager.setReadOnly(!1),state.reactives.has(name)?(state.reactives.get(name).countcomponents=instance.components.length,state.reactives.get(name).readOnly=instance.stateManager.readonly,state.reactives.get(name).modified=(new Date).getTime()):state.reactives.add({id:name,countcomponents:instance.components.length,readOnly:instance.stateManager.readonly,lastChanges:[],modified:(new Date).getTime()}),stateManager.setReadOnly(!0)}lastTransaction(stateManager,name,changes){if(!changes||0===changes.length)return;const state=stateManager.state,lastChanges=["transaction:start"];changes.forEach((change=>{lastChanges.push(change.eventName)})),lastChanges.push("transaction:end"),stateManager.setReadOnly(!1),state.reactives.get(name).lastChanges=lastChanges,stateManager.setReadOnly(!0)}} /** * Class used to debug a specific instance and manipulate the state from the JS console. * * @class core/reactive/local/reactive/debug/DebugInstance * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */class DebugInstance{constructor(instance){this.instance=instance,void 0===instance._reactiveDebugData&&(instance._reactiveDebugData={highlighted:!1})}set readOnly(value){this.instance.stateManager.setReadOnly(value)}get readOnly(){return this.instance.stateManager.readonly}get state(){return this.instance.state}set highlight(value){this.instance._reactiveDebugData.highlighted=value,this.instance.components.forEach((_ref2=>{let{element:element}=_ref2;const border=value?"thick solid #0000FF":"";element.style.border=border}))}get highlight(){return this.instance._reactiveDebugData.highlighted}get components(){return[...this.instance.components]}get changes(){const result=[];return this.instance.stateManager.eventsToPublish.forEach((element=>{result.push(element.eventName)})),result}async dispatch(){this.instance.dispatch(...arguments)}get elements(){const result=[];return this.instance.components.forEach((_ref3=>{let{element:element}=_ref3;result.push(element)})),result}get stateData(){return JSON.parse(JSON.stringify(this.state))}processUpdates(updates){this.instance.stateManager.processUpdates(updates)}}function dispatchStateChangedEvent(detail,target){void 0===target&&(target=document),target.dispatchEvent(new CustomEvent("core_reactive_debug:stateChanged",{bubbles:!0,detail:detail}))}_exports.initDebug=()=>{const debug=new Debug({name:"CoreReactiveDebug",eventName:"core_reactive_debug:stateChanged",eventDispatch:dispatchStateChangedEvent,mutations:new Mutations,state:{reactives:[]}});return reactiveDebuggers.registerNewInstance=debug.registerNewInstance.bind(debug),{debug:debug,debuggers:reactiveDebuggers}}})); define("core/local/reactive/basecomponent",["exports","core/templates"],(function(_exports,_templates){var obj; /** * Reactive UI component base class. * * Each UI reactive component should extend this class to interact with a reactive state. * * @module core/local/reactive/basecomponent * @class core/local/reactive/basecomponent * @copyright 2020 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=(obj=_templates)&&obj.__esModule?obj:{default:obj};return _exports.default=class{constructor(descriptor){if(void 0===descriptor.element||!(descriptor.element instanceof HTMLElement))throw Error("Reactive components needs a main DOM element to dispatch events");this.element=descriptor.element,this.eventHandlers=new Map([]),this.eventListeners=[],this.selectors={},this.events=this.constructor.getEvents(),this.create(descriptor),void 0!==descriptor.selectors&&this.addSelectors(descriptor.selectors),void 0===descriptor.reactive?this.element.dispatchEvent(new CustomEvent("core/reactive:requestRegistration",{bubbles:!0,detail:{component:this}})):(this.reactive=descriptor.reactive,this.reactive.registerComponent(this),this.addEventListener(this.element,"core/reactive:requestRegistration",(event=>{var _event$detail;null!=event&&null!==(_event$detail=event.detail)&&void 0!==_event$detail&&_event$detail.component&&(event.stopPropagation(),this.registerChildComponent(event.detail.component))})))}static getEvents(){return{}}create(descriptor){}destroy(){}getWatchers(){return[]}stateReady(){}getElement(query,dataId){if(void 0===query&&void 0===dataId)return this.element;const dataSelector=dataId?"[data-id='".concat(dataId,"']"):"",selector="".concat(null!=query?query:"").concat(dataSelector);return this.element.querySelector(selector)}getElements(query,dataId){const dataSelector=dataId?"[data-id='".concat(dataId,"']"):"",selector="".concat(null!=query?query:"").concat(dataSelector);return this.element.querySelectorAll(selector)}addSelectors(newSelectors){for(const[selectorName,selector]of Object.entries(newSelectors))this.selectors[selectorName]=selector}getSelector(selectorName){return this.selectors[selectorName]}dispatchEvent(eventName,detail){this.element.dispatchEvent(new CustomEvent(eventName,{bubbles:!0,detail:detail}))}renderComponent(target,file,data){return new Promise(((resolve,reject)=>{target.addEventListener("ComponentRegistration:Success",(_ref=>{let{detail:detail}=_ref;resolve(detail.component)})),target.addEventListener("ComponentRegistration:Fail",(()=>{reject("Registration of ".concat(file," fails."))})),_templates.default.renderForPromise(file,data).then((_ref2=>{let{html:html,js:js}=_ref2;return _templates.default.replaceNodeContents(target,html,js),!0})).catch((error=>{throw reject("Rendering of ".concat(file," throws an error.")),error}))}))}addEventListener(target,type,listener){let bindListener=this.eventHandlers.get(listener);void 0===bindListener&&(bindListener=listener.bind(this),this.eventHandlers.set(listener,bindListener)),target.addEventListener(type,bindListener),this.eventListeners.push({target:target,type:type,bindListener:bindListener})}removeEventListener(target,type,listener){let bindListener=this.eventHandlers.get(listener);void 0!==bindListener&&target.removeEventListener(type,bindListener)}removeAllEventListeners(){this.eventListeners.forEach((_ref3=>{let{target:target,type:type,bindListener:bindListener}=_ref3;target.removeEventListener(type,bindListener)})),this.eventListeners=[]}remove(){this.unregister(),this.element.remove()}unregister(){this.reactive.unregisterComponent(this),this.removeAllEventListeners(),this.destroy()}dispatchRegistrationSuccess(){void 0!==this.element.parentNode&&this.element.parentNode.dispatchEvent(new CustomEvent("ComponentRegistration:Success",{bubbles:!1,detail:{component:this}}))}dispatchRegistrationFail(){void 0!==this.element.parentNode&&this.element.parentNode.dispatchEvent(new CustomEvent("ComponentRegistration:Fail",{bubbles:!1,detail:{component:this}}))}registerChildComponent(component){component.reactive=this.reactive,this.reactive.registerComponent(component)}set locked(locked){this.setElementLocked(this.element,locked)}get locked(){return this.getElementLocked(this.element)}setElementLocked(target,locked){target.dataset.locked=null!=locked&&locked,locked?(target.style.pointerEvents="none",target.style.userSelect="none",target.hasAttribute("draggable")&&target.setAttribute("draggable",!1),target.setAttribute("aria-busy",!0)):(target.style.pointerEvents=null,target.style.userSelect=null,target.hasAttribute("draggable")&&target.setAttribute("draggable",!0),target.setAttribute("aria-busy",!1))}getElementLocked(target){var _target$dataset$locke;return null!==(_target$dataset$locke=target.dataset.locked)&&void 0!==_target$dataset$locke&&_target$dataset$locke}},_exports.default})); define("core/local/reactive/reactive",["exports","core/log","core/local/reactive/statemanager","core/pending"],(function(_exports,_log,_statemanager,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A generic single state reactive module. * * @module core/reactive/local/reactive/reactive * @class core/reactive/local/reactive/reactive * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_log=_interopRequireDefault(_log),_statemanager=_interopRequireDefault(_statemanager),_pending=_interopRequireDefault(_pending);let pendingCount=0;return _exports.default=class{constructor(description){var _description$target,_description$mutation;if(void 0===description.eventName||void 0===description.eventDispatch)throw new Error("Reactivity event required");void 0!==description.name&&(this.name=description.name),this.target=null!==(_description$target=description.target)&&void 0!==_description$target?_description$target:document.createTextNode(null),this.eventName=description.eventName,this.eventDispatch=description.eventDispatch,this.stateManager=new _statemanager.default(this.eventDispatch,this.target),this.watchers=new Map([]),this.components=new Set([]),this.mutations=null!==(_description$mutation=description.mutations)&&void 0!==_description$mutation?_description$mutation:{},this.target.addEventListener(this.eventName,this.callWatchersHandler.bind(this)),this.pendingState=new _pending.default("core/reactive:registerInstance".concat(pendingCount++)),void 0!==description.state&&this.setInitialState(description.state),void 0!==M.reactive&&M.reactive.registerNewInstance(this)}callWatchersHandler(event){this.target.dispatchEvent(new CustomEvent(event.detail.action,{bubbles:!1,detail:event.detail}))}setInitialState(stateData){this.pendingState.resolve(),this.stateManager.setInitialState(stateData)}addMutations(newFunctions){void 0!==newFunctions.init&&newFunctions.init(this.stateManager);for(const[mutation,mutationFunction]of Object.entries(newFunctions))this.mutations[mutation]=mutationFunction.bind(newFunctions)}setMutations(manager){this.mutations=manager,void 0!==manager.init&&manager.init(this.stateManager)}get state(){return this.stateManager.state}get(name,id){return this.stateManager.get(name,id)}getInitialStatePromise(){return this.stateManager.getInitialPromise()}registerComponent(component){var _component$name;const componentName=null!==(_component$name=component.name)&&void 0!==_component$name?_component$name:"Unkown component";let dispatchSuccess=()=>{},dispatchFail=dispatchSuccess;if(void 0!==component.dispatchRegistrationSuccess&&(dispatchSuccess=component.dispatchRegistrationSuccess.bind(component)),void 0!==component.dispatchRegistrationFail&&(dispatchFail=component.dispatchRegistrationFail.bind(component)),this.components.has(component))return dispatchSuccess(),component;const pendingPromise=new _pending.default("core/reactive:registerComponent".concat(pendingCount++));let listeners=[],handlers=[];return void 0!==component.getWatchers&&(handlers=component.getWatchers()),handlers.forEach((_ref=>{let{watch:watch,handler:handler}=_ref;if(void 0===watch)throw dispatchFail(),new Error("Missing watch attribute in ".concat(componentName," watcher"));if(void 0===handler)throw dispatchFail(),new Error("Missing handler for watcher ".concat(watch," in ").concat(componentName));const listener=event=>{const currentFocus=document.activeElement;handler.apply(component,[event.detail]),document.activeElement===document.body&&document.body.contains(currentFocus)&¤tFocus.focus()};listeners.push({target:this.target,watch:watch,listener:listener}),this.target.addEventListener(watch,listener)})),void 0!==component.stateReady&&this.getInitialStatePromise().then((state=>(component.stateReady(state),pendingPromise.resolve(),!0))).catch((reason=>{pendingPromise.resolve(),_log.default.error("Initial state in ".concat(componentName," rejected due to: ").concat(reason)),_log.default.error(reason)})),this.watchers.set(component,listeners),this.components.add(component),this.target.dispatchEvent(new CustomEvent("registerComponent:success",{bubbles:!1,detail:{component:component}})),dispatchSuccess(),component}unregisterComponent(component){if(!this.components.has(component))return component;this.components.delete(component);const listeners=this.watchers.get(component);return void 0===listeners||(listeners.forEach((_ref2=>{let{target:target,watch:watch,listener:listener}=_ref2;target.removeEventListener(watch,listener)})),this.watchers.delete(component)),component}async dispatch(actionName){if("string"!=typeof actionName)throw new Error("Dispatch action name must be a string");if("_"===actionName.charAt(0))throw new Error("Illegal Private ".concat(actionName," mutation method dispatch"));if(void 0===this.mutations[actionName])throw new Error("Unkown ".concat(actionName," mutation"));const pendingPromise=new _pending.default("core/reactive:".concat(actionName).concat(pendingCount++)),mutationFunction=this.mutations[actionName];try{for(var _len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)params[_key-1]=arguments[_key];await mutationFunction.apply(this.mutations,[this.stateManager,...params]),pendingPromise.resolve()}catch(error){throw this.stateManager.setReadOnly(!0),pendingPromise.resolve(),error}}},_exports.default})); define("core/local/reactive/logger",["exports","core/toast"],(function(_exports,_toast){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default= /** * Default reactive mutations logger class. * * This logger is used by default by the StateManager to log mutation feedbacks * and actions. By default, feedbacks will be displayed as a toast. However, the * reactive instance can provide alternative loggers to provide advanced logging * capabilities. * * @module core/local/reactive/logger * @class Logger * @copyright 2023 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class{constructor(){this._debug=!1}add(entry){entry.feedbackMessage&&(0,_toast.add)(entry.feedbackMessage)}},_exports.default})); define("core/local/reactive/statemanager",["exports","core/local/reactive/logger"],(function(_exports,_logger){var obj; /** * Reactive simple state manager. * * The state manager contains the state data, trigger update events and * can lock and unlock the state data. * * This file contains the three main elements of the state manager: * - State manager: the public class to alter the state, dispatch events and process update messages. * - Proxy handler: a private class to keep track of the state object changes. * - StateMap class: a private class extending Map class that triggers event when a state list is modifed. * * @module core/local/reactive/stateManager * @class core/local/reactive/stateManager * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_logger=(obj=_logger)&&obj.__esModule?obj:{default:obj};_exports.default=class{constructor(dispatchEvent,target){this.dispatchEvent=dispatchEvent,this.target=null!=target?target:document,this.readonly=!1,this.eventsToPublish=[],this.updateTypes={create:this.defaultCreate.bind(this),update:this.defaultUpdate.bind(this),delete:this.defaultDelete.bind(this),put:this.defaultPut.bind(this),override:this.defaultOverride.bind(this),remove:this.defaultRemove.bind(this),prepareFields:this.defaultPrepareFields.bind(this)},this.initialPromise=new Promise((resolve=>{this.target.addEventListener("state:loaded",(event=>{resolve(event.detail.state)}))})),this.logger=new _logger.default}setInitialState(initialState){if(void 0!==this.state)throw Error("Initial state can only be initialized ones");const state=new Proxy({},new Handler("state",this,!0));for(const[prop,propValue]of Object.entries(initialState))state[prop]=propValue;this.state=state,this.readonly=!0,this.dispatchEvent({action:"state:loaded",state:this.state},this.target)}getInitialPromise(){return this.initialPromise}setReadOnly(readonly){this.readonly=readonly;let mode="off";this.readonly&&(mode="on",this._publishEvents()),this.dispatchEvent({action:"readmode:".concat(mode),state:this.state,element:null},this.target)}addUpdateTypes(newFunctions){for(const[updateType,updateFunction]of Object.entries(newFunctions))"function"==typeof updateFunction&&(this.updateTypes[updateType]=updateFunction.bind(newFunctions))}processUpdates(updates,updateTypes){if(!Array.isArray(updates))throw Error("State updates must be an array");this.setReadOnly(!1),updates.forEach((update=>{if(void 0===update.name)throw Error("Missing state update name");this.processUpdate(update.name,update.action,update.fields,updateTypes)})),this.setReadOnly(!0)}processUpdate(updateName,action,fields,updateTypes){var _action,_updateTypes$action,_updateTypes$prepareF;if(!fields)throw Error("Missing state update fields");void 0===updateTypes&&(updateTypes={});const method=null!==(_updateTypes$action=updateTypes[action=null!==(_action=action)&&void 0!==_action?_action:"update"])&&void 0!==_updateTypes$action?_updateTypes$action:this.updateTypes[action];if(void 0===method)throw Error("Unkown update action ".concat(action));method(this,updateName,(null!==(_updateTypes$prepareF=updateTypes.prepareFields)&&void 0!==_updateTypes$prepareF?_updateTypes$prepareF:this.updateTypes.prepareFields)(this,updateName,fields))}defaultPrepareFields(stateManager,updateName,fields){return fields}defaultCreate(stateManager,updateName,fields){let state=stateManager.state;state[updateName]instanceof StateMap?state[updateName].add(fields):state[updateName]=fields}defaultDelete(stateManager,updateName,fields){if(!stateManager.get(updateName,fields.id))throw Error("Inexistent ".concat(updateName," ").concat(fields.id));let state=stateManager.state;state[updateName]instanceof StateMap?state[updateName].delete(fields.id):delete state[updateName]}defaultRemove(stateManager,updateName,fields){if(!stateManager.get(updateName,fields.id))return;let state=stateManager.state;state[updateName]instanceof StateMap?state[updateName].delete(fields.id):delete state[updateName]}defaultUpdate(stateManager,updateName,fields){let current=stateManager.get(updateName,fields.id);if(!current)throw Error("Inexistent ".concat(updateName," ").concat(fields.id));for(const[fieldName,fieldValue]of Object.entries(fields))current[fieldName]=fieldValue}defaultPut(stateManager,updateName,fields){let current=stateManager.get(updateName,fields.id);if(current)for(const[fieldName,fieldValue]of Object.entries(fields))current[fieldName]=fieldValue;else{let state=stateManager.state;if(state[updateName]instanceof StateMap)return void state[updateName].add(fields);state[updateName]=fields}}defaultOverride(stateManager,updateName,fields){let current=stateManager.get(updateName,fields.id);if(current){for(const[fieldName]of Object.entries(current))void 0===fields[fieldName]&&delete current[fieldName];for(const[fieldName,fieldValue]of Object.entries(fields))current[fieldName]=fieldValue}else{let state=stateManager.state;if(state[updateName]instanceof StateMap)return void state[updateName].add(fields);state[updateName]=fields}}setLogger(logger){this.logger=logger}addLoggerEntry(entry){this.logger.add(entry)}get(name,id){const state=this.state;let current=state[name];if(current instanceof StateMap){if(void 0===id)throw Error("Missing id for ".concat(name," state update"));current=state[name].get(id)}return current}registerStateAction(field,prop,action,data){let parentAction="updated";null!==prop?this.eventsToPublish.push({eventName:"".concat(field,".").concat(prop,":").concat(action),eventData:data,action:action}):parentAction=action,void 0!==data.id&&(null!==prop&&this.eventsToPublish.push({eventName:"".concat(field,"[").concat(data.id,"].").concat(prop,":").concat(action),eventData:data,action:action}),this.eventsToPublish.push({eventName:"".concat(field,"[").concat(data.id,"]:").concat(parentAction),eventData:data,action:parentAction})),this.eventsToPublish.push({eventName:"".concat(field,":").concat(parentAction),eventData:data,action:parentAction}),this.eventsToPublish.push({eventName:"state:updated",eventData:data,action:"updated"})}_publishEvents(){const fieldChanges=this.eventsToPublish;this.eventsToPublish=[],this.dispatchEvent({action:"transaction:start",state:this.state,element:null,changes:fieldChanges},this.target),fieldChanges.sort(((a,b)=>{var _weights$a$action,_weights$b$action;const weights={created:0,updated:1,deleted:2},aweight=null!==(_weights$a$action=weights[a.action])&&void 0!==_weights$a$action?_weights$a$action:0,bweight=null!==(_weights$b$action=weights[b.action])&&void 0!==_weights$b$action?_weights$b$action:0;return aweight===bweight?a.eventName.length-b.eventName.length:aweight-bweight}));let publishedEvents=new Set;fieldChanges.forEach((event=>{var _event$eventData$id;const eventkey="".concat(event.eventName,".").concat(null!==(_event$eventData$id=event.eventData.id)&&void 0!==_event$eventData$id?_event$eventData$id:0);publishedEvents.has(eventkey)||(this.dispatchEvent({action:event.eventName,state:this.state,element:event.eventData},this.target),publishedEvents.add(eventkey))})),this.dispatchEvent({action:"transaction:end",state:this.state,element:null},this.target)}};class Handler{constructor(name,stateManager,proxyValues){this.name=name,this.stateManager=stateManager,this.proxyValues=null!=proxyValues&&proxyValues}set(obj,prop,value,receiver){if(this.stateManager.readonly)throw new Error("State locked. Use mutations to change ".concat(prop," value in ").concat(this.name,"."));if(JSON.stringify(obj[prop])===JSON.stringify(value))return!0;const action=void 0!==obj[prop]?"updated":"created";return this.proxyValues?Array.isArray(value)?obj[prop]=new StateMap(prop,this.stateManager).loadValues(value):obj[prop]=new Proxy(value,new Handler(prop,this.stateManager)):obj[prop]=value,void 0===this.stateManager.state||this.stateManager.registerStateAction(this.name,prop,action,receiver),!0}deleteProperty(obj,prop){if(this.stateManager.readonly)throw new Error("State locked. Use mutations to delete ".concat(prop," in ").concat(this.name,"."));return prop in obj&&(delete obj[prop],this.stateManager.registerStateAction(this.name,prop,"deleted",obj)),!0}}class StateMap extends Map{constructor(name,stateManager,iterable){super(iterable),this.name=name,this.stateManager=stateManager}set(key,value){if(this.stateManager.readonly)throw new Error("State locked. Use mutations to change ".concat(key," value in ").concat(this.name,"."));if(key=this.normalizeKey(key),this.checkValue(value),null==key)throw Error("State lists keys cannot be null or undefined");if(this.normalizeKey(value.id)!==key)throw new Error("State error: ".concat(this.name," list element ID (").concat(value.id,") and key (").concat(key,") mismatch"));const action=super.has(key)?"updated":"created",result=super.set(key,new Proxy(value,new Handler(this.name,this.stateManager)));return void 0===this.stateManager.state||this.stateManager.registerStateAction(this.name,null,action,super.get(key)),result}checkValue(value){if(void 0===value.id)throw Error("State lists elements must contain at least an id attribute")}normalizeKey(key){return String(key).valueOf()}add(value){return this.checkValue(value),this.set(value.id,value)}get(key){return super.get(this.normalizeKey(key))}has(key){return super.has(this.normalizeKey(key))}delete(key){if(key=this.normalizeKey(key),this.stateManager.readonly)throw new Error("State locked. Use mutations to change ".concat(key," value in ").concat(this.name,"."));const previous=super.get(key),result=super.delete(key);return result?(this.stateManager.registerStateAction(this.name,null,"deleted",previous),result):result}toJSON(){let result=[];return this.forEach((value=>{result.push(value)})),result}loadValues(values){return values.forEach((data=>{this.checkValue(data);let key=data.id,newvalue=new Proxy(data,new Handler(this.name,this.stateManager));this.set(key,newvalue)})),this}}return _exports.default})); define("core/local/reactive/debugpanel",["exports","core/reactive","core/log","core/utils"],(function(_exports,_reactive,_log,_utils){var obj; /** * Reactive module debug panel. * * This module contains all the UI components for the reactive debug tools. * Those tools are only available if the debug is enables and could be used * from the footer. * * @module core/local/reactive/debugpanel * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initsubpanel=_exports.init=void 0,_log=(obj=_log)&&obj.__esModule?obj:{default:obj};_exports.init=(target,selectors)=>{const element=document.getElementById(target);void 0!==_reactive.debug?new GlobalDebugPanel({element:element,reactive:_reactive.debug,selectors:selectors}):element.remove()};_exports.initsubpanel=(target,selectors)=>{const element=document.getElementById(target);void 0!==_reactive.debug?new DebugInstanceSubpanel({element:element,reactive:_reactive.debug,selectors:selectors}):element.remove()};class GlobalDebugPanel extends _reactive.BaseComponent{create(){this.name="GlobalDebugPanel",this.selectors={LOADERS:"[data-for='loaders']",SUBPANEL:"[data-for='subpanel']",NOINSTANCES:"[data-for='noinstances']",LOG:"[data-for='log']"},this.classes={HIDE:"d-none"},this.subPanels=new Set}stateReady(state){this._updateReactivesPanels({state:state}),this.getElement(this.selectors.SUBPANEL).innerHTML=""}getWatchers(){return[{watch:"reactives:created",handler:this._updateReactivesPanels}]}_updateReactivesPanels(_ref){var _this$getElement,_this$getElement$clas;let{state:state}=_ref;null===(_this$getElement=this.getElement(this.selectors.NOINSTANCES))||void 0===_this$getElement||null===(_this$getElement$clas=_this$getElement.classList)||void 0===_this$getElement$clas||_this$getElement$clas.toggle(this.classes.HIDE,state.reactives.size>0),state.reactives.forEach((instance=>{this._createLoader(instance)}))}_createLoader(instance){if(this.subPanels.has(instance.id))return;this.subPanels.add(instance.id);const loaders=this.getElement(this.selectors.LOADERS),btn=document.createElement("button");btn.innerHTML=instance.id,btn.dataset.id=instance.id,loaders.appendChild(btn),this.addEventListener(btn,"click",(()=>this._openPanel(btn,instance)))}async _openPanel(btn,instance){try{const target=this.getElement(this.selectors.SUBPANEL),data={...instance};await this.renderComponent(target,"core/local/reactive/debuginstancepanel",data)}catch(error){throw _log.default.error("Cannot load reactive debug subpanel"),error}}}class DebugInstanceSubpanel extends _reactive.BaseComponent{create(){this.name="DebugInstanceSubpanel",this.selectors={NAME:"[data-for='name']",CLOSE:"[data-for='close']",READMODE:"[data-for='readmode']",HIGHLIGHT:"[data-for='highlight']",LOG:"[data-for='log']",STATE:"[data-for='state']",CLEAN:"[data-for='clean']",PIN:"[data-for='pin']",SAVE:"[data-for='save']",INVALID:"[data-for='invalid']"},this.id=this.element.dataset.id,this.controller=M.reactive[this.id],this.draggable=!1,this.relativeDrag=!0,this.strings={savewarning:""}}stateReady(){var _this$getElement$inne,_this$getElement2;this.dragdrop=new _reactive.DragDrop(this),this.addEventListener(this.getElement(this.selectors.CLOSE),"click",this.remove),this.controller.highlight&&this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT)),this.addEventListener(this.getElement(this.selectors.HIGHLIGHT),"click",(()=>{this.controller.highlight=!this.controller.highlight,this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT))})),this.addEventListener(this.getElement(this.selectors.READMODE),"click",this._toggleEditMode),this.addEventListener(this.getElement(this.selectors.CLEAN),"click",this._cleanAreas),this.addEventListener(this.getElement(this.selectors.PIN),"click",this._togglePin),this.getElement(this.selectors.SAVE).disabled=!0,this.addEventListener(this.getElement(this.selectors.STATE),"keyup",(0,_utils.debounce)(this._checkJSON,500)),this.addEventListener(this.getElement(this.selectors.SAVE),"click",this._saveState),this.strings.savewarning=null!==(_this$getElement$inne=null===(_this$getElement2=this.getElement(this.selectors.INVALID))||void 0===_this$getElement2?void 0:_this$getElement2.innerHTML)&&void 0!==_this$getElement$inne?_this$getElement$inne:"",this._refreshState()}destroy(){void 0!==this.dragdrop&&this.dragdrop.unregister()}getWatchers(){return[{watch:"reactives[".concat(this.id,"].lastChanges:updated"),handler:this._refreshLog},{watch:"reactives[".concat(this.id,"].modified:updated"),handler:this._refreshState},{watch:"reactives[".concat(this.id,"].readOnly:updated"),handler:this._refreshReadOnly}]}_refreshLog(_ref2){var _element$lastChanges;let{element:element}=_ref2;const logContent=(null!==(_element$lastChanges=null==element?void 0:element.lastChanges)&&void 0!==_element$lastChanges?_element$lastChanges:[]).join("\n"),target=this.getElement(this.selectors.LOG);target.value+="\n\n= Transaction =\n ".concat(logContent),target.scrollTop=target.scrollHeight}_cleanAreas(){this.getElement(this.selectors.LOG).value="",this._refreshState()}_refreshState(){this.getElement(this.selectors.STATE).value=JSON.stringify(this.controller.state,null,4)}_refreshReadOnly(){const target=this.getElement(this.selectors.READMODE);void 0===target.dataset.readonly&&(target.dataset.readonly=target.innerHTML),this.controller.readOnly?target.innerHTML=target.dataset.readonly:target.innerHTML=target.dataset.alt}_toggleEditMode(){this.controller.readOnly=!this.controller.readOnly}_checkJSON(){const invalid=this.getElement(this.selectors.INVALID),save=this.getElement(this.selectors.SAVE),edited=this.getElement(this.selectors.STATE).value,currentStateData=this.controller.stateData;if(edited==JSON.stringify(this.controller.state,null,4))return invalid.style.color="",invalid.innerHTML="",void(save.disabled=!0);try{const newState=JSON.parse(edited),result=this._generateStateUpdates(currentStateData,newState);return invalid.style.color="",invalid.innerHTML=this.strings.savewarning,save.disabled=!1,result}catch(error){var _error$message;return invalid.style.color="red",invalid.innerHTML=null!==(_error$message=error.message)&&void 0!==_error$message?_error$message:"Invalid JSON sctructure",void(save.disabled=!0)}}_saveState(){const updates=this._checkJSON();updates&&this.controller.processUpdates(updates)}_generateStateUpdates(currentStateData,newStateData){const updates=[],ids={};for(const[key,newValue]of Object.entries(newStateData))Array.isArray(newValue)?(ids[key]={},newValue.forEach((element=>{if(void 0===element.id)throw Error("Array ".concat(key," element without id attribute"));updates.push({name:key,action:"override",fields:element});const index=String(element.id).valueOf();ids[key][index]=!0}))):updates.push({name:key,action:"override",fields:newValue});for(const[key,oldValue]of Object.entries(currentStateData)){let deleteField=!1;if(void 0===newStateData[key]&&(deleteField=!0),Array.isArray(oldValue)){if(!deleteField&&void 0===ids[key])throw Error("Array ".concat(key," cannot change to object."));oldValue.forEach((element=>{const index=String(element.id).valueOf();let deleteEntry=deleteField;deleteEntry||void 0!==ids[key][index]||(deleteEntry=!0),deleteEntry&&updates.push({name:key,action:"delete",fields:element})}))}else{if(!deleteField&&void 0!==ids[key])throw Error("Object ".concat(key," cannot change to array."));deleteField&&updates.push({name:key,action:"delete",fields:oldValue})}}return updates}getDraggableData(){return this.draggable}dragEnd(dropdata,event){this.element.style.top="".concat(event.newFixedTop,"px"),this.element.style.left="".concat(event.newFixedLeft,"px")}_togglePin(){this.draggable=!this.draggable,this.dragdrop.setDraggable(this.draggable),this.draggable?this._unpin():this._pin()}_unpin(){const pageCenterY=window.innerHeight/2,pageCenterX=window.innerWidth/2,style={position:"fixed",resize:"both",overflow:"auto",height:"400px",width:"400px",top:"".concat(pageCenterY-200,"px"),left:"".concat(pageCenterX-200,"px")};Object.assign(this.element.style,style),this.getElement(this.selectors.STATE).style.height="50px",this.getElement(this.selectors.LOG).style.height="50px",this._toggleButtonText(this.getElement(this.selectors.PIN))}_pin(){["position","resize","overflow","top","left","height","width"].forEach((prop=>this.element.style.removeProperty(prop))),this._toggleButtonText(this.getElement(this.selectors.PIN))}_toggleButtonText(element){[element.innerHTML,element.dataset.alt]=[element.dataset.alt,element.innerHTML]}}})); define("core/local/reactive/dragdrop",["exports","core/local/reactive/basecomponent"],(function(_exports,_basecomponent){var obj; /** * Drag and drop helper component. * * This component is used to delegate drag and drop handling. * * To delegate the logic to this particular element the component should create a new instance * passing "this" as param. The component will use all the necessary callbacks and add all the * necessary listeners to the component element. * * Component attributes used by dragdrop module: * - element: the draggable or dropzone element. * - (optional) classes: object with alternative CSS classes * - (optional) fullregion: page element affeted by the elementy dragging. Use this attribute if * the draggable element affects a bigger region (for example a draggable * title). * - (optional) autoconfigDraggable: by default, the component will be draggable if it has a * getDraggableData method. If this value is false draggable * property must be defined using setDraggable method. * - (optional) relativeDrag: by default the drag image is located at point (0,0) relative to the * mouse position to prevent the mouse from covering it. If this attribute * is true the drag image will be located at the click offset. * * Methods the parent component should have for making it draggable: * * - getDraggableData(): Object|data * Return the data that will be passed to any valid dropzone while it is dragged. * If the component has this method, the dragdrop module will enable the dragging, * this is the only required method for dragging. * If at the dragging moment this method returns a false|null|undefined, the dragging * actions won't be captured. * * - (optional) dragStart(Object dropdata, Event event): void * - (optional) dragEnd(Object dropdata, Event event): void * Callbacks dragdrop will call when the element is dragged and getDraggableData * return some data. * * Methods the parent component should have for enabling it as a dropzone: * * - validateDropData(Object dropdata): boolean * If that method exists, the dragdrop module will automathically configure the element as dropzone. * This method will return true if the dropdata is accepted. In case it returns false, no drag and * drop event will be listened for this specific dragged dropdata. * * - (Optional) showDropZone(Object dropdata, Event event): void * - (Optional) hideDropZone(Object dropdata, Event event): void * Methods called when a valid dragged data pass over the element. * * - (Optional) drop(Object dropdata, Event event): void * Called when a valid dragged element is dropped over the element. * * Note that none of this methods will be called if validateDropData * returns a false value. * * This module will also add or remove several CSS classes from both dragged elements and dropzones. * See the "this.classes" in the create method for more details. In case the parent component wants * to use the same classes, it can use the getClasses method. On the other hand, if the parent * component has an alternative "classes" attribute, this will override the default drag and drop * classes. * * @module core/local/reactive/dragdrop * @class core/local/reactive/dragdrop * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_basecomponent=(obj=_basecomponent)&&obj.__esModule?obj:{default:obj};let activeDropData=new Map,dragStartPoint={};class _default extends _basecomponent.default{create(parent){var _parent$name,_parent$classes,_this$parent$draggabl,_this$parent$relative;this.name="".concat(null!==(_parent$name=parent.name)&&void 0!==_parent$name?_parent$name:"unkown","_dragdrop"),this.classes=Object.assign({BODYDRAGGING:"dragging",DRAGGABLEREADY:"draggable",DROPREADY:"dropready",DRAGOVER:"dragover",DRAGGING:"dragging",DROPUP:"drop-up",DROPDOWN:"drop-down",DROPZONE:"drop-zone",DRAGICON:"dragicon"},null!==(_parent$classes=null==parent?void 0:parent.classes)&&void 0!==_parent$classes?_parent$classes:{}),this.fullregion=parent.fullregion,this.parent=parent,this.autoconfigDraggable=null===(_this$parent$draggabl=this.parent.draggable)||void 0===_this$parent$draggabl||_this$parent$draggabl,this.relativeDrag=null!==(_this$parent$relative=this.parent.relativeDrag)&&void 0!==_this$parent$relative&&_this$parent$relative,this.entercount=0,this.dropzonevisible=!1}getClasses(){return this.classes}stateReady(){"function"==typeof this.parent.validateDropData&&(this.element.classList.add(this.classes.DROPREADY),this.addEventListener(this.element,"dragenter",this._dragEnter),this.addEventListener(this.element,"dragleave",this._dragLeave),this.addEventListener(this.element,"dragover",this._dragOver),this.addEventListener(this.element,"drop",this._drop)),this.autoconfigDraggable&&"function"==typeof this.parent.getDraggableData&&this.setDraggable(!0)}setDraggable(value){if("function"!=typeof this.parent.getDraggableData)throw new Error("Draggable components must have a getDraggableData method");this.element.setAttribute("draggable",value),value?(this.addEventListener(this.element,"dragstart",this._dragStart),this.addEventListener(this.element,"dragend",this._dragEnd),this.element.classList.add(this.classes.DRAGGABLEREADY)):(this.removeEventListener(this.element,"dragstart",this._dragStart),this.removeEventListener(this.element,"dragend",this._dragEnd),this.element.classList.remove(this.classes.DRAGGABLEREADY))}_dragStart(event){var _this$fullregion;if(document.activeElement.matches("textarea, input"))return void event.preventDefault();const dropdata=this.parent.getDraggableData();if(!dropdata)return;dragStartPoint={pageX:event.pageX,pageY:event.pageY},event.stopPropagation(),activeDropData.set(this.reactive,dropdata),document.body.classList.add(this.classes.BODYDRAGGING),this.element.classList.add(this.classes.DRAGGING),null===(_this$fullregion=this.fullregion)||void 0===_this$fullregion||_this$fullregion.classList.add(this.classes.DRAGGING);let dragImage=this.element;if(void 0!==this.parent.setDragImage){const customImage=this.parent.setDragImage(dropdata,event);customImage&&(dragImage=customImage)}const position={x:0,y:0};this.relativeDrag&&(position.x=event.offsetX,position.y=event.offsetY),event.dataTransfer.setDragImage(dragImage,position.x,position.y),this._callParentMethod("dragStart",dropdata,event)}_dragEnd(event){var _this$fullregion2;const dropdata=activeDropData.get(this.reactive);dropdata&&(activeDropData.delete(this.reactive),document.body.classList.remove(this.classes.BODYDRAGGING),this.element.classList.remove(this.classes.DRAGGING),null===(_this$fullregion2=this.fullregion)||void 0===_this$fullregion2||_this$fullregion2.classList.remove(this.classes.DRAGGING),this._addEventTotalMovement(event),this._callParentMethod("dragEnd",dropdata,event))}_dragEnter(event){const dropdata=this._processEvent(event);dropdata&&(this.entercount++,this.element.classList.add(this.classes.DRAGOVER),1!=this.entercount||this.dropzonevisible||(this.dropzonevisible=!0,this.element.classList.add(this.classes.DRAGOVER),this._callParentMethod("showDropZone",dropdata,event)))}_dragOver(event){const dropdata=this._processEvent(event);dropdata&&!this.dropzonevisible&&(this.dropzonevisible=!0,this.element.classList.add(this.classes.DRAGOVER),this._callParentMethod("showDropZone",dropdata,event))}_dragLeave(event){const dropdata=this._processEvent(event);dropdata&&(this.entercount--,0==this.entercount&&this.dropzonevisible&&(this.dropzonevisible=!1,this.element.classList.remove(this.classes.DRAGOVER),this._callParentMethod("hideDropZone",dropdata,event)))}_drop(event){const dropdata=this._processEvent(event);dropdata&&(this.entercount=0,this.dropzonevisible&&(this.dropzonevisible=!1,this._callParentMethod("hideDropZone",dropdata,event)),this.element.classList.remove(this.classes.DRAGOVER),this._callParentMethod("drop",dropdata,event),dragStartPoint={})}_processEvent(event){const dropdata=this._getDropData(event);return dropdata&&this.parent.validateDropData(dropdata)?(event.preventDefault(),event.stopPropagation(),this._addEventTotalMovement(event),dropdata):null}_addEventTotalMovement(event){if(void 0===dragStartPoint.pageX||void 0===event.pageX)return;event.fixedMovementX=event.pageX-dragStartPoint.pageX,event.fixedMovementY=event.pageY-dragStartPoint.pageY,event.initialPageX=dragStartPoint.pageX,event.initialPageY=dragStartPoint.pageY;const current=this.element.getBoundingClientRect();if(event.newFixedTop=current.top+event.fixedMovementY,event.newFixedLeft=current.left+event.fixedMovementX,void 0!==this.fullregion){const current=this.fullregion.getBoundingClientRect();event.newRegionFixedxTop=current.top+event.fixedMovementY,event.newRegionFixedxLeft=current.left+event.fixedMovementX}}_callParentMethod(methodname,dropdata,event){"function"==typeof this.parent[methodname]&&this.parent[methodname](dropdata,event)}_getDropData(event){if(!this._containsOnlyFiles(event))return activeDropData.get(this.reactive)}_containsOnlyFiles(event){return!!(event.dataTransfer.types&&event.dataTransfer.types.length>0)&&event.dataTransfer.types.every((type=>"Files"===type))}}return _exports.default=_default,_exports.default})); define("core/local/reactive/srlogger",["exports","core/local/reactive/logger"],(function(_exports,_logger){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_logger=(obj=_logger)&&obj.__esModule?obj:{default:obj};class SRLogger extends _logger.default{add(entry){if(entry.feedbackMessage){let loggerFeedback=document.getElementById(SRLogger.liveRegionId);loggerFeedback||(loggerFeedback=document.createElement("div"),loggerFeedback.id=SRLogger.liveRegionId,loggerFeedback.classList.add("sr-only"),loggerFeedback.setAttribute("aria-live","polite"),document.body.append(loggerFeedback)),loggerFeedback.innerHTML=entry.feedbackMessage,setTimeout((()=>{loggerFeedback.innerHTML=""}),4e3)}}}return _exports.default=SRLogger,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value}(SRLogger,"liveRegionId","sr-logger-feedback-container"),_exports.default})); define("core/local/inplace_editable/events",["exports","jquery","core/event_dispatcher"],(function(_exports,_jquery,_event_dispatcher){var obj; /** * Inplace editable module events * * @module core/local/inplace_editable/events * @copyright 2021 Paul Holden * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyElementUpdated=_exports.notifyElementUpdateFailed=_exports.eventTypes=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};const eventTypes={elementUpdated:"core/inplace_editable:updated",elementUpdateFailed:"core/inplace_editable:updateFailed"};_exports.eventTypes=eventTypes;_exports.notifyElementUpdated=(element,ajaxreturn,oldvalue)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.elementUpdated,{ajaxreturn:ajaxreturn,oldvalue:oldvalue},element);_exports.notifyElementUpdateFailed=(element,exception,newvalue)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.elementUpdateFailed,{exception:exception,newvalue:newvalue},element,{cancelable:!0});let legacyEventsRegistered=!1;legacyEventsRegistered||(document.addEventListener(eventTypes.elementUpdated,(event=>{const legacyEvent=_jquery.default.Event("updated",event.detail);(0,_jquery.default)(event.target).trigger(legacyEvent)})),document.addEventListener(eventTypes.elementUpdateFailed,(event=>{const legacyEvent=_jquery.default.Event("updatefailed",event.detail);(0,_jquery.default)(event.target).trigger(legacyEvent),legacyEvent.isDefaultPrevented()&&event.preventDefault()})),legacyEventsRegistered=!0)})); define("core/local/aria/aria-hidden",["exports","core/normalise","./selectors"],(function(_exports,_normalise,_selectors){var obj; /** * ARIA helpers related to the aria-hidden attribute. * * @module core/local/aria/aria-hidden. * @copyright 2020 Andrew Nicols * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.unhideSiblings=_exports.unhide=_exports.hideSiblings=_exports.hide=void 0,_selectors=(obj=_selectors)&&obj.__esModule?obj:{default:obj};const childObserverMap=new Map,siblingObserverMap=new Map,supportsMutationObservers=()=>MutationObserver&&"function"==typeof MutationObserver,disableElementFocusability=target=>{target instanceof HTMLElement&&(target.matches(_selectors.default.elements.focusable)&&disableAndStoreTabIndex(target),target.querySelectorAll(_selectors.default.elements.focusable).forEach(disableAndStoreTabIndex))},disableAndStoreTabIndex=element=>{void 0===element.dataset.ariaHiddenTabIndex&&(element.getAttribute("tabindex")?element.dataset.ariaHiddenTabIndex=element.getAttribute("tabindex"):element.dataset.ariaHiddenTabIndex="",element.setAttribute("tabindex",-1))},restoreTabIndex=element=>{if(element.closest(_selectors.default.aria.hidden))return;const oldTabIndex=element.dataset.ariaHiddenTabIndex;""===oldTabIndex?element.removeAttribute("tabindex"):element.setAttribute("tabindex",oldTabIndex),delete element.dataset.ariaHiddenTabIndex},hide=target=>(0,_normalise.getList)(target).forEach(_hide);_exports.hide=hide;const _hide=target=>{if(target instanceof HTMLElement&&!target.closest(_selectors.default.aria.hidden)&&(target.setAttribute("aria-hidden",!0),disableElementFocusability(target),supportsMutationObservers())){const mutationObserver=new MutationObserver((mutationList=>{mutationList.forEach((mutation=>{if("childList"===mutation.type)mutation.addedNodes.forEach(disableElementFocusability);else if("attributes"===mutation.type){const element=mutation.target,proposedTabIndex=element.getAttribute("tabindex");"-1"!==proposedTabIndex&&(element.dataset.ariaHiddenTabIndex=proposedTabIndex,element.setAttribute("tabindex",-1))}}))}));mutationObserver.observe(target,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["tabindex"]}),childObserverMap.set(target,mutationObserver)}},unhide=target=>(0,_normalise.getList)(target).forEach(_unhide);_exports.unhide=unhide;const _unhide=target=>{target instanceof HTMLElement&&(target.removeAttribute("aria-hidden"),(target=>{target instanceof HTMLElement&&(target.matches(_selectors.default.elements.focusableToUnhide)&&restoreTabIndex(target),target.querySelectorAll(_selectors.default.elements.focusableToUnhide).forEach(restoreTabIndex))})(target),childObserverMap.has(target)&&(childObserverMap.get(target).disconnect(),childObserverMap.delete(target)))};_exports.hideSiblings=target=>(0,_normalise.getList)(target).forEach(_hideSiblings);const _hideSiblings=target=>{if(target instanceof HTMLElement&&target.parentElement&&(target.parentElement.childNodes.forEach((node=>{node!==target&&hide(node)})),supportsMutationObservers())){const newNodeObserver=new MutationObserver((mutationList=>{mutationList.forEach((mutation=>{mutation.addedNodes.forEach((node=>{target.contains(node)||hide(node)}))}))}));newNodeObserver.observe(target.parentElement,{childList:!0,subtree:!0}),siblingObserverMap.set(target.parentElement,newNodeObserver)}};_exports.unhideSiblings=target=>(0,_normalise.getList)(target).forEach(_unhideSiblings);const _unhideSiblings=target=>{target instanceof HTMLElement&&target.parentElement&&(target.parentElement.childNodes.forEach((node=>{node!==target&&unhide(node)})),siblingObserverMap.has(target.parentElement)&&(siblingObserverMap.get(target.parentElement).disconnect(),siblingObserverMap.delete(target.parentElement)))}})); define("core/local/aria/focuslock",["exports","./selectors"],(function(_exports,_selectors){var obj; /** * Tab locking system. * * This is based on code and examples provided in the ARIA specification. * https://www.w3.org/TR/wai-aria-practices/examples/dialog-modal/dialog.html * * @module core/tablock * @copyright 2019 Andrew Nicols * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.untrapFocus=_exports.trapFocus=void 0,_selectors=(obj=_selectors)&&obj.__esModule?obj:{default:obj};const lockRegionStack=[],initialFocusElementStack=[],finalFocusElementStack=[];let lastFocus=null,ignoreFocusChanges=!1,isLocked=!1;const lockHandler=event=>{if(ignoreFocusChanges)return;let lockRegion=getCurrentLockRegion();for(;lockRegion&&!document.contains(lockRegion);)untrapFocus(),lockRegion=getCurrentLockRegion();lockRegion&&(lockRegion.contains(event.target)?lastFocus=event.target:(focusFirstDescendant(),lastFocus==document.activeElement&&focusLastDescendant(),lastFocus=document.activeElement))},focusFirstDescendant=()=>{const lockRegion=getCurrentLockRegion(),focusableElements=Array.from(lockRegion.querySelectorAll(_selectors.default.elements.focusable));return focusableElements.unshift(lockRegion),focusableElements.some((focusableElement=>attemptFocus(focusableElement)))},focusLastDescendant=()=>{const lockRegion=getCurrentLockRegion(),focusableElements=Array.from(lockRegion.querySelectorAll(_selectors.default.elements.focusable)).reverse();return focusableElements.push(lockRegion),focusableElements.some((focusableElement=>attemptFocus(focusableElement)))},attemptFocus=focusTarget=>{if(!(focusTarget=>{if(focusTarget.tabIndex>0||0===focusTarget.tabIndex&&null!==focusTarget.getAttribute("tabIndex"))return!0;if(focusTarget.disabled)return!1;switch(focusTarget.nodeName){case"A":return!!focusTarget.href&&"ignore"!=focusTarget.rel;case"INPUT":return"hidden"!=focusTarget.type&&"file"!=focusTarget.type;case"BUTTON":case"SELECT":case"TEXTAREA":return!0;default:return!1}})(focusTarget))return!1;ignoreFocusChanges=!0;try{focusTarget.focus()}catch(e){}return ignoreFocusChanges=!1,document.activeElement===focusTarget},getCurrentLockRegion=()=>lockRegionStack[lockRegionStack.length-1];_exports.trapFocus=newLockRegion=>{if((newLockRegion=>{if(newLockRegion===getCurrentLockRegion())return;lockRegionStack.push(newLockRegion);const currentLockRegion=getCurrentLockRegion(),element=document.createElement("div");element.tabIndex=0,element.style.position="fixed",element.style.top=0,element.style.left=0;const initialNode=element.cloneNode();currentLockRegion.parentNode.insertBefore(initialNode,currentLockRegion),initialFocusElementStack.push(initialNode);const finalNode=element.cloneNode();currentLockRegion.parentNode.insertBefore(finalNode,currentLockRegion.nextSibling),finalFocusElementStack.push(finalNode)})(newLockRegion),isLocked||document.addEventListener("focus",lockHandler,!0),!focusFirstDescendant()){const currentLockRegion=getCurrentLockRegion(),originalRegionTabIndex=currentLockRegion.tabIndex;currentLockRegion.tabIndex=0,attemptFocus(currentLockRegion),currentLockRegion.tabIndex=originalRegionTabIndex}lastFocus=document.activeElement,isLocked=!0};const untrapFocus=()=>{(()=>{lockRegionStack.pop();const finalNode=finalFocusElementStack.pop();finalNode&&finalNode.remove();const initialNode=initialFocusElementStack.pop();initialNode&&initialNode.remove()})(),lockRegionStack.length||(document.removeEventListener("focus",lockHandler,!0),lastFocus=null,ignoreFocusChanges=!1,isLocked=!1)};_exports.untrapFocus=untrapFocus})); define("core/local/aria/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={aria:{hidden:"[aria-hidden]"},elements:{focusable:'input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',focusableToUnhide:"[data-aria-hidden-tab-index]"}},_exports.default})); define("core/str",["exports","jquery","core/ajax","core/config","core/localstorage"],(function(_exports,_jquery,_ajax,_config,_localstorage){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Fetch and return language strings. * * @module core/str * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 * */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.get_strings=_exports.get_string=_exports.cache_strings=void 0,_jquery=_interopRequireDefault(_jquery),_ajax=_interopRequireDefault(_ajax),_config=_interopRequireDefault(_config),_localstorage=_interopRequireDefault(_localstorage);let promiseCache=[];_exports.get_string=(key,component,param,lang)=>get_strings([{key:key,component:component,param:param,lang:lang}]).then((results=>results[0]));const get_strings=requests=>{let requestData=[];const pageLang=_config.default.language,stringPromises=requests.map((request=>{let{component:component,key:key,param:param,lang:lang=pageLang}=request;component||(component="core");const cacheKey=(_ref=>{let{key:key,component:component,lang:lang=pageLang}=_ref;return"core_str/".concat(key,"/").concat(component,"/").concat(lang)})({key:key,component:component,lang:lang}),buildReturn=promise=>(promiseCache[cacheKey]=promise,promise);if(component in M.str&&key in M.str[component])return buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})));const cached=_localstorage.default.get(cacheKey);return cached?(M.str[component]={...M.str[component],[key]:cached},buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})))):cacheKey in promiseCache?buildReturn(promiseCache[cacheKey]).then((()=>M.util.get_string(key,component,param,lang))):buildReturn(new Promise(((resolve,reject)=>{requestData.push({methodname:"core_get_string",args:{stringid:key,stringparams:[],component:component,lang:lang},done:str=>{M.str[component]={...M.str[component],[key]:str},_localstorage.default.set(cacheKey,str),resolve(M.util.get_string(key,component,param,lang))},fail:reject})})))}));return requestData.length&&_ajax.default.call(requestData,!0,!1,!1,0,M.cfg.langrev),_jquery.default.when.apply(_jquery.default,stringPromises).then((function(){for(var _len=arguments.length,strings=new Array(_len),_key=0;_key<_len;_key++)strings[_key]=arguments[_key];return strings}))};_exports.get_strings=get_strings;_exports.cache_strings=strings=>{strings.forEach((_ref2=>{let{key:key,component:component,value:value,lang:lang=_config.default.language}=_ref2;const cacheKey=["core_str",key,component,lang].join("/");component in M.str&&key in M.str[component]||(component in M.str||(M.str[component]={}),M.str[component][key]=value),_localstorage.default.get(cacheKey)||_localstorage.default.set(cacheKey,value),cacheKey in promiseCache||(promiseCache[cacheKey]=_jquery.default.Deferred().resolve(value).promise())}))}})); /** * Poll the server to keep the session alive. * * @module core/network * @copyright 2019 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/network",["jquery","core/ajax","core/config","core/notification","core/str"],(function($,Ajax,Config,Notification,Str){var started=!1,warningDisplayed=!1,keepAliveFrequency=0,requestTimeout=0,keepAliveMessage=!1,sessionTimeout=!1,checkFrequency=1e3*Math.min(Config.sessiontimeout/10,600),warningLimit=Config.sessiontimeoutwarning>0?1e3*Config.sessiontimeoutwarning:2*checkFrequency,firstWait=Config.sessiontimeoutwarning>0?Math.min(1e3*(Config.sessiontimeout-Config.sessiontimeoutwarning),5*checkFrequency):5*checkFrequency,timeoutSessionExpired=function(modal){sessionTimeout=!0,warningDisplayed=!1,closeModal(modal),displaySessionExpired()},closeModal=function(modal){modal.destroy()},displaySessionExpired=function(){return Ajax.call([{methodname:"core_session_time_remaining",args:{}}],!0,!0,!0)[0].then((function(args){return!(1e3*args.timeremaining>warningLimit)&&Str.get_strings([{key:"sessionexpired",component:"error"},{key:"sessionerroruser",component:"error"},{key:"loginagain",component:"moodle"},{key:"cancel",component:"moodle"}]).then((function(strings){return Notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){return location.reload(),!0})),!0})).catch(Notification.exception)}))},touchSession=function(){return sessionTimeout?displaySessionExpired():Ajax.call([{methodname:"core_session_touch",args:{}}],!0,!0,!1,requestTimeout)[0].then((function(){return keepAliveFrequency>0&&setTimeout(touchSession,keepAliveFrequency),!0})).catch((function(){Notification.alert("",keepAliveMessage)}))},checkSession=function(){return sessionTimeout=!1,Ajax.call([{methodname:"core_session_time_remaining",args:{}}],!0,!0,!0)[0].then((function(args){return!(args.userid<=0)&&(args.timeremaining<=0?displaySessionExpired():(1e3*args.timeremaining<=warningLimit&&!warningDisplayed?(warningDisplayed=!0,Str.get_strings([{key:"norecentactivity",component:"moodle"},{key:"sessiontimeoutsoon",component:"moodle"},{key:"extendsession",component:"moodle"},{key:"cancel",component:"moodle"}]).then((function(strings){return Notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){return touchSession(),warningDisplayed=!1,setTimeout(checkSession,firstWait),!0}),(function(){setTimeout(checkSession,checkFrequency)}))})).then((modal=>{setTimeout(timeoutSessionExpired,1e3*args.timeremaining,modal)})).catch(Notification.exception)):setTimeout(checkSession,checkFrequency),!0))}))},start=function(){keepAliveFrequency>0?setTimeout(touchSession,keepAliveFrequency):setTimeout(checkSession,firstWait)};const isMoodleIframe=function(){if(window.parent===window)return!1;let parentUrl;try{parentUrl=window.parent.location.href}catch(e){return!1}return parentUrl.startsWith(M.cfg.wwwroot)};return{keepalive:async function(freq,timeout,identifier,component){started?window.console.warn("Ignoring session keep-alive. The core/network module was already initialised."):(started=!0,isMoodleIframe()?window.console.warn("Ignoring session keep-alive in this iframe inside another Moodle page."):(window.console.log("Starting Moodle session keep-alive."),keepAliveFrequency=1e3*freq,keepAliveMessage=await Str.get_string(identifier,component),requestTimeout=1e3*timeout,start()))},init:function(){started||(started=!0,isMoodleIframe()?window.console.log("Not starting Moodle session timeout warning in this iframe."):(window.console.log("Starting Moodle session timeout warning."),start()))}}})); /** * Wrap an instance of the browser's local or session storage to handle * cache expiry, key namespacing and other helpful things. * * @module core/storagewrapper * @copyright 2017 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/storagewrapper",["core/config"],(function(config){var Wrapper=function(storage){this.storage=storage,this.supported=this.detectSupport(),this.hashSource=config.wwwroot+"/"+config.jsrev,this.hash=this.hashString(this.hashSource),this.prefix=this.hash+"/",this.jsrevPrefix=this.hashString(config.wwwroot)+"/jsrev",this.validateCache()};return Wrapper.prototype.detectSupport=function(){if(-1==config.jsrev)return!1;if(void 0===this.storage)return!1;try{return null!==this.storage&&(this.storage.setItem("test","1"),this.storage.removeItem("test"),!0)}catch(ex){return!1}},Wrapper.prototype.prefixKey=function(key){return this.prefix+key},Wrapper.prototype.validateCache=function(){if(this.supported){var cacheVersion=this.storage.getItem(this.jsrevPrefix);if(null!==cacheVersion)config.jsrev!=cacheVersion&&(this.storage.clear(),this.storage.setItem(this.jsrevPrefix,config.jsrev));else this.storage.setItem(this.jsrevPrefix,config.jsrev)}},Wrapper.prototype.hashString=function(source){var i,len,hash=0;if(0===source.length)return hash;for(i=0,len=source.length;i * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_paging_dropdown",["jquery","core/custom_interaction_events","core/paged_content_events","core/pubsub"],(function($,CustomEvents,PagedContentEvents,PubSub){var SELECTORS_DROPDOWN_ITEM='[data-region="dropdown-item"]',SELECTORS_DROPDOWN_TOGGLE='[data-region="dropdown-toggle"]',SELECTORS_ACTIVE_DROPDOWN_ITEM='[data-region="dropdown-item"].active',SELECTORS_CARET='[data-region="caret"]',getPageNumber=function(item){return parseInt(item.attr("data-page-number"),10)},getAllItems=function(root){return root.find(SELECTORS_DROPDOWN_ITEM)},getPreviousItems=function(root,item){var pageNumber=getPageNumber(item);return getAllItems(root).filter((function(index,element){return getPageNumber($(element))").attr("name",this.name);e.preventDefault(),str.get_strings([{key:"delete",component:"core"},{key:"confirmdeletetags",component:"tag"},{key:"yes",component:"core"},{key:"no",component:"core"}]).then((function(s){return notification.confirm(s[0],s[1],s[2],s[3],(function(){tempElement.appendTo(form),form.submit()}))})).always(pendingPromise.resolve).catch(notification.exception)}})),$("#tag-management-combine").click((function(e){var pendingPromise=new Pending("core/tag:tag-management-combine");e.preventDefault();var form=$(this).closest("form").get(0),tags=$(form).find("input[data-togglegroup='tags-manage'][data-toggle='slave']:checked");if(tags.length<=1)str.get_strings([{key:"combineselected",component:"tag"},{key:"selectmultipletags",component:"tag"},{key:"ok"}]).then((function(s){return notification.alert(s[0],s[1],s[2])})).always(pendingPromise.resolve).catch(notification.exception);else{var tempElement=$("").attr("name",this.name),saveButtonText="",tagOptions=[];tags.each((function(){var tagid=$(this).val(),tagname=$(".inplaceeditable[data-itemtype=tagname][data-itemid="+tagid+"]").attr("data-value");tagOptions.push({id:tagid,name:tagname})})),str.get_strings([{key:"combineselected",component:"tag"},{key:"continue",component:"core"}]).then((function(langStrings){var modalTitle=langStrings[0];saveButtonText=langStrings[1];var templateContext={tags:tagOptions};return ModalFactory.create({title:modalTitle,body:templates.render("core_tag/combine_tags",templateContext),type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){return modal.setSaveButtonText(saveButtonText),modal})).then((function(modal){modal.getRoot().on(ModalEvents.save,(function(e){e.preventDefault(),tempElement.appendTo(form);var maintag=$("input[name=maintag]:checked","#combinetags_form").val();$("").attr("name","maintag").attr("value",maintag).appendTo(form),form.submit()})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show(),$("#combinetags_form input[type=radio]").first().focus().prop("checked",!0)})).always(pendingPromise.resolve).catch(notification.exception)}})),$("body").on("updatefailed","[data-inplaceeditable][data-itemtype=tagname]",(function(e){var exception=e.exception,newvalue=e.newvalue,tagid=$(e.target).attr("data-itemid");if("namesalreadybeeingused"===exception.errorcode){var pendingPromise=new Pending("core/tag:updatefailed");e.preventDefault(),str.get_strings([{key:"confirm",component:"core"},{key:"nameuseddocombine",component:"tag"},{key:"yes",component:"core"},{key:"cancel",component:"core"}]).then((function(s){return notification.confirm(s[0],s[1],s[2],s[3],(function(){window.location.href=window.location.href+"&newname="+encodeURIComponent(newvalue)+"&tagid="+encodeURIComponent(tagid)+"&action=renamecombine&sesskey="+M.cfg.sesskey}))})).always(pendingPromise.resolve).catch(notification.exception)}})),$("body").on("click","a[data-action=addstandardtag]",(function(e){var pendingPromise=new Pending("core/tag:addstandardtag");return e.preventDefault(),ModalFactory.create({title:str.get_string("addotags","tag"),body:templates.render("core_tag/add_tags",{actionurl:window.location.href,sesskey:M.cfg.sesskey}),type:ModalFactory.types.SAVE_CANCEL}).then((function(modal){modal.setSaveButtonText(str.get_string("continue","core")),modal.getRoot().on(ModalEvents.save,(function(e){var tagsInput=$(e.currentTarget).find("#id_tagslist"),name=tagsInput.val().trim();tagsInput.val(name);var tagsForm=$("#addtags_form");return tagsForm.on("submit",(function(e){var form=$("#addtags_form");!1===form[0].checkValidity()&&(e.preventDefault(),e.stopPropagation()),form.addClass("was-validated"),$('[data-region="tagslistinput"]').addClass("error");var errorMessage=$("#id_tagslist_error_message");errorMessage.removeAttr("hidden"),errorMessage.addClass("help-block")})),tagsForm.submit(),!1})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show()})).always(pendingPromise.resolve).catch(notification.exception)}))},initManageCollectionsPage:function(){$("body").on("updated","[data-inplaceeditable]",(function(e){var areaid,collid,pendingPromise=new Pending("core/tag:initManageCollectionsPage-updated"),ajaxreturn=e.ajaxreturn;"core_tag"===ajaxreturn.component&&"tagareaenable"===ajaxreturn.itemtype&&(areaid=$(this).attr("data-itemid"),$(".tag-collections-table ul[data-collectionid] li[data-areaid="+areaid+"]").hide(),"1"===ajaxreturn.value?($(this).closest("tr").removeClass("dimmed_text"),collid=$(this).closest("tr").find('[data-itemtype="tagareacollection"]').attr("data-value"),$(".tag-collections-table ul[data-collectionid="+collid+"] li[data-areaid="+areaid+"]").show()):$(this).closest("tr").addClass("dimmed_text")),"core_tag"===ajaxreturn.component&&"tagareacollection"===ajaxreturn.itemtype&&(areaid=$(this).attr("data-itemid"),$(".tag-collections-table ul[data-collectionid] li[data-areaid="+areaid+"]").hide(),collid=$(this).attr("data-value"),"1"===$(this).closest("tr").find('[data-itemtype="tagareaenable"]').attr("data-value")&&$(".tag-collections-table ul[data-collectionid="+collid+"] li[data-areaid="+areaid+"]").show()),pendingPromise.resolve()})),$("body").on("click",".addtagcoll > a",(function(e){var pendingPromise=new Pending("core/tag:initManageCollectionsPage-addtagcoll");e.preventDefault();var href=$(this).attr("data-url"),saveButtonText="";str.get_strings([{key:"addtagcoll",component:"tag"},{key:"create",component:"core"}]).then((function(langStrings){var modalTitle=langStrings[0];saveButtonText=langStrings[1];var templateContext={actionurl:href,sesskey:M.cfg.sesskey};return ModalFactory.create({title:modalTitle,body:templates.render("core_tag/add_tag_collection",templateContext),type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){return modal.setSaveButtonText(saveButtonText),modal.getRoot().on(ModalEvents.save,(function(e){var collectionInput=$(e.currentTarget).find("#addtagcoll_name"),name=collectionInput.val().trim();collectionInput.val(name);var form=$("#addtagcoll_form");return form.on("submit",(function(e){!1===form[0].checkValidity()&&(e.preventDefault(),e.stopPropagation()),form.addClass("was-validated"),$('[data-region="addtagcoll_nameinput"]').addClass("error");var errorMessage=$("#id_addtagcoll_name_error_message");errorMessage.removeAttr("hidden"),errorMessage.addClass("help-block")})),form.submit(),!1})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show(),modal})).always(pendingPromise.resolve).catch(notification.exception)})),$("body").on("click",".tag-collections-table .action_delete",(function(e){var pendingPromise=new Pending("core/tag:initManageCollectionsPage-action_delete");e.preventDefault();var href=$(this).attr("data-url")+"&sesskey="+M.cfg.sesskey;str.get_strings([{key:"delete"},{key:"suredeletecoll",component:"tag",param:$(this).attr("data-collname")},{key:"yes"},{key:"no"}]).then((function(s){return notification.confirm(s[0],s[1],s[2],s[3],(function(){window.location.href=href}))})).always(pendingPromise.resolve).catch(notification.exception)}))}}})); define("core/fullscreen",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getElement=void 0;_exports.getElement=()=>{let element=null;return document.fullscreenElement?element=document.fullscreenElement:document.mozFullscreenElement?element=document.mozFullscreenElement:document.msFullscreenElement?element=document.msFullscreenElement:document.webkitFullscreenElement&&(element=document.webkitFullscreenElement),element}})); define("core/moremenu",["exports","jquery","core/menu_navigation"],(function(_exports,_jquery,_menu_navigation){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Moves wrapping navigation items into a more menu. * * @module core/moremenu * @copyright 2021 Moodle * @author Bas Brands * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_menu_navigation=_interopRequireDefault(_menu_navigation);const Selectors_regions={moredropdown:'[data-region="moredropdown"]',morebutton:'[data-region="morebutton"]'},Selectors_classes={dropdownitem:"dropdown-item",dropdownmoremenu:"dropdownmoremenu",hidden:"d-none",active:"active",nav:"nav",navlink:"nav-link",observed:"observed"},Selectors_attributes={menu:'[role="menu"]',dropdowntoggle:'[data-toggle="dropdown"]'};let isTabListMenu=!1;const autoCollapse=menu=>{const maxHeight=menu.parentNode.offsetHeight+1,moreDropdown=menu.querySelector(Selectors_regions.moredropdown),moreButton=menu.querySelector(Selectors_regions.morebutton);if(menu.offsetHeight>maxHeight){moreButton.classList.remove(Selectors_classes.hidden);let menuHeight=0;Array.from(menu.children).reverse().forEach((item=>{item.classList.contains(Selectors_classes.dropdownmoremenu)?menu.offsetHeight>maxHeight&&(menuHeight=menu.offsetHeight):menu.offsetHeight>maxHeight?moveIntoMoreDropdown(menu,item,!0):menuHeight>maxHeight&&(moveIntoMoreDropdown(menu,item,!0),menuHeight=0)}))}else"children"in moreDropdown&&(Array.from(moreDropdown.children).forEach((item=>{if(menu.offsetHeightmaxHeight&&autoCollapse(menu);menu.parentNode.classList.add(Selectors_classes.observed)},moveIntoMoreDropdown=function(menu,navNode){let prepend=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const moreDropdown=menu.querySelector(Selectors_regions.moredropdown),dropdownToggle=menu.querySelector(Selectors_attributes.dropdowntoggle),navLink=navNode.querySelector("."+Selectors_classes.navlink);navLink.classList.contains(Selectors_classes.active)&&(dropdownToggle.classList.add(Selectors_classes.active),dropdownToggle.setAttribute("tabindex","0"),navLink.setAttribute("tabindex","-1"),isTabListMenu&&navLink.removeAttribute("aria-selected"),navLink.setAttribute("aria-current","true")),navLink.setAttribute("role","menuitem"),navLink.classList.remove(Selectors_classes.navlink),navLink.classList.add(Selectors_classes.dropdownitem),prepend?moreDropdown.prepend(navNode):moreDropdown.append(navNode)},moveOutOfMoreDropdown=(menu,navNode)=>{const moreButton=menu.querySelector(Selectors_regions.morebutton),dropdownToggle=menu.querySelector(Selectors_attributes.dropdowntoggle),navLink=navNode.querySelector("."+Selectors_classes.dropdownitem);isTabListMenu&&navLink.setAttribute("role","tab"),navLink.classList.contains(Selectors_classes.active)&&(dropdownToggle.classList.remove(Selectors_classes.active),dropdownToggle.setAttribute("tabindex","-1"),navLink.setAttribute("tabindex","0"),isTabListMenu&&(navLink.removeAttribute("aria-current"),navLink.setAttribute("aria-selected","true"))),navLink.classList.remove(Selectors_classes.dropdownitem),navLink.classList.add(Selectors_classes.navlink),menu.insertBefore(navNode,moreButton)};return _exports.default=menu=>{isTabListMenu="tablist"===menu.getAttribute("role");if(!window.location.hash){const itemRole=isTabListMenu?"tab":"menuitem",menuListItem=menu.firstElementChild,roleSelector="[role=".concat(itemRole,"]"),menuItem=menuListItem.querySelector(roleSelector),ariaAttribute=isTabListMenu?"aria-selected":"aria-current";menu.querySelector("[".concat(ariaAttribute,"='true']"))||(menuItem.setAttribute(ariaAttribute,"true"),menuItem.setAttribute("tabindex","0"))}if("children"in menu){const moreButton=menu.querySelector(Selectors_regions.morebutton);Array.from(menu.children).forEach((item=>{item.classList.contains(Selectors_classes.dropdownmoremenu)||"true"!==item.dataset.forceintomoremenu||(moveIntoMoreDropdown(menu,item,!1),moreButton.classList.contains(Selectors_classes.hidden)&&moreButton.classList.remove(Selectors_classes.hidden))}))}autoCollapse(menu),(0,_menu_navigation.default)(menu),window.addEventListener("resize",(()=>{autoCollapse(menu),(0,_menu_navigation.default)(menu)}));const toggledropdown=e=>{const innerMenu=e.target.parentNode.querySelector(Selectors_attributes.menu);innerMenu&&innerMenu.classList.toggle("show"),e.stopPropagation()};(0,_jquery.default)("."+Selectors_classes.dropdownmoremenu).on("show.bs.dropdown",(function(){menu.querySelector(Selectors_regions.moredropdown).querySelectorAll(".dropdown").forEach((dropdown=>{dropdown.removeEventListener("click",toggledropdown,!0),dropdown.addEventListener("click",toggledropdown,!0)}))}))},_exports.default})); define("core/pubsub",["exports","core/pending"],(function(_exports,_pending){var obj; /** * A simple Javascript PubSub implementation. * * @module core/pubsub * @copyright 2018 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.unsubscribe=_exports.subscribe=_exports.publish=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};const events={};_exports.subscribe=function(eventName,callback){events[eventName]=events[eventName]||[],events[eventName].push(callback)};_exports.unsubscribe=function(eventName,callback){if(events[eventName])for(var i=0;i * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_paging_bar_limit_selector",["jquery","core/custom_interaction_events","core/paged_content_events","core/pubsub"],(function($,CustomEvents,PagedContentEvents,PubSub){var SELECTORS_LIMIT_OPTION="[data-limit]";return{init:function(root,id){root=$(root),CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_LIMIT_OPTION,(function(e,data){var optionElement=$(e.target).closest(SELECTORS_LIMIT_OPTION);if(!optionElement.hasClass("active")){var limit=parseInt(optionElement.attr("data-limit"),10);PubSub.publish(id+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT,limit),data.originalEvent.preventDefault()}}))},rootSelector:'[data-region="paging-control-limit-container"]'}})); /** * Module for text truncation. * * Implementation provided by Pathable (thanks!). * See: https://github.com/pathable/truncate * * @module core/truncate * @copyright 2017 Pathable * 2017 Mathias Bynens * 2017 Ryan Wyllie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/truncate",["jquery"],(function($){var chop=/(\s*\S+|\s)$/,start=/^(\S*)/,space=/\s/,charLengthAt=function(text,position){var string=String(text),size=string.length,index=position?Number(position):0;if(index!=index&&(index=0),index<=-1||index>=size)return"";index|=0;var cuSecond,cuFirst=string.charCodeAt(index),nextIndex=index+1,len=1;return cuFirst>=55296&&cuFirst<=56319&&size>nextIndex&&(cuSecond=string.charCodeAt(nextIndex))>=56320&&cuSecond<=57343&&(len=2),len},lengthMultiByte=function(text){for(var count=0,i=0;i").append(html).truncate(options).html()},$.fn.truncate=function(options){isNaN(parseFloat(options))||(options={length:options});var o=$.extend({},$.truncate.defaults,options);return this.each((function(){var self=$(this);o.noBreaks&&self.find("br").replaceWith(" ");var ellipsisLength=o.ellipsis.length,text=self.text(),textLength=lengthMultiByte(text),excess=textLength-o.length+ellipsisLength;if(!(textLength0){var sliced=text.slice(0,getSliceLength(text,o.length-ellipsisLength)+1),replaced=sliced.replace(chop,""),truncated=lengthMultiByte(replaced),oneWord=!sliced.match(space);excess=o.keepFirstWord&&0===truncated?textLength-lengthMultiByte(start.exec(text)[0])-ellipsisLength:oneWord&&0===truncated?textLength-o.length+ellipsisLength:textLength-truncated-1}excess>textLength&&(excess=textLength-o.length),excess<0||!excess&&!o.truncated||$.each(self.contents().get().reverse(),(function(i,el){var $el=$(el),text=$el.text(),length=lengthMultiByte(text);if(length<=excess)return o.truncated=!0,excess-=length,void $el.remove();if(3===el.nodeType){var splitAmount=length-excess;return splitAmount=splitAmount>=0?getSliceLength(text,splitAmount):0,$(el.splitText(splitAmount)).replaceWith(o.ellipsis),!1}return $el.truncate($.extend(o,{length:length-excess+ellipsisLength})),!1}))}}))},$.truncate.defaults={stripTags:!1,words:!1,keepFirstWord:!1,noBreaks:!1,length:1/0,ellipsis:"…"},{truncate:$.truncate}})); define("core/copy_to_clipboard",["core/str","core/toast","core/prefetch"],(function(_str,_toast,_prefetch){ /** * A JavaScript module that enhances a button and text container to support copy-to-clipboard functionality. * * This module needs to be loaded by pages/templates/modules that require this functionality. * * To enable copy-to-clipboard functionality, we need a trigger element (usually a button) and a copy target element * (e.g. a div, span, text input, or text area). * * In the trigger element, we need to declare the data-action="copytoclipboard" attribute and set the * data-clipboard-target attribute which is the CSS selector that points to the target element that contains the text * to be copied. * * When the text is successfully copied to the clipboard, a toast message that indicates that the copy operation was a success * will be shown. This success message can be customised by setting the data-clipboard-success-message attribute in the * trigger element. * * @module core/copy_to_clipboard * @copyright 2021 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * @example Markup for the trigger and target elements * * */ const copyNodeContentToClipboard=(copyButton,copyTarget)=>(copyTarget.select(),document.execCommand("copy")?(displaySuccessToast(copyButton),!0):(displayFailureToast(),!1)),displaySuccessToast=copyButton=>getSuccessText(copyButton).then((successMessage=>(0,_toast.add)(successMessage,{}))),displayFailureToast=()=>getFailureText().then((message=>(0,_toast.add)(message,{type:"warning"}))),getFailureText=()=>(0,_str.get_string)("unabletocopytoclipboard","core"),getSuccessText=copyButton=>copyButton.dataset.clipboardSuccessMessage?Promise.resolve(copyButton.dataset.clipboardSuccessMessage):(0,_str.get_string)("textcopiedtoclipboard","core"),getTextFromContainer=container=>container.value?container.value:container.innerText?container.innerText:null;let loaded=!1;loaded||((0,_prefetch.prefetchStrings)("core",["textcopiedtoclipboard","unabletocopytoclipboard"]),document.addEventListener("click",(e=>{const copyButton=e.target.closest('[data-action="copytoclipboard"]');if(!copyButton)return;if(!copyButton.dataset.clipboardTarget)return;const copyTarget=document.querySelector(copyButton.dataset.clipboardTarget);if(!copyTarget)return;e.preventDefault();const textToCopy=getTextFromContainer(copyTarget);if(textToCopy)if(navigator.clipboard)navigator.clipboard.writeText(textToCopy).then((()=>displaySuccessToast(copyButton))).catch();else if(copyTarget instanceof HTMLInputElement||copyTarget instanceof HTMLTextAreaElement)copyTarget.focus(),copyNodeContentToClipboard(copyButton,copyTarget)&©Button.focus();else{const copyRegion=document.createElement("textarea");copyRegion.value=textToCopy,copyRegion.classList.add("sr-only"),document.body.appendChild(copyRegion),copyNodeContentToClipboard(copyButton,copyRegion),copyRegion.remove(),copyButton.focus()}else displayFailureToast()})),loaded=!0)})); 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})); /** * Chart output for HTML table. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_output_htmltable */ define("core/chart_output_htmltable",["jquery","core/chart_output_base"],(function($,Base){function Output(){Base.prototype.constructor.apply(this,arguments),this._build()}return Output.prototype=Object.create(Base.prototype),Output.prototype._build=function(){this._node.empty(),this._node.append(this._makeTable())},Output.prototype._makeTable=function(){var node,value,tbl=$(""),c=this._chart,labels=c.getLabels(),hasLabel=labels.length>0,series=c.getSeries(),rowCount=series[0].getCount();tbl.addClass("chart-output-htmltable generaltable"),null!==c.getTitle()&&tbl.append($(""),hasLabel&&node.append($("
").text(c.getTitle())),node=$("
")),series.forEach((function(serie){node.append($("").text(serie.getLabel()).attr("scope","col"))})),tbl.append(node);for(var rowId=0;rowId"),labels.length>0&&node.append($("").text(labels[rowId]).attr("scope","row"));for(var serieId=0;serieId").text(value));tbl.append(node)}return tbl},Output.prototype.update=function(){this._build()},Output})); /** * Standard Ajax wrapper for Moodle. It calls the central Ajax script, * which can call any existing webservice using the current session. * In addition, it can batch multiple requests and return multiple responses. * * @module core/ajax * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/ajax",["jquery","core/config","core/log","core/url"],(function($,config,Log,URL){var unloading=!1,requestSuccess=function(responses){var request,response,nosessionupdate,exception=null,i=0;if(responses.error)for(;i2e3?(settings.type="POST",settings.data=ajaxRequestData):url=urlUseGet}return async?$.ajax(url,settings).done(requestSuccess).fail(requestFail):(settings.success=requestSuccess,settings.error=requestFail,$.ajax(url,settings)),promises}}})); /** * @copyright 2015 Martin Mastny * @since 3.0 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/permissionmanager",["jquery","core/config","core/notification","core/templates","core/yui"],(function($,config,notification,templates,Y){var contextid,contextname,adminurl,overideableroles,SELECTORS_ADDROLE="a.allowlink, a.prohibitlink",SELECTORS_REMOVEROLE="a.preventlink, a.unprohibitlink",SELECTORS_UNPROHIBIT="a.unprohibitlink",rolesloadedevent=$.Event("rolesloaded"),panel=null,loadOverideableRoles=function(){var params={contextid:contextid,getroles:1,sesskey:config.sesskey};$.post(adminurl+"roles/ajax.php",params,null,"json").done((function(data){try{overideableroles=data,(loadOverideableRoles=function(){$("body").trigger(rolesloadedevent)})()}catch(err){notification.exception(err)}})).fail((function(jqXHR,status,error){notification.exception(error)}))},changePermissions=function(row,roleid,action){var params={contextid:contextid,roleid:roleid,sesskey:M.cfg.sesskey,action:action,capability:row.data("name")};$.post(adminurl+"roles/ajax.php",params,null,"json").done((function(data){var action=data;try{var templatedata={rolename:overideableroles[roleid],roleid:roleid,adminurl:adminurl,imageurl:M.util.image_url("t/delete","moodle")};switch(action){case"allow":templatedata.spanclass="allowed",templatedata.linkclass="preventlink",templatedata.action="prevent",templatedata.icon="t/delete",templatedata.iconalt=M.util.get_string("deletexrole","core_role",overideableroles[roleid]);break;case"prohibit":templatedata.spanclass="forbidden",templatedata.linkclass="unprohibitlink",templatedata.action="unprohibit",templatedata.icon="t/delete",templatedata.iconalt=M.util.get_string("deletexrole","core_role",overideableroles[roleid]);break;case"prevent":return void row.find('a[data-role-id="'+roleid+'"]').first().closest(".allowed").remove();case"unprohibit":return void row.find('a[data-role-id="'+roleid+'"]').first().closest(".forbidden").remove();default:return}templates.render("core/permissionmanager_role",templatedata).done((function(content){if("allow"==action)$(content).insertBefore(row.find(".allowmore").first());else if("prohibit"==action){$(content).insertBefore(row.find(".prohibitmore").first());var allowedLink=row.find(".allowedroles").first().find('a[data-role-id="'+roleid+'"]');allowedLink&&allowedLink.first().closest(".allowed").remove()}panel.hide()})).fail(notification.exception)}catch(err){notification.exception(err)}})).fail((function(jqXHR,status,error){notification.exception(error)}))},handleAddRole=function(e){e.preventDefault();var link=$(e.currentTarget);$("body").one("rolesloaded",(function(){Y.use("moodle-core-notification-dialogue",(function(){var i,existingrolelinks,action=link.data("action"),row=link.closest("tr.rolecap"),confirmationDetails={cap:row.data("humanname"),context:contextname},message=M.util.get_string("role"+action+"info","core_role",confirmationDetails);null===panel&&(panel=new M.core.dialogue({draggable:!0,modal:!0,closeButton:!0,width:"450px"})),panel.set("headerContent",M.util.get_string("role"+action+"header","core_role"));var roles=[];switch(action){case"allow":existingrolelinks=row.find(SELECTORS_REMOVEROLE);break;case"prohibit":existingrolelinks=row.find(SELECTORS_UNPROHIBIT)}for(i in overideableroles){var disabled="";existingrolelinks.filter("[data-role-id='"+i+"']").length&&(disabled="disabled");var roledetails={roleid:i,rolename:overideableroles[i],disabled:disabled};roles.push(roledetails)}templates.render("core/permissionmanager_panelcontent",{message:message,roles:roles}).done((function(content){panel.set("bodyContent",content),panel.show(),$("div.role_buttons").on("click","button",(function(e){var roleid=$(e.currentTarget).data("role-id");changePermissions(row,roleid,action)}))})).fail(notification.exception)}))})),loadOverideableRoles()},handleRemoveRole=function(e){e.preventDefault();var link=$(e.currentTarget);$("body").one("rolesloaded",(function(){var action=link.data("action"),roleid=link.data("role-id"),row=link.closest("tr.rolecap"),questionDetails={role:overideableroles[roleid],cap:row.data("humanname"),context:contextname};notification.confirm(M.util.get_string("confirmunassigntitle","core_role"),M.util.get_string("confirmrole"+action,"core_role",questionDetails),M.util.get_string("confirmunassignyes","core_role"),M.util.get_string("confirmunassignno","core_role"),(function(){changePermissions(row,roleid,action)}))})),loadOverideableRoles()};return{initialize:function(args){contextid=args.contextid,contextname=args.contextname,adminurl=args.adminurl;var body=$("body");body.on("click",SELECTORS_ADDROLE,handleAddRole),body.on("click",SELECTORS_REMOVEROLE,handleRemoveRole)}}})); /** * Chart.js loader. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/chartjs",["core/chartjs-lazy"],(function(ChartJS){return ChartJS})); define("core/usermenu",["exports","jquery","core/key_codes"],(function(_exports,_jquery,_key_codes){var obj; /** * Initializes and handles events in the user menu. * * @module core/usermenu * @copyright 2021 Moodle * @author Mihail Geshoski * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};const selectors_userMenu=".usermenu",selectors_userMenuCarousel=".usermenu #usermenu-carousel",selectors_userMenuCarouselItem=".usermenu #usermenu-carousel .carousel-item",selectors_userMenuCarouselItemActive=".usermenu #usermenu-carousel .carousel-item.active",selectors_userMenuCarouselNavigationLink=".usermenu #usermenu-carousel .carousel-navigation-link";var _default={init:()=>{(()=>{const userMenu=document.querySelector(selectors_userMenu);(0,_jquery.default)(selectors_userMenu).on("shown.bs.dropdown",(()=>{const activeCarouselItem=document.querySelector(selectors_userMenuCarouselItemActive);activeCarouselItem.focus(),userMenu.querySelectorAll(selectors_userMenuCarouselItem).forEach((element=>{element.classList.contains("active")||(element.style.width=activeCarouselItem.offsetWidth+"px",element.style.height=activeCarouselItem.offsetHeight+"px")}))})),userMenu.addEventListener("click",(e=>{e.target.matches(selectors_userMenuCarouselNavigationLink)&&carouselManagement(e)})),userMenu.addEventListener("keydown",(e=>{e.keyCode!==_key_codes.space&&e.keyCode!==_key_codes.enter||!e.target.matches(selectors_userMenuCarouselNavigationLink)||(e.preventDefault(),carouselManagement(e))}));const carouselManagement=e=>{e.stopPropagation();const targetedCarouselItemId=e.target.dataset.carouselTargetId,targetedCarouselItem=userMenu.querySelector("#"+targetedCarouselItemId),index=Array.from(targetedCarouselItem.parentNode.children).indexOf(targetedCarouselItem);(0,_jquery.default)(selectors_userMenuCarousel).carousel(index)};(0,_jquery.default)(selectors_userMenu).on("hide.bs.dropdown",(()=>{(0,_jquery.default)(selectors_userMenuCarousel).carousel(0)})),(0,_jquery.default)(selectors_userMenuCarousel).on("slid.bs.carousel",(()=>{userMenu.querySelector(selectors_userMenuCarouselItemActive).focus()}))})()}};return _exports.default=_default,_exports.default})); /** * Chart pie. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_pie */ define("core/chart_pie",["core/chart_base"],(function(Base){function Pie(){Base.prototype.constructor.apply(this,arguments)}return Pie.prototype=Object.create(Base.prototype),Pie.prototype.TYPE="pie",Pie.prototype._doughnut=null,Pie.prototype.create=function(Klass,data){var chart=Base.prototype.create.apply(this,arguments);return chart.setDoughnut(data.doughnut),chart},Pie.prototype.addSeries=function(series){if(null===series.getColor()){for(var colors=[],configColorSet=this.getConfigColorSet()||Base.prototype.COLORSET,i=0;i=1)throw new Error("Pie charts only support one serie.");return Base.prototype._validateSeries.apply(this,arguments)},Pie})); define("core/reactive",["exports","core/local/reactive/basecomponent","core/local/reactive/reactive","core/local/reactive/dragdrop","core/local/reactive/debug"],(function(_exports,_basecomponent,_reactive,_dragdrop,_debug){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Generic reactive module used in the course editor. * * @module core/reactive * @copyright 2021 Ferran Recio * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */let debug;if(Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"BaseComponent",{enumerable:!0,get:function(){return _basecomponent.default}}),Object.defineProperty(_exports,"DragDrop",{enumerable:!0,get:function(){return _dragdrop.default}}),Object.defineProperty(_exports,"Reactive",{enumerable:!0,get:function(){return _reactive.default}}),_exports.debug=void 0,_basecomponent=_interopRequireDefault(_basecomponent),_reactive=_interopRequireDefault(_reactive),_dragdrop=_interopRequireDefault(_dragdrop),_exports.debug=debug,M.cfg.developerdebug&&void 0===M.reactive){const debugOBject=(0,_debug.initDebug)();M.reactive=debugOBject.debuggers,_exports.debug=debug=debugOBject.debug}})); /** * Template renderer for Moodle. Load and render Moodle templates with Mustache. * * @module core/templates * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/templates",["core/mustache","jquery","core/ajax","core/str","core/notification","core/url","core/config","core/localstorage","core/icon_system","core_filters/events","core/yui","core/log","core/truncate","core/user_date","core/pending"],(function(mustache,$,ajax,str,notification,coreurl,config,storage,IconSystem,filterEvents,Y,Log,Truncate,UserDate,Pending){var uniqInstances=0,templateCache={},templatePromises={},cachePartialPromises={},iconSystem={},loadTemplateBuffer=[],isLoadingTemplates=!1,disallowedNestedHelpers=["js"],getNormalisedComponent=function(component){return component&&"moodle"!==component&&"core"!==component?component:"core"},getTemplatePromiseFromCache=function(searchKey){if(searchKey in templatePromises)return templatePromises[searchKey];if(searchKey in templateCache)return templatePromises[searchKey]=$.Deferred().resolve(templateCache[searchKey]).promise(),templatePromises[searchKey];if(M.cfg.templaterev<=0)return null;var cached=storage.get("core_template/"+M.cfg.templaterev+":"+searchKey);return cached?(templateCache[searchKey]=cached,templatePromises[searchKey]=$.Deferred().resolve(cached).promise(),templatePromises[searchKey]):null},processLoadTemplateBuffer=function(){if(loadTemplateBuffer.length&&!isLoadingTemplates){isLoadingTemplates=!0;var templatesToLoad=loadTemplateBuffer.slice(),serverRequestsDeferred=$.Deferred(),requests=[],templatePromises=templatesToLoad.map((function(templateData){var component=getNormalisedComponent(templateData.component),name=templateData.name,searchKey=templateData.searchKey,theme=templateData.theme,templateDeferred=templateData.deferred,promise=null,cachedPromise=getTemplatePromiseFromCache(searchKey);if(cachedPromise)promise=cachedPromise;else{requests.push({methodname:"core_output_load_template_with_dependencies",args:{component:component,template:name,themename:theme,lang:config.language}});var index=requests.length-1;promise=serverRequestsDeferred.promise().then((function(promises){return templatePromises[searchKey]=promises[index].then((function(response){var templateSource=null;return response.templates.forEach((function(data){data.component=getNormalisedComponent(data.component);var tempSearchKey=[theme,data.component,data.name].join("/");templateCache[tempSearchKey]=data.value,M.cfg.templaterev>0&&storage.set("core_template/"+M.cfg.templaterev+":"+tempSearchKey,data.value),data.component==component&&data.name==name&&(templateSource=data.value)})),response.strings.length&&str.cache_strings(response.strings.map((function(data){return{component:getNormalisedComponent(data.component),key:data.name,value:data.value}}))),templateSource})),templatePromises[searchKey]}))}return promise.then((function(source){return templateDeferred.resolve(source)})).catch((function(error){throw templateDeferred.reject(error),error}))}));requests.length?serverRequestsDeferred.resolve(ajax.call(requests,!0,!1,!1,0,M.cfg.templaterev)):serverRequestsDeferred.resolve(),$.when.apply(null,templatePromises).then((function(){loadTemplateBuffer.splice(0,templatesToLoad.length),isLoadingTemplates=!1,processLoadTemplateBuffer()})).catch((function(){loadTemplateBuffer.splice(0,templatesToLoad.length),isLoadingTemplates=!1,processLoadTemplateBuffer()}))}},Renderer=function(){this.requiredStrings=[],this.requiredJS=[],this.requiredDates=[],this.currentThemeName=""};Renderer.prototype.requiredStrings=null,Renderer.prototype.requiredDates=[],Renderer.prototype.requiredJS=null,Renderer.prototype.currentThemeName="",Renderer.prototype.getTemplate=function(templateName){var currentTheme=this.currentThemeName,searchKey=currentTheme+"/"+templateName,cachedPromise=getTemplatePromiseFromCache(searchKey);if(cachedPromise)return cachedPromise;var existingBufferRecords=loadTemplateBuffer.filter((function(record){return record.searchKey==searchKey}));if(existingBufferRecords.length)return existingBufferRecords[0].deferred.promise();var parts=templateName.split("/"),component=getNormalisedComponent(parts.shift()),name=parts.join("/"),deferred=$.Deferred();return loadTemplateBuffer.push({component:component,name:name,theme:currentTheme,searchKey:searchKey,deferred:deferred}),processLoadTemplateBuffer(),deferred.promise()},Renderer.prototype.prefetchTemplates=function(templateNames,currentTheme){templateNames.forEach((function(templateName){var searchKey=currentTheme+"/"+templateName;if(!getTemplatePromiseFromCache(searchKey)&&!loadTemplateBuffer.filter((function(record){return record.searchKey==searchKey})).length){var parts=templateName.split("/"),component=getNormalisedComponent(parts.shift()),name=parts.join("/");loadTemplateBuffer.push({component:component,name:name,theme:currentTheme,searchKey:searchKey,deferred:$.Deferred()})}})),processLoadTemplateBuffer()},Renderer.prototype.partialHelper=function(name){var searchKey=this.currentThemeName+"/"+name;return searchKey in templateCache||notification.exception(new Error("Failed to pre-fetch the template: "+name)),templateCache[searchKey]},Renderer.prototype.renderIcon=function(key,component,title){var modulename=config.iconsystemmodule;component=getNormalisedComponent(component);var ready=$.Deferred();return require([modulename],(function(System){var system=new System;system instanceof IconSystem?(iconSystem=system,system.init().then(ready.resolve).catch(notification.exception)):ready.reject("Invalid icon system specified"+config.iconsystemmodule)})),ready.then(function(iconSystem){return this.getTemplate(iconSystem.getTemplateName())}.bind(this)).then((function(template){return iconSystem.renderIcon(key,component,title,template)}))},Renderer.prototype.pixHelper=function(context,sectionText,helper){var parts=sectionText.split(","),key="",component="",text="";parts.length>0&&(key=helper(parts.shift().trim(),context)),parts.length>0&&(component=helper(parts.shift().trim(),context)),parts.length>0&&(text=helper(parts.join(",").trim(),context));var templateName=iconSystem.getTemplateName(),searchKey=this.currentThemeName+"/"+templateName,template=templateCache[searchKey];return component=getNormalisedComponent(component),key=key.replace(///gi,"/"),iconSystem.renderIcon(key,component,text,template)},Renderer.prototype.jsHelper=function(context,sectionText,helper){return this.requiredJS.push(helper(sectionText,context)),""},Renderer.prototype.stringHelper=function(context,sectionText,helper){var parts=sectionText.split(","),key="",component="",param="";if(parts.length>0&&(key=parts.shift().trim()),parts.length>0&&(component=parts.shift().trim()),parts.length>0&&(param=parts.join(",").trim()),component=getNormalisedComponent(component),""!==param&&(param=helper(param,context)),param.match(/^{\s*"/gm))try{const parsedParam=JSON.parse(param);parsedParam&&"object"==typeof parsedParam&&(param=parsedParam)}catch(err){window.console.warn(err.message)}var index=this.requiredStrings.length;return this.requiredStrings.push({key:key,component:component,param:param}),"[[_s"+index+"]]"},Renderer.prototype.cleanStringHelper=function(context,sectionText,helper){return this.stringHelper(context,sectionText,helper).replace("s","c")},Renderer.prototype.quoteHelper=function(context,sectionText,helper){var content=helper(sectionText.trim(),context);return content=(content=JSON.stringify(content)).replace(/([{}]{2,3})/g,"{{=<% %>=}}$1<%={{ }}=%>")},Renderer.prototype.shortenTextHelper=function(context,sectionText,helper){var parts=sectionText.match(/(.*?),(.*)/),length=parts[1].trim(),content=helper(parts[2].trim(),context);return Truncate.truncate(content,{length:length,words:!0,ellipsis:"..."})},Renderer.prototype.userDateHelper=function(context,sectionText,helper){var parts=sectionText.match(/(.*?),(.*)/),timestamp=helper(parts[1].trim(),context),format=helper(parts[2].trim(),context),index=this.requiredDates.length;return this.requiredDates.push({timestamp:timestamp,format:format}),"[[_t_"+index+"]]"},Renderer.prototype.addHelperFunction=function(helperFunction,context){return function(){return function(sectionText,helper){var originalHelpers=disallowedNestedHelpers.reduce((function(carry,name){return context.hasOwnProperty(name)&&(carry[name]=context[name]),carry}),{});disallowedNestedHelpers.forEach((function(helperName){context[helperName]=function(){return""}}));var result=helperFunction.apply(this,[context,sectionText,helper]);for(var name in originalHelpers)context[name]=originalHelpers[name];return result}.bind(this)}.bind(this)},Renderer.prototype.addHelpers=function(context,themeName){this.currentThemeName=themeName,this.requiredStrings=[],this.requiredJS=[],context.uniqid=uniqInstances++,context.str=this.addHelperFunction(this.stringHelper,context),context.cleanstr=this.addHelperFunction(this.cleanStringHelper,context),context.pix=this.addHelperFunction(this.pixHelper,context),context.js=this.addHelperFunction(this.jsHelper,context),context.quote=this.addHelperFunction(this.quoteHelper,context),context.shortentext=this.addHelperFunction(this.shortenTextHelper,context),context.userdate=this.addHelperFunction(this.userDateHelper,context),context.globals={config:config},context.currentTheme=themeName},Renderer.prototype.getJS=function(){var js="";return this.requiredJS.length>0&&(js=this.requiredJS.join(";\n")),js},Renderer.prototype.treatStringsInContent=function(content,strings){var treated,index,strIndex,walker,char,strFinal,isClean,pattern=/\[\[_(s|c)\d+\]\]/;do{for(treated="",index=content.search(pattern);index>-1;){treated+=content.substring(0,index),isClean="c"==(content=content.substr(index))[3],strIndex="",walker=4,char=content.substr(walker,1);do{strIndex+=char,walker++,char=content.substr(walker,1)}while("]"!=char);void 0===(strFinal=strings[parseInt(strIndex,10)])&&(Log.debug("Could not find string for pattern [[_"+(isClean?"c":"s")+strIndex+"]]."),strFinal=""),isClean&&(strFinal=mustache.escape(strFinal)),treated+=strFinal,index=(content=content.substr(6+strIndex.length)).search(pattern)}index=(content=treated+content).search(pattern)}while(index>-1);return content},Renderer.prototype.treatDatesInContent=function(content,dates){return dates.forEach((function(date,index){var re=new RegExp("\\[\\[_t_"+index+"\\]\\]","g");content=content.replace(re,date)})),content},Renderer.prototype.doRender=function(templateSource,context,themeName){this.currentThemeName=themeName;var iconTemplate=iconSystem.getTemplateName(),pendingPromise=new Pending("core/templates:doRender");return this.getTemplate(iconTemplate).then(function(){this.addHelpers(context,themeName);var result=mustache.render(templateSource,context,this.partialHelper.bind(this));return $.Deferred().resolve(result.trim(),this.getJS()).promise()}.bind(this)).then(function(html,js){return this.requiredStrings.length>0?str.get_strings(this.requiredStrings).then(function(strings){return this.requiredDates=this.requiredDates.map(function(date){return{timestamp:this.treatStringsInContent(date.timestamp,strings),format:this.treatStringsInContent(date.format,strings)}}.bind(this)),html=this.treatStringsInContent(html,strings),js=this.treatStringsInContent(js,strings),$.Deferred().resolve(html,js).promise()}.bind(this)):$.Deferred().resolve(html,js).promise()}.bind(this)).then(function(html,js){return this.requiredDates.length>0?UserDate.get(this.requiredDates).then(function(dates){return html=this.treatDatesInContent(html,dates),js=this.treatDatesInContent(js,dates),$.Deferred().resolve(html,js).promise()}.bind(this)):$.Deferred().resolve(html,js).promise()}.bind(this)).then((function(html,js){return pendingPromise.resolve(),$.Deferred().resolve(html,js).promise()}))};var runTemplateJS=function(source){if(""!==source.trim()){var newscript=$("