define("core/adapter",[],(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){var n=t[o][1][e];return s(n||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});module.exports=adapter},{"./adapter_factory.js":2}],2:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=function(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings,sdp:sdp};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter};var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim")),sdp=_interopRequireWildcard(require("sdp"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}},{"./chrome/chrome_shim":3,"./common_shim":6,"./firefox/firefox_shim":7,"./safari/safari_shim":10,"./utils":11,sdp:12}],3:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=function(window){window.MediaStream=window.MediaStream||window.webkitMediaStream},exports.shimOnTrack=function(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",(function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===te.track.id})):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})),e.stream.getTracks().forEach((function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===track.id})):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}))},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},exports.shimGetSendersWithDtmf=function(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach((function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))}))};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach((function(track){var sender=_this3._senders.find((function(s){return s.track===track}));sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)}))}}else if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this4})),senders},Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},exports.shimGetStats=function(window){if(!window.RTCPeerConnection)return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach((function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach((function(name){standardStats[name]=report.stat(name)})),standardReport[standardStats.id]=standardStats})),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map((function(key){return[key,stats[key]]})))};if(arguments.length>=2){var successCallbackWrapper_=function(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise((function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])})).then(onSucc,onErr)}},exports.shimSenderReceiverGetStats=function(window){if(!("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver))return;if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this6})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function(){var sender=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,sender.track,!0)}))}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this7})),receivers}),utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){var receiver=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,receiver.track,!1)}))}}if(!("getStats"in window.RTCRtpSender.prototype)||!("getStats"in window.RTCRtpReceiver.prototype))return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach((function(s){s.track===track&&(sender?err=!0:sender=s)})),this.getReceivers().forEach((function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track})),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}},exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=function(window,browserDetails){if(!window.RTCPeerConnection)return;if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map((function(stream){return _this11._reverseStreams[stream.id]}))};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach((function(track){if(_this12.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}window.RTCPeerConnection.prototype.removeStream=function(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find((function(t){return t===track})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var alreadyExists=this.getSenders().find((function(s){return s.track===track}));if(alreadyExists)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then((function(){_this13.dispatchEvent(new Event("negotiationneeded"))}));else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find((function(s){return s.track===track}))},["createOffer","createAnswer"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then((function(description){return replaceInternalStreamId(_this14,description)}))}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(sender._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach((function(streamid){_this15._streams[streamid].getTracks().find((function(track){return sender.track===track}))&&(stream=_this15._streams[streamid])})),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}},exports.shimPeerConnection=function(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection);if(!window.RTCPeerConnection)return;browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}))},exports.fixNegotiationNeeded=function(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",(function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js"));function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(streamId){return _this8._shimmedLocalStreams[streamId][0]}))};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach((function(track){if(_this9.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")}));var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter((function(newSender){return-1===existingSenders.indexOf(newSender)}));this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach((function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]})),origRemoveTrack.apply(this,arguments)}}},{"../utils.js":11,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,getSourceId){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;if("function"!=typeof getSourceId)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");window.navigator.mediaDevices.getDisplayMedia=function(constraints){return getSourceId(constraints).then((function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)}))}}},{}],5:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator;if(!navigator.mediaDevices)return;var constraintsToChrome_=function(c){if("object"!==(void 0===c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach((function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach((function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])}))}})),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===(void 0===face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then((function(devices){var dev=(devices=devices.filter((function(d){return"videoinput"===d.kind}))).find((function(d){return matches.some((function(match){return d.label.toLowerCase().includes(match)}))}));return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)}))}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(navigator.getUserMedia=function(constraints,onSuccess,onError){shimConstraints_(constraints,(function(c){navigator.webkitGetUserMedia(c,onSuccess,(function(e){onError&&onError(shimError_(e))}))}))}.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,(function(c){return origGetUserMedia(c).then((function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach((function(track){track.stop()})),new DOMException("","NotFoundError");return stream}),(function(e){return Promise.reject(shimError_(e))}))}))}}};var logging=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js")).log},{"../utils.js":11}],6:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimRTCIceCandidate=function(window){if(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)return;var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function(args){if("object"===(void 0===args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",(function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e}))},exports.shimMaxMessageSize=function(window,browserDetails){if(!window.RTCPeerConnection)return;"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some((function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76){var _getConfiguration=this.getConfiguration(),sdpSemantics=_getConfiguration.sdpSemantics;"plan-b"===sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}},exports.shimSendThrowTypeError=function(window){if(!window.RTCPeerConnection||!("createDataChannel"in window.RTCPeerConnection.prototype))return;function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",(function(e){return wrapDcSend(e.channel,e.target),e}))},exports.shimConnectionState=function(window){if(!window.RTCPeerConnection||"connectionState"in window.RTCPeerConnection.prototype)return;var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}}))},exports.removeExtmapAllowMixed=function(window,browserDetails){if(!window.RTCPeerConnection)return;if("chrome"===browserDetails.browser&&browserDetails.version>=71)return;if("safari"===browserDetails.browser&&browserDetails.version>=605)return;var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter((function(line){return"a=extmap-allow-mixed"!==line.trim()})).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}},exports.shimAddIceCandidateNullOrEmpty=function(window,browserDetails){if(!window.RTCPeerConnection||!window.RTCPeerConnection.prototype)return;var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;if(!nativeAddIceCandidate||0===nativeAddIceCandidate.length)return;window.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}};var obj,_sdp=require("sdp"),_sdp2=(obj=_sdp)&&obj.__esModule?obj:{default:obj},utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./utils"))},{"./utils":11,sdp:12}],7:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=function(window){"object"===(void 0===window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimPeerConnection=function(window,browserDetails){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection&&!window.mozRTCPeerConnection)return;!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection);browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then((function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach((function(stat){stat.type=modernStatsTypes[stat.type]||stat.type}))}catch(e){if("TypeError"!==e.name)throw e;stats.forEach((function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))}))}return stats})).then(onSucc,onErr)}},exports.shimSenderGetStats=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpSender.prototype)return;var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender});window.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}},exports.shimReceiverGetStats=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpReceiver.prototype)return;var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this2})),receivers});utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},exports.shimRemoveStream=function(window){if(!window.RTCPeerConnection||"removeStream"in window.RTCPeerConnection.prototype)return;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)}))}},exports.shimRTCDataChannel=function(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)},exports.shimAddTransceiver=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach((function(encodingParam){if("rid"in encodingParam){if(!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then((function(){delete sender.sendEncodings})).catch((function(){delete sender.sendEncodings}))))}return transceiver})},exports.shimGetParameters=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCRtpSender)return;var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})},exports.shimCreateOffer=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateOffer.apply(_this4,_arguments2)})).finally((function(){_this4.setParametersPromises=[]})):origCreateOffer.apply(this,arguments)}},exports.shimCreateAnswer=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateAnswer.apply(_this5,_arguments3)})).finally((function(){_this5.setParametersPromises=[]})):origCreateAnswer.apply(this,arguments)}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":11,"./getdisplaymedia":8,"./getusermedia":9}],8:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,preferredMediaSource){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=function(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)}}},{}],9:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===(void 0===c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===(void 0===c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":11}],10:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimLocalStreamsAPI=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach((function(track){return _addTrack.call(_this,track,stream)})),stream.getVideoTracks().forEach((function(track){return _addTrack.call(_this,track,stream)}))},window.RTCPeerConnection.prototype.addTrack=function(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach((function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]})),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach((function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)}))}})},exports.shimRemoteStreamsAPI=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}}))})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}}))}),origSetRemoteDescription.apply(pc,arguments)}}},exports.shimCallbacksAPI=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback},exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))},exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=function(window){if(!window.RTCPeerConnection)return;var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return OrigPeerConnection.generateCertificate}})},exports.shimTrackEventTransceiver=function(window){"object"===(void 0===window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimCreateOfferLegacy=function(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(offerOptions){if(offerOptions){void 0!==offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find((function(transceiver){return"audio"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),void 0!==offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find((function(transceiver){return"video"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}},exports.shimAudioContext=function(window){if("object"!==(void 0===window?"undefined":_typeof(window))||window.AudioContext)return;window.AudioContext=window.webkitAudioContext};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"));function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}},{"../utils":11}],11:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=function(window,eventNameToWrap,wrapper){if(!window.RTCPeerConnection)return;var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function(){return this["_on"+eventNameToWrap]},set:function(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})},exports.disableLog=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean.");return logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled"},exports.disableWarnings=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean.");return deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled")},exports.log=function(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},exports.deprecated=function(oldMethod,newMethod){if(!deprecationWarnings_)return;console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")},exports.detectBrowser=function(window){var result={browser:null,version:null};if(void 0===window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result},exports.compactObject=function compactObject(data){if(!isObject(data))return data;return Object.keys(data).reduce((function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},key,value))}),{})},exports.walkStats=walkStats,exports.filterStats=function(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach((function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)})),trackStats.forEach((function(trackStat){result.forEach((function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)}))})),filteredResult};var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach((function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach((function(id){walkStats(stats,stats.get(id),resultSet)}))})))}},{}],12:[function(require,module,exports){var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map((function(line){return line.trim()}))},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map((function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"}))},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&§ions[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter((function(line){return 0===line.indexOf(prefix)}))},SDPUtils.parseCandidate=function(line){for(var parts=void 0,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[parts[1]],protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:void 0===candidate[parts[i]]&&(candidate[parts[i]]=parts[i+1])}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation);var component=candidate.component;"rtp"===component?sdp.push(1):"rtcp"===component?sdp.push(2):sdp.push(component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var parsed={},kv=void 0,parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach((function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)})),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach((function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"})),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map((function(ssrc){return parseInt(ssrc,10)}))}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach((function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"})),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"===_typeof(parameters.keyParams)?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){var sdp="a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n";return params.iceLite&&(sdp+="a=ice-lite\r\n"),sdp},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach((function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))})),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map((function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType})).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach((function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)}));var maxptime=0;return caps.codecs.forEach((function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)})),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),caps.headerExtensions&&caps.headerExtensions.forEach((function(extension){sdp+=SDPUtils.writeExtmap(extension)})),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(parts){return"cname"===parts.attribute})),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,secondarySsrc=void 0,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map((function(line){return line.substr(17).split(" ").map((function(part){return parseInt(part,10)}))}));flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach((function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}})),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach((function(params){params.maxBitrate=bandwidth}))),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(obj){return"cname"===obj.attribute}))[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.writeRtcpParameters=function(rtcpParameters){var sdp="";return rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n"),rtcpParameters.mux&&(sdp+="a=rtcp-mux\r\n"),void 0!==rtcpParameters.ssrc&&rtcpParameters.cname&&(sdp+="a=ssrc:"+rtcpParameters.ssrc+" cname:"+rtcpParameters.cname+"\r\n"),sdp},SDPUtils.parseMsid=function(mediaSection){var parts=void 0,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(msidParts){return"msid"===msidParts.attribute}));return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:"),maxMessageSize=void 0;maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};var sctpMapLines=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:");if(sctpMapLines.length>0){var parts=sctpMapLines[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"===(void 0===module?"undefined":_typeof(module))&&(module.exports=SDPUtils)},{}]},{},[1])(1)})); /** * 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 <damyon@moodle.com> * @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(;i<this.length;i++)(request=this[i]).deferred.reject(responses);else{for(i=0;i<this.length;i++){if(request=this[i],void 0===(response=responses[i])){exception=new Error("missing response");break}if(!1!==response.error){exception=response.exception,nosessionupdate=this[i].nosessionupdate;break}request.deferred.resolve(response.data)}null!==exception&&("servicerequireslogin"!==exception.errorcode||nosessionupdate?this.forEach((function(request){request.deferred.reject(exception)})):window.location=URL.relativeUrl("/login/index.php"))}},requestFail=function(jqXHR,textStatus,exception){var i=0;for(i=0;i<this.length;i++){var request=this[i];unloading?(Log.error("Page unloaded."),Log.error(exception)):request.deferred.reject(exception)}};return{call:function(requests,async,loginrequired,nosessionupdate,timeout,cachekey){$(window).bind("beforeunload",(function(){unloading=!0}));var i,ajaxRequestData=[],promises=[],methodInfo=[],requestInfo="";for(void 0===loginrequired&&(loginrequired=!0),void 0===async&&(async=!0),void 0===timeout&&(timeout=0),void 0===cachekey||(cachekey=parseInt(cachekey))<=0?cachekey=null:cachekey||(cachekey=null),void 0===nosessionupdate&&(nosessionupdate=!1),i=0;i<requests.length;i++){var request=requests[i];ajaxRequestData.push({index:i,methodname:request.methodname,args:request.args}),request.nosessionupdate=nosessionupdate,request.deferred=$.Deferred(),promises.push(request.deferred.promise()),void 0!==request.done&&request.deferred.done(request.done),void 0!==request.fail&&request.deferred.fail(request.fail),request.index=i,methodInfo.push(request.methodname)}requestInfo=methodInfo.length<=5?methodInfo.sort().join():methodInfo.length+"-method-calls",ajaxRequestData=JSON.stringify(ajaxRequestData);var settings={type:"POST",context:requests,dataType:"json",processData:!1,async:async,contentType:"application/json",timeout:timeout},script="service.php",url=config.wwwroot+"/lib/ajax/";if(loginrequired?url+=script+"?sesskey="+config.sesskey+"&info="+requestInfo:(url+=(script="service-nologin.php")+"?info="+requestInfo,cachekey&&(url+="&cachekey="+cachekey,settings.type="GET")),nosessionupdate&&(url+="&nosessionupdate=true"),"POST"===settings.type)settings.data=ajaxRequestData;else{var urlUseGet=url+"&args="+encodeURIComponent(ajaxRequestData);urlUseGet.length>2e3?(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}}})); define("core/aria",["exports","./local/aria/aria-hidden"],(function(_exports,_ariaHidden){Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"hide",{enumerable:!0,get:function(){return _ariaHidden.hide}}),Object.defineProperty(_exports,"hideSiblings",{enumerable:!0,get:function(){return _ariaHidden.hideSiblings}}),Object.defineProperty(_exports,"unhide",{enumerable:!0,get:function(){return _ariaHidden.unhide}}),Object.defineProperty(_exports,"unhideSiblings",{enumerable:!0,get:function(){return _ariaHidden.unhideSiblings}})})); /** * Enhance a textarea with auto growing rows to fit the content. * * @module core/auto_rows * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("core/auto_rows",["jquery"],(function($){var SELECTORS_ELEMENT="[data-auto-rows]",EVENTS={ROW_CHANGE:"autorows:rowchange"},changeListener=function(e){var element=$(e.target),minRows=element.data("min-rows"),currentRows=element.attr("rows");void 0===minRows&&element.data("min-rows",currentRows),element.attr("rows",1);var rows=function(element){var currentRows=element.attr("rows"),minRows=element.data("min-rows"),maxRows=element.attr("data-max-rows"),height=element.height(),padding=element.innerHeight()-height,rows=(element[0].scrollHeight-padding)/(height/currentRows);return element.css("height",""),rows<minRows?minRows:maxRows&&rows>=maxRows?maxRows:rows}(element);element.attr("rows",rows),rows!=currentRows&&element.trigger(EVENTS.ROW_CHANGE)};return{init:function(root){$(root).data("auto-rows")?$(root).on("input propertychange",changeListener.bind(this)):$(root).on("input propertychange",SELECTORS_ELEMENT,changeListener.bind(this))},events:EVENTS}})); /* * JavaScript to provide automatic scrolling, e.g. during a drag operation. * * Note: this module is defined statically. It is a singleton. You * can only have one use of it active at any time. However, since this * is usually used in relation to drag-drop, and since you only ever * drag one thing at a time, this is not a problem in practice. * * @module core/autoscroll * @copyright 2016 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("core/autoscroll",["jquery"],(function($){var autoscroll={SCROLL_THRESHOLD:30,SCROLL_FREQUENCY:1e3/60,SCROLL_SPEED:.5,scrollingId:null,scrollAmount:0,callback:null,start:function(callback){$(window).on("mousemove",autoscroll.mouseMove),$(window).on("touchmove",autoscroll.touchMove),autoscroll.callback=callback},stop:function(){$(window).off("mousemove",autoscroll.mouseMove),$(window).off("touchmove",autoscroll.touchMove),null!==autoscroll.scrollingId&&autoscroll.stopScrolling()},touchMove:function(e){for(var i=0;i<e.changedTouches.length;i++)autoscroll.handleMove(e.changedTouches[i].clientX,e.changedTouches[i].clientY)},mouseMove:function(e){autoscroll.handleMove(e.clientX,e.clientY)},handleMove:function(clientX,clientY){clientY<autoscroll.SCROLL_THRESHOLD?autoscroll.scrollAmount=-Math.min(autoscroll.SCROLL_THRESHOLD-clientY,autoscroll.SCROLL_THRESHOLD):clientY>$(window).height()-autoscroll.SCROLL_THRESHOLD?autoscroll.scrollAmount=Math.min(clientY-($(window).height()-autoscroll.SCROLL_THRESHOLD),autoscroll.SCROLL_THRESHOLD):autoscroll.scrollAmount=0,autoscroll.scrollAmount&&null===autoscroll.scrollingId?autoscroll.startScrolling():autoscroll.scrollAmount||null===autoscroll.scrollingId||autoscroll.stopScrolling()},startScrolling:function(){var maxScroll=$(document).height()-$(window).height();autoscroll.scrollingId=window.setInterval((function(){var y=$(window).scrollTop(),offset=Math.round(autoscroll.scrollAmount*autoscroll.SCROLL_SPEED);if(y+offset<0&&(offset=-y),y+offset>maxScroll&&(offset=maxScroll-y),0!==offset){$(window).scrollTop(y+offset);var realOffset=$(window).scrollTop()-y;0!==realOffset&&autoscroll.callback&&autoscroll.callback(realOffset)}}),autoscroll.SCROLL_FREQUENCY)},stopScrolling:function(){window.clearInterval(autoscroll.scrollingId),autoscroll.scrollingId=null}};return{start:autoscroll.start,stop:autoscroll.stop}})); /** * A timer that will execute a callback with decreasing frequency. Useful for * doing polling on the server without overwhelming it with requests. * * @module core/backoff_timer * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/backoff_timer",(function(){var BackoffTimer=function(callback,backoffFunction){this.callback=callback,this.backOffFunction=backoffFunction};return BackoffTimer.prototype.callback=null,BackoffTimer.prototype.backOffFunction=null,BackoffTimer.prototype.time=null,BackoffTimer.prototype.timeout=null,BackoffTimer.prototype.generateNextTime=function(){var newTime=this.backOffFunction(this.time);return this.time=newTime,newTime},BackoffTimer.prototype.reset=function(){return this.time=null,this.stop(),this},BackoffTimer.prototype.stop=function(){return this.timeout&&(window.clearTimeout(this.timeout),this.timeout=null),this},BackoffTimer.prototype.start=function(){if(!this.timeout){var time=this.generateNextTime();this.timeout=window.setTimeout(function(){this.callback(),this.stop(),this.start()}.bind(this),time)}return this},BackoffTimer.prototype.restart=function(){return this.reset().start()},BackoffTimer.getIncrementalCallback=function(minamount,incrementamount,maxamount,timeoutamount){return function(time){return time?time+incrementamount>maxamount?timeoutamount:time+incrementamount:minamount}},BackoffTimer})); /** * Chart axis. * * @module core/chart_axis * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/chart_axis",[],(function(){function Axis(){}return Axis.prototype.POS_DEFAULT=null,Axis.prototype.POS_BOTTOM="bottom",Axis.prototype.POS_LEFT="left",Axis.prototype.POS_RIGHT="right",Axis.prototype.POS_TOP="top",Axis.prototype._label=null,Axis.prototype._labels=null,Axis.prototype._max=null,Axis.prototype._min=null,Axis.prototype._position=null,Axis.prototype._stepSize=null,Axis.prototype.create=function(obj){var s=new Axis;return s.setPosition(obj.position),s.setLabel(obj.label),s.setStepSize(obj.stepSize),s.setMax(obj.max),s.setMin(obj.min),s.setLabels(obj.labels),s},Axis.prototype.getLabel=function(){return this._label},Axis.prototype.getLabels=function(){return this._labels},Axis.prototype.getMax=function(){return this._max},Axis.prototype.getMin=function(){return this._min},Axis.prototype.getPosition=function(){return this._position},Axis.prototype.getStepSize=function(){return this._stepSize},Axis.prototype.setLabel=function(label){this._label=label||null},Axis.prototype.setLabels=function(labels){this._labels=labels||null,null===this._labels||null!==this._stepSize||null!==this._min&&0!==this._min||null!==this._max||(this.setStepSize(1),this.setMin(0),this.setMax(labels.length-1))},Axis.prototype.setMax=function(max){this._max=void 0!==max?max:null},Axis.prototype.setMin=function(min){this._min=void 0!==min?min:null},Axis.prototype.setPosition=function(position){if(position!=this.POS_DEFAULT&&position!=this.POS_BOTTOM&&position!=this.POS_LEFT&&position!=this.POS_RIGHT&&position!=this.POS_TOP)throw new Error("Invalid axis position.");this._position=position},Axis.prototype.setStepSize=function(stepSize){if(null==stepSize)stepSize=null;else{if(isNaN(Number(stepSize)))throw new Error("Value for stepSize is not a number.");stepSize=Number(stepSize)}this._stepSize=stepSize},Axis})); /** * Chart bar. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_bar */ define("core/chart_bar",["core/chart_base"],(function(Base){function Bar(){Base.prototype.constructor.apply(this,arguments)}return Bar.prototype=Object.create(Base.prototype),Bar.prototype._horizontal=!1,Bar.prototype._stacked=!1,Bar.prototype.TYPE="bar",Bar.prototype.create=function(Klass,data){var chart=Base.prototype.create.apply(this,arguments);return chart.setHorizontal(data.horizontal),chart.setStacked(data.stacked),chart},Bar.prototype._setDefaults=function(){Base.prototype._setDefaults.apply(this,arguments);var axis=this.getYAxis(0,!0);axis.setMin(0)},Bar.prototype.getHorizontal=function(){return this._horizontal},Bar.prototype.getStacked=function(){return this._stacked},Bar.prototype.setHorizontal=function(horizontal){var axis=this.getXAxis(0,!0);null===axis.getMin()&&axis.setMin(0),this._horizontal=Boolean(horizontal)},Bar.prototype.setStacked=function(stacked){this._stacked=Boolean(stacked)},Bar})); /** * Chart base. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_base */ define("core/chart_base",["core/chart_series","core/chart_axis"],(function(Series,Axis){function Base(){this._series=[],this._labels=[],this._xaxes=[],this._yaxes=[],this._setDefaults()}return Base.prototype._series=null,Base.prototype._labels=null,Base.prototype._legendOptions=null,Base.prototype._title=null,Base.prototype._xaxes=null,Base.prototype._yaxes=null,Base.prototype.COLORSET=["#f3c300","#875692","#f38400","#a1caf1","#be0032","#c2b280","#7f180d","#008856","#e68fac","#0067a5"],Base.prototype._configColorSet=null,Base.prototype.TYPE=null,Base.prototype.addSeries=function(series){if(this._validateSeries(series),this._series.push(series),null===series.getColor()){var configColorSet=this.getConfigColorSet()||Base.prototype.COLORSET;series.setColor(configColorSet[this._series.length%configColorSet.length])}},Base.prototype.create=function(Klass,data){var Chart=new Klass;return Chart.setConfigColorSet(data.config_colorset),Chart.setLabels(data.labels),Chart.setTitle(data.title),data.legend_options&&Chart.setLegendOptions(data.legend_options),data.series.forEach((function(seriesData){Chart.addSeries(Series.prototype.create(seriesData))})),data.axes.x.forEach((function(axisData,i){Chart.setXAxis(Axis.prototype.create(axisData),i)})),data.axes.y.forEach((function(axisData,i){Chart.setYAxis(Axis.prototype.create(axisData),i)})),Chart},Base.prototype.__getAxis=function(xy,index,createIfNotExists){var axis,axes="x"===xy?this._xaxes:this._yaxes,setAxis=("x"===xy?this.setXAxis:this.setYAxis).bind(this);if(createIfNotExists=void 0!==createIfNotExists&&createIfNotExists,void 0===(axis=axes[index=void 0===index?0:index])){if(!createIfNotExists)throw new Error("Unknown axis.");setAxis(axis=new Axis,index)}return axis},Base.prototype.getConfigColorSet=function(){return this._configColorSet},Base.prototype.getLabels=function(){return this._labels},Base.prototype.getLegendOptions=function(){return this._legendOptions},Base.prototype.getSeries=function(){return this._series},Base.prototype.getTitle=function(){return this._title},Base.prototype.getType=function(){if(!this.TYPE)throw new Error("The TYPE property has not been set.");return this.TYPE},Base.prototype.getXAxes=function(){return this._xaxes},Base.prototype.getXAxis=function(index,createIfNotExists){return this.__getAxis("x",index,createIfNotExists)},Base.prototype.getYAxes=function(){return this._yaxes},Base.prototype.getYAxis=function(index,createIfNotExists){return this.__getAxis("y",index,createIfNotExists)},Base.prototype.setConfigColorSet=function(colorset){this._configColorSet=colorset},Base.prototype._setDefaults=function(){},Base.prototype.setLabels=function(labels){if(labels.length&&this._series.length&&this._series[0].length!=labels.length)throw new Error("Series must match label values.");this._labels=labels},Base.prototype.setLegendOptions=function(legendOptions){if("object"!=typeof legendOptions)throw new Error("Setting legend with non-object value:"+legendOptions);this._legendOptions=legendOptions},Base.prototype.setTitle=function(title){this._title=title},Base.prototype.setXAxis=function(axis,index){index=void 0===index?0:index,this._validateAxis("x",axis,index),this._xaxes[index]=axis},Base.prototype.setYAxis=function(axis,index){index=void 0===index?0:index,this._validateAxis("y",axis,index),this._yaxes[index]=axis},Base.prototype._validateAxis=function(xy,axis,index){if((index=void 0===index?0:index)>0&&void 0===("x"==xy?this._xaxes:this._yaxes)[index-1])throw new Error("Missing "+xy+" axis at index lower than "+index)},Base.prototype._validateSeries=function(series){if(this._series.length&&this._series[0].getCount()!=series.getCount())throw new Error("Series do not have an equal number of values.");if(this._labels.length&&this._labels.length!=series.getCount())throw new Error("Series must match label values.")},Base})); /** * Chart builder. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/chart_builder",["jquery"],(function($){return{make:function(data){var deferred=$.Deferred();return require(["core/chart_"+data.type],(function(Klass){var instance=Klass.prototype.create(Klass,data);deferred.resolve(instance)})),deferred.promise()}}})); /** * Chart line. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_line */ define("core/chart_line",["core/chart_base"],(function(Base){function Line(){Base.prototype.constructor.apply(this,arguments)}return Line.prototype=Object.create(Base.prototype),Line.prototype.TYPE="line",Line.prototype._smooth=!1,Line.prototype.create=function(Klass,data){var chart=Base.prototype.create.apply(this,arguments);return chart.setSmooth(data.smooth),chart},Line.prototype.getSmooth=function(){return this._smooth},Line.prototype.setSmooth=function(smooth){this._smooth=Boolean(smooth)},Line})); /** * Chart output. * * Proxy to the default output module. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/chart_output",["core/chart_output_chartjs"],(function(Output){return Output})); /** * Chart output base. * * This takes a chart object and draws it. * * @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_base */ define("core/chart_output_base",["jquery"],(function($){function Base(node,chart){this._node=$(node),this._chart=chart}return Base.prototype.update=function(){throw new Error("Not supported.")},Base})); /** * Chart output for chart.js. * * @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_chartjs */ define("core/chart_output_chartjs",["jquery","core/chartjs","core/chart_axis","core/chart_bar","core/chart_output_base","core/chart_line","core/chart_pie","core/chart_series"],(function($,Chartjs,Axis,Bar,Base,Line,Pie,Series){var makeAxisId=function(xy,index){return"axis-"+xy+"-"+index};function Output(){Base.prototype.constructor.apply(this,arguments),this._canvas=this._node,"CANVAS"!=this._canvas.prop("tagName")&&(this._canvas=$("<canvas>"),this._node.append(this._canvas)),this._build()}return Output.prototype=Object.create(Base.prototype),Output.prototype._config=null,Output.prototype._chartjs=null,Output.prototype._canvas=null,Output.prototype._build=function(){this._config=this._makeConfig(),this._chartjs=new Chartjs(this._canvas[0],this._config)},Output.prototype._cleanData=function(data){return data instanceof Array?data.map((function(value){return $("<span>").html(value).text()})):$("<span>").html(data).text()},Output.prototype._getChartType=function(){var type=this._chart.getType();return this._chart.getType()===Bar.prototype.TYPE&&!0===this._chart.getHorizontal()?type="horizontalBar":this._chart.getType()===Pie.prototype.TYPE&&!0===this._chart.getDoughnut()&&(type="doughnut"),type},Output.prototype._makeAxisConfig=function(axis,xy,index){var scaleData={id:makeAxisId(xy,index)};return axis.getPosition()!==Axis.prototype.POS_DEFAULT&&(scaleData.position=axis.getPosition()),null!==axis.getLabel()&&(scaleData.title={display:!0,text:this._cleanData(axis.getLabel())}),null!==axis.getStepSize()&&(scaleData.ticks=scaleData.ticks||{},scaleData.ticks.stepSize=axis.getStepSize()),null!==axis.getMax()&&(scaleData.ticks=scaleData.ticks||{},scaleData.ticks.max=axis.getMax()),null!==axis.getMin()&&(scaleData.ticks=scaleData.ticks||{},scaleData.ticks.min=axis.getMin()),scaleData},Output.prototype._makeConfig=function(){var charType=this._getChartType(),config={type:charType,data:{labels:this._cleanData(this._chart.getLabels()),datasets:this._makeDatasetsConfig()},options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:null!==this._chart.getTitle(),text:this._cleanData(this._chart.getTitle())}}}};"horizontalBar"===charType&&(config.type="bar",config.options.indexAxis="y");var legendOptions=this._chart.getLegendOptions();return legendOptions&&(config.options.plugins.legend=legendOptions),this._chart.getXAxes().forEach(function(axis,i){var axisLabels=axis.getLabels();config.options.scales=config.options.scales||{},config.options.scales.x=config.options.scales.x||{},config.options.scales.x[i]=this._makeAxisConfig(axis,"x",i),null!==axisLabels&&(config.options.scales.x[i].ticks.callback=function(value,index){return axisLabels[index]||""}),config.options.scales.x.stacked=this._isStacked()}.bind(this)),this._chart.getYAxes().forEach(function(axis,i){var axisLabels=axis.getLabels();config.options.scales=config.options.scales||{},config.options.scales.y=config.options.scales.yAxes||{},config.options.scales.y[i]=this._makeAxisConfig(axis,"y",i),null!==axisLabels&&(config.options.scales.y[i].ticks.callback=function(value){return axisLabels[parseInt(value,10)]||""}),config.options.scales.y.stacked=this._isStacked()}.bind(this)),config.options.plugins.tooltip={callbacks:{label:this._makeTooltip.bind(this)}},config},Output.prototype._makeDatasetsConfig=function(){return this._chart.getSeries().map(function(series){var colors=series.hasColoredValues()?series.getColors():series.getColor(),dataset={label:this._cleanData(series.getLabel()),data:series.getValues(),type:series.getType(),fill:series.getFill(),backgroundColor:colors,borderColor:this._chart.getType()==Pie.prototype.TYPE?"#fff":colors,tension:this._isSmooth(series)?.3:0};return null!==series.getXAxis()&&(dataset.xAxisID=makeAxisId("x",series.getXAxis())),null!==series.getYAxis()&&(dataset.yAxisID=makeAxisId("y",series.getYAxis())),dataset}.bind(this))},Output.prototype._makeTooltip=function(tooltipItem){var serieLabel=this._chart.getSeries()[tooltipItem.datasetIndex].getLabel(),tooltipData=tooltipItem.dataset.data[tooltipItem.dataIndex],tooltip=[];if(this._chart.getType()===Pie.prototype.TYPE){var chartLabels=this._cleanData(this._chart.getLabels());tooltip.push(chartLabels[tooltipItem.dataIndex]+" - "+this._cleanData(serieLabel)+": "+tooltipData)}else tooltip.push(this._cleanData(serieLabel)+": "+tooltipData);return tooltip},Output.prototype._isSmooth=function(series){var smooth=!1;return this._chart.getType()===Line.prototype.TYPE?null===(smooth=series.getSmooth())&&(smooth=this._chart.getSmooth()):series.getType()===Series.prototype.TYPE_LINE&&(smooth=series.getSmooth()),smooth},Output.prototype._isStacked=function(){var stacked=!1;return this._chart.getType()===Bar.prototype.TYPE&&(stacked=this._chart.getStacked()),stacked},Output.prototype.update=function(){$.extend(!0,this._config,this._makeConfig()),this._chartjs.update()},Output})); /** * 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=$("<table>"),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($("<caption>").text(c.getTitle())),node=$("<tr>"),hasLabel&&node.append($("<td>")),series.forEach((function(serie){node.append($("<th>").text(serie.getLabel()).attr("scope","col"))})),tbl.append(node);for(var rowId=0;rowId<rowCount;rowId++){node=$("<tr>"),labels.length>0&&node.append($("<th>").text(labels[rowId]).attr("scope","row"));for(var serieId=0;serieId<series.length;serieId++)value=series[serieId].getValues()[rowId],null!==series[serieId].getLabels()&&(value=series[serieId].getLabels()[rowId]),node.append($("<td>").text(value));tbl.append(node)}return tbl},Output.prototype.update=function(){this._build()},Output})); /** * 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<series.getCount();i++)colors.push(configColorSet[i%configColorSet.length]);series.setColors(colors)}return Base.prototype.addSeries.apply(this,arguments)},Pie.prototype.getDoughnut=function(){return this._doughnut},Pie.prototype.setDoughnut=function(doughnut){this._doughnut=Boolean(doughnut)},Pie.prototype._validateSeries=function(){if(this._series.length>=1)throw new Error("Pie charts only support one serie.");return Base.prototype._validateSeries.apply(this,arguments)},Pie})); /** * Chart series. * * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @module core/chart_series */ define("core/chart_series",[],(function(){function Series(label,values){if("string"!=typeof label)throw new Error("Invalid label for series.");if("object"!=typeof values)throw new Error("Values for a series must be an array.");if(values.length<1)throw new Error("Invalid values received for series.");this._colors=[],this._label=label,this._values=values}return Series.prototype.TYPE_DEFAULT=null,Series.prototype.TYPE_LINE="line",Series.prototype._colors=null,Series.prototype._fill=!1,Series.prototype._label=null,Series.prototype._labels=null,Series.prototype._smooth=!1,Series.prototype._type=Series.prototype.TYPE_DEFAULT,Series.prototype._values=null,Series.prototype._xaxis=null,Series.prototype._yaxis=null,Series.prototype.create=function(obj){var s=new Series(obj.label,obj.values);return s.setType(obj.type),s.setXAxis(obj.axes.x),s.setYAxis(obj.axes.y),s.setLabels(obj.labels),obj.colors&&obj.colors.length>1?s.setColors(obj.colors):s.setColor(obj.colors[0]),s.setFill(obj.fill),s.setSmooth(obj.smooth),s},Series.prototype.getColor=function(){return this._colors[0]||null},Series.prototype.getColors=function(){return this._colors},Series.prototype.getCount=function(){return this._values.length},Series.prototype.getFill=function(){return this._fill},Series.prototype.getLabel=function(){return this._label},Series.prototype.getLabels=function(){return this._labels},Series.prototype.getSmooth=function(){return this._smooth},Series.prototype.getType=function(){return this._type},Series.prototype.getValues=function(){return this._values},Series.prototype.getXAxis=function(){return this._xaxis},Series.prototype.getYAxis=function(){return this._yaxis},Series.prototype.hasColoredValues=function(){return this._colors.length==this.getCount()},Series.prototype.setColor=function(color){this._colors=[color]},Series.prototype.setColors=function(colors){if(colors&&colors.length!=this.getCount())throw new Error("When setting multiple colors there must be one per value.");this._colors=colors||[]},Series.prototype.setFill=function(fill){this._fill=void 0===fill?null:fill},Series.prototype.setLabels=function(labels){this._validateLabels(labels),labels=void 0===labels?null:labels,this._labels=labels},Series.prototype.setSmooth=function(smooth){smooth=void 0===smooth?null:smooth,this._smooth=smooth},Series.prototype.setType=function(type){if(type!=this.TYPE_DEFAULT&&type!=this.TYPE_LINE)throw new Error("Invalid serie type.");this._type=type||null},Series.prototype.setXAxis=function(index){this._xaxis=index||null},Series.prototype.setYAxis=function(index){this._yaxis=index||null},Series.prototype._validateLabels=function(labels){if(labels&&labels.length>0&&labels.length!=this.getCount())throw new Error("Series labels must match series values.")},Series})); /** * 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})); /** * A module to help with toggle select/deselect all. * * @module core/checkbox-toggleall * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/checkbox-toggleall",["jquery","core/pubsub"],(function($,PubSub){var registered=!1,events={checkboxToggled:"core/checkbox-toggleall:checkboxToggled"},getToggleGroupElements=function(root,toggleGroup,exactMatch){return exactMatch?root.find('[data-action="toggle"][data-togglegroup="'+toggleGroup+'"]'):root.find('[data-action="toggle"][data-togglegroup^="'+toggleGroup+'"]')},getAllSlaveCheckboxes=function(root,toggleGroup){return getToggleGroupElements(root,toggleGroup,!1).filter('[data-toggle="slave"]')},getControlCheckboxes=function(root,toggleGroup,exactMatch){return getToggleGroupElements(root,toggleGroup,exactMatch).filter('[data-toggle="master"]')},toggleSlavesFromMasters=function(e){var targetState,root=e.data.root,target=$(e.target),toggleGroupName=target.data("togglegroup");targetState=target.is(":checkbox")?target.is(":checked"):1===target.data("checkall"),toggleSlavesToState(root,toggleGroupName,targetState)},toggleMastersAndActionElements=function(root,toggleGroupName){var toggleGroupSlaves=getAllSlaveCheckboxes(root,toggleGroupName);if(toggleGroupSlaves.length>0){var toggleGroupCheckedSlaves=toggleGroupSlaves.filter(":checked"),targetState=toggleGroupSlaves.length===toggleGroupCheckedSlaves.length;setMasterStates(root,toggleGroupName,targetState,!0),setActionElementStates(root,toggleGroupName,!toggleGroupCheckedSlaves.length)}},getToggleGroupLevels=function(toggleGroupName){var toggleGroups=toggleGroupName.split(" "),toggleGroupLevels=[],toggleGroupLevel="";return toggleGroups.forEach((function(toggleGroupName){toggleGroupLevel+=" "+toggleGroupName,toggleGroupLevels.push(toggleGroupLevel.trim())})),toggleGroupLevels},toggleSlavesToState=function(root,toggleGroupName,targetState){var slaves=getAllSlaveCheckboxes(root,toggleGroupName);slaves.prop("checked",targetState).trigger("change");var checkedSlaves=slaves.filter(":checked");setMasterStates(root,toggleGroupName,targetState,!1),setActionElementStates(root,toggleGroupName,!checkedSlaves.length),getToggleGroupLevels(toggleGroupName).filter((toggleGroupLevel=>toggleGroupLevel!==toggleGroupName)).forEach((function(toggleGroupLevel){toggleMastersAndActionElements(root,toggleGroupLevel)})),PubSub.publish(events.checkboxToggled,{root:root,toggleGroupName:toggleGroupName,slaves:slaves,checkedSlaves:checkedSlaves,anyChecked:targetState})},toggleMastersFromSlaves=function(e){var root=e.data.root,toggleGroupName=$(e.target).data("togglegroup"),slaves=getAllSlaveCheckboxes(root,toggleGroupName),checkedSlaves=slaves.filter(":checked");getToggleGroupLevels(toggleGroupName).forEach((function(toggleGroupLevel){toggleMastersAndActionElements(root,toggleGroupLevel)})),PubSub.publish(events.checkboxToggled,{root:root,toggleGroupName:toggleGroupName,slaves:slaves,checkedSlaves:checkedSlaves,anyChecked:!!checkedSlaves.length})},setActionElementStates=function(root,toggleGroupName,disableActionElements){(function(root,toggleGroup){return getToggleGroupElements(root,toggleGroup,!0).filter('[data-toggle="action"]')})(root,toggleGroupName).prop("disabled",disableActionElements)},setMasterStates=function(root,toggleGroupName,targetState,exactMatch){var masters=getControlCheckboxes(root,toggleGroupName,exactMatch);masters.prop("checked",targetState),masters.each((function(i,masterElement){var targetString;if(masterElement=$(masterElement),targetString=targetState?masterElement.data("toggle-deselectall"):masterElement.data("toggle-selectall"),masterElement.is(":checkbox")){var masterLabel=root.find('[for="'+masterElement.attr("id")+'"]');masterLabel.length&&masterLabel.html()!==targetString&&masterLabel.html(targetString)}else masterElement.text(targetString),masterElement.data("checkall",targetState?0:1)}))};return{init:function(){!function(){if(!registered){registered=!0;var root=$(document.body);root.on("click",'[data-action="toggle"][data-toggle="master"]',{root:root},toggleSlavesFromMasters),root.on("click",'[data-action="toggle"][data-toggle="slave"]',{root:root},toggleMastersFromSlaves)}}()},events:events,setGroupState:function(root,toggleGroupName,targetState){root=$(root),setMasterStates(root,toggleGroupName,targetState,!0),toggleSlavesToState(root,toggleGroupName,targetState)},updateSlavesFromMasterState:function(root,toggleGroupName){root=$(root);var targetState,target=getControlCheckboxes(root,toggleGroupName,!1);targetState=target.is(":checkbox")?target.is(":checked"):1===target.data("checkall"),toggleSlavesToState(root,toggleGroupName,targetState)}}})); /** * This module provides a wrapper to encapsulate a lot of the common combinations of * user interaction we use in Moodle. * * @module core/custom_interaction_events * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("core/custom_interaction_events",["jquery","core/key_codes"],(function($,keyCodes){var events={activate:"cie:activate",keyboardActivate:"cie:keyboardactivate",escape:"cie:escape",down:"cie:down",up:"cie:up",home:"cie:home",end:"cie:end",next:"cie:next",previous:"cie:previous",asterix:"cie:asterix",scrollLock:"cie:scrollLock",scrollTop:"cie:scrollTop",scrollBottom:"cie:scrollBottom",ctrlPageUp:"cie:ctrlPageUp",ctrlPageDown:"cie:ctrlPageDown",enter:"cie:enter",accessibleChange:"cie:accessibleChange"},triggeredEvents={},isModifierPressed=function(e){return e.shiftKey||e.metaKey||e.altKey||e.ctrlKey},triggerEvent=function(eventName,e){var eventTypeKey="";return e.hasOwnProperty("originalEvent")?(eventTypeKey="triggeredCustom_"+eventName,e.originalEvent.hasOwnProperty(eventTypeKey)?void 0:(e.originalEvent[eventTypeKey]=!0,void $(e.target).trigger(eventName,[{originalEvent:e}]))):(eventTypeKey=""+eventName+e.type+e.timeStamp,void(triggeredEvents.hasOwnProperty(eventTypeKey)||(triggeredEvents[eventTypeKey]=!0,$(e.target).trigger(eventName,[{originalEvent:e}]))))},addKeyboardEvent=function(element,event,keyCode){element.off("keydown."+event).on("keydown."+event,(function(e){isModifierPressed(e)||e.keyCode==keyCode&&triggerEvent(event,e)}))},addActivateListener=function(element){element.off("click.cie.activate").on("click.cie.activate",(function(e){triggerEvent(events.activate,e)})),element.off("keydown.cie.activate").on("keydown.cie.activate",(function(e){isModifierPressed(e)||e.keyCode!=keyCodes.enter&&e.keyCode!=keyCodes.space||triggerEvent(events.activate,e)}))},addKeyboardActivateListener=function(element){element.off("keydown.cie.keyboardactivate").on("keydown.cie.keyboardactivate",(function(e){isModifierPressed(e)||e.keyCode!=keyCodes.enter&&e.keyCode!=keyCodes.space||triggerEvent(events.keyboardActivate,e)}))},addEscapeListener=function(element){addKeyboardEvent(element,events.escape,keyCodes.escape)},addDownListener=function(element){addKeyboardEvent(element,events.down,keyCodes.arrowDown)},addUpListener=function(element){addKeyboardEvent(element,events.up,keyCodes.arrowUp)},addHomeListener=function(element){addKeyboardEvent(element,events.home,keyCodes.home)},addEndListener=function(element){addKeyboardEvent(element,events.end,keyCodes.end)},addNextListener=function(element){var keyCode="rtl"==$("html").attr("dir")?keyCodes.arrowLeft:keyCodes.arrowRight;addKeyboardEvent(element,events.next,keyCode)},addPreviousListener=function(element){var keyCode="rtl"==$("html").attr("dir")?keyCodes.arrowRight:keyCodes.arrowLeft;addKeyboardEvent(element,events.previous,keyCode)},addAsterixListener=function(element){addKeyboardEvent(element,events.asterix,keyCodes.asterix)},addScrollTopListener=function(element){element.off("scroll.cie.scrollTop").on("scroll.cie.scrollTop",(function(e){0===element.scrollTop()&&triggerEvent(events.scrollTop,e)}))},addScrollBottomListener=function(element){element.off("scroll.cie.scrollBottom").on("scroll.cie.scrollBottom",(function(e){element.scrollTop()+element.innerHeight()>=element[0].scrollHeight&&triggerEvent(events.scrollBottom,e)}))},addScrollLockListener=function(element){element.off("DOMMouseScroll.cie.DOMMouseScrollLock mousewheel.cie.mousewheelLock").on("DOMMouseScroll.cie.DOMMouseScrollLock mousewheel.cie.mousewheelLock",(function(e){var scrollTop=element.scrollTop(),scrollHeight=element[0].scrollHeight,height=element.height(),delta="DOMMouseScroll"==e.type?-40*e.originalEvent.detail:e.originalEvent.wheelDelta,up=delta>0;return!up&&-delta>scrollHeight-height-scrollTop?(element.scrollTop(scrollHeight),e.stopPropagation(),e.preventDefault(),e.returnValue=!1,triggerEvent(events.scrollLock,e),!1):!(up&&delta>scrollTop)||(element.scrollTop(0),e.stopPropagation(),e.preventDefault(),e.returnValue=!1,triggerEvent(events.scrollLock,e),!1)}))},addCtrlPageUpListener=function(element){element.off("keydown.cie.ctrlpageup").on("keydown.cie.ctrlpageup",(function(e){e.ctrlKey&&e.keyCode==keyCodes.pageUp&&triggerEvent(events.ctrlPageUp,e)}))},addCtrlPageDownListener=function(element){element.off("keydown.cie.ctrlpagedown").on("keydown.cie.ctrlpagedown",(function(e){e.ctrlKey&&e.keyCode==keyCodes.pageDown&&triggerEvent(events.ctrlPageDown,e)}))},addEnterListener=function(element){addKeyboardEvent(element,events.enter,keyCodes.enter)},addAccessibleChangeListener=function(element){var onMac=-1!==navigator.userAgent.indexOf("Macintosh"),touchEnabled="ontouchstart"in window||"msMaxTouchPoints"in navigator&&navigator.msMaxTouchPoints>0;if(onMac||touchEnabled)element.on("change",(function(e){triggerEvent(events.accessibleChange,e)}));else{var checkAndTriggerAccessibleChange=function(e){"initValue"in e.target.dataset&&e.target.value!==e.target.dataset.initValue&&(e.target.dataset.initValue=e.target.value,triggerEvent(events.accessibleChange,e))},nativeElement=element.get()[0];nativeElement.addEventListener("focus",(function(e){var target;(target=e.target).dataset.initValue=target.value}),!0),nativeElement.addEventListener("blur",(function(e){checkAndTriggerAccessibleChange(e)}),!0),element.on("keydown",(function(e){var target;e.which===keyCodes.enter?checkAndTriggerAccessibleChange(e):e.which===keyCodes.escape?("initValue"in(target=e.target).dataset&&(target.value=target.dataset.initValue),e.target.dataset.ignoreChange=!0):e.target.dataset.ignoreChange=!0})),element.on("change",(function(e){e.target.dataset.ignoreChange||checkAndTriggerAccessibleChange(e)})),element.on("keyup",(function(e){delete e.target.dataset.ignoreChange})),element.on("click",(function(e){checkAndTriggerAccessibleChange(e)}))}};return{define:function(element,include){var handlers;(element=$(element),include=include||[],element.length&&include.length)&&$.each(((handlers={})[events.activate]=addActivateListener,handlers[events.keyboardActivate]=addKeyboardActivateListener,handlers[events.escape]=addEscapeListener,handlers[events.down]=addDownListener,handlers[events.up]=addUpListener,handlers[events.home]=addHomeListener,handlers[events.end]=addEndListener,handlers[events.next]=addNextListener,handlers[events.previous]=addPreviousListener,handlers[events.asterix]=addAsterixListener,handlers[events.scrollLock]=addScrollLockListener,handlers[events.scrollTop]=addScrollTopListener,handlers[events.scrollBottom]=addScrollBottomListener,handlers[events.ctrlPageUp]=addCtrlPageUpListener,handlers[events.ctrlPageDown]=addCtrlPageDownListener,handlers[events.enter]=addEnterListener,handlers[events.accessibleChange]=addAccessibleChangeListener,handlers),(function(eventType,handler){(function(eventType,include){return!(!(include=include||[]).length||-1===include.indexOf(eventType))})(eventType,include)&&handler(element)}))},events:events}})); define("core/datafilter/filtertypes/country",["exports","core/datafilter/filtertype"],(function(_exports,_filtertype){var obj; /** * Country filter * * @module core/datafilter/filtertypes/country * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_filtertype=(obj=_filtertype)&&obj.__esModule?obj:{default:obj};class _default extends _filtertype.default{get values(){return this.rawValues}}return _exports.default=_default,_exports.default})); define("core/datafilter/filtertypes/courseid",["exports","core/datafilter/filtertype"],(function(_exports,_filtertype){var obj; /** * Course ID filter. * * @module core/datafilter/filtertypes/courseid * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_filtertype=(obj=_filtertype)&&obj.__esModule?obj:{default:obj};class _default extends _filtertype.default{constructor(filterType,filterSet){super(filterType,filterSet)}async addValueSelector(){}get filterValue(){return{name:this.name,jointype:1,values:[parseInt(this.rootNode.dataset.tableCourseId,10)]}}}return _exports.default=_default,_exports.default})); define("core/datafilter/filtertypes/keyword",["exports","core/datafilter/filtertype","core/str"],(function(_exports,_filtertype,_str){var obj; /** * Keyword filter. * * @module core/datafilter/filtertypes/keyword * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_filtertype=(obj=_filtertype)&&obj.__esModule?obj:{default:obj};class _default extends _filtertype.default{get values(){return this.rawValues}get placeholder(){return(0,_str.get_string)("placeholdertype","core_user")}get showSuggestions(){return!1}}return _exports.default=_default,_exports.default})); define("core/datafilter/filtertype",["exports","core/form-autocomplete","core/datafilter/selectors","core/str"],(function(_exports,_formAutocomplete,_selectors,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Base Filter class for a filter type in the filter UI. * * @module core/datafilter/filtertype * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_formAutocomplete=_interopRequireDefault(_formAutocomplete),_selectors=_interopRequireDefault(_selectors);return _exports.default=class{constructor(filterType,rootNode,initialValues){this.filterType=filterType,this.rootNode=rootNode,this.addValueSelector(initialValues)}tearDown(){}get placeholder(){return(0,_str.get_string)("placeholdertypeorselect","core")}get showSuggestions(){return!0}async addValueSelector(){let initialValues=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const filterValueNode=this.getFilterValueNode(),sourceDataNode=this.getSourceDataForFilter();if(!sourceDataNode)return;filterValueNode.innerHTML=sourceDataNode.outerHTML;const dataSource=filterValueNode.querySelector("select");dataSource.id="filter-value-"+dataSource.getAttribute("data-field-name");const filterValueLabel=document.createElement("label");filterValueLabel.setAttribute("for",dataSource.id),filterValueLabel.classList.add("sr-only"),filterValueLabel.innerText=dataSource.getAttribute("data-field-title"),filterValueNode.appendChild(filterValueLabel),initialValues.forEach((filterValue=>{let selectedOption=dataSource.querySelector('option[value="'.concat(filterValue,'"]'));selectedOption?selectedOption.selected=!0:this.showSuggestions||(selectedOption=document.createElement("option"),selectedOption.value=filterValue,selectedOption.innerHTML=filterValue,selectedOption.selected=!0,dataSource.append(selectedOption))})),_formAutocomplete.default.enhance(dataSource,"1"==dataSource.dataset.allowCustom,null,await this.placeholder,!1,this.showSuggestions,null,!dataSource.multiple,{items:"core/datafilter/autocomplete_selection_items",layout:"core/datafilter/autocomplete_layout",selection:"core/datafilter/autocomplete_selection"})}get filterRoot(){return this.rootNode.querySelector(_selectors.default.filter.byName(this.filterType))}getSourceDataForFilter(){return this.rootNode.querySelector(_selectors.default.filterset.regions.datasource).querySelector(_selectors.default.data.fields.byName(this.filterType))}getFilterValueNode(){return this.filterRoot.querySelector(_selectors.default.filter.regions.values)}get name(){return this.filterType}get jointype(){return parseInt(this.filterRoot.querySelector(_selectors.default.filter.fields.join).value,10)}get rawValues(){const filterValueSelect=this.getFilterValueNode().querySelector("select");return Object.values((select=filterValueSelect,select.querySelectorAll(":checked"))).map((option=>option.value));var select}get values(){return this.rawValues.map((option=>parseInt(option,10)))}get filterValue(){return{name:this.name,jointype:this.jointype,values:this.values}}},_exports.default})); define("core/datafilter/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Module containing the selectors for user filters. * * @module core/datafilter/selectors * @copyright 2020 Michael Hawkins <michaelh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const getFilterRegion=region=>'[data-filterregion="'.concat(region,'"]'),getFilterAction=action=>'[data-filteraction="'.concat(action,'"]'),getFilterField=field=>'[data-filterfield="'.concat(field,'"]');var _default={filter:{region:getFilterRegion("filter"),actions:{remove:getFilterAction("remove")},fields:{join:getFilterField("join"),type:getFilterField("type")},regions:{values:getFilterRegion("value")},byName:name=>"".concat(getFilterRegion("filter"),'[data-filter-type="').concat(name,'"]')},filterset:{region:getFilterRegion("actions"),actions:{addRow:getFilterAction("add"),applyFilters:getFilterAction("apply"),resetFilters:getFilterAction("reset")},regions:{filtermatch:getFilterRegion("filtermatch"),filterlist:getFilterRegion("filters"),datasource:getFilterRegion("filtertypedata")},fields:{join:"".concat(getFilterRegion("filtermatch")," ").concat(getFilterField("join"))}},data:{fields:{byName:name=>'[data-field-name="'.concat(name,'"]'),all:"".concat(getFilterRegion("filtertypedata")," [data-field-name]")},typeList:getFilterRegion("filtertypelist"),typeListSelect:"select".concat(getFilterRegion("filtertypelist"))}};return _exports.default=_default,_exports.default})); /* * JavaScript to handle drag operations, including automatic scrolling. * * Note: this module is defined statically. It is a singleton. You * can only have one use of it active at any time. However, you * can only drag one thing at a time, this is not a problem in practice. * * @module core/dragdrop * @copyright 2016 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("core/dragdrop",["jquery","core/autoscroll"],(function($,autoScroll){var dragdrop={eventCaptureOptions:{passive:!1,capture:!0},dragProxy:null,onMove:null,onDrop:null,initialPosition:null,initialX:null,initialY:null,touching:null,prepare:function(event){if(event.preventDefault(),"touchstart"===event.type?null===dragdrop.touching&&event.changedTouches.length>0:1===event.which){var details=dragdrop.getEventXY(event);return details.start=!0,details}return{start:!1}},start:function(event,dragProxy,onMove,onDrop){var xy=dragdrop.getEventXY(event);switch(dragdrop.initialX=xy.x,dragdrop.initialY=xy.y,dragdrop.initialPosition=dragProxy.offset(),dragdrop.dragProxy=dragProxy,dragdrop.onMove=onMove,dragdrop.onDrop=onDrop,event.type){case"mousedown":dragdrop.addEventSpecial("mousemove",dragdrop.mouseMove),dragdrop.addEventSpecial("mouseup",dragdrop.mouseUp);break;case"touchstart":dragdrop.addEventSpecial("touchend",dragdrop.touchEnd),dragdrop.addEventSpecial("touchcancel",dragdrop.touchEnd),dragdrop.addEventSpecial("touchmove",dragdrop.touchMove),dragdrop.touching=event.changedTouches[0].identifier;break;default:throw new Error("Unexpected event type: "+event.type)}autoScroll.start(dragdrop.scroll)},addEventSpecial:function(event,handler){try{window.addEventListener(event,handler,dragdrop.eventCaptureOptions)}catch(ex){dragdrop.eventCaptureOptions=!0,window.addEventListener(event,handler,dragdrop.eventCaptureOptions)}},getEventXY:function(event){switch(event.type){case"touchstart":return{x:event.changedTouches[0].pageX,y:event.changedTouches[0].pageY};case"mousedown":return{x:event.pageX,y:event.pageY};default:throw new Error("Unexpected event type: "+event.type)}},touchMove:function(e){e.preventDefault();for(var i=0;i<e.changedTouches.length;i++)e.changedTouches[i].identifier===dragdrop.touching&&dragdrop.handleMove(e.changedTouches[i].pageX,e.changedTouches[i].pageY)},mouseMove:function(e){dragdrop.handleMove(e.pageX,e.pageY)},handleMove:function(pageX,pageY){var current=dragdrop.dragProxy.offset(),topOffset=current.top-parseInt(dragdrop.dragProxy.css("top")),leftOffset=current.left-parseInt(dragdrop.dragProxy.css("left")),maxY=$(document).height()-dragdrop.dragProxy.outerHeight()-topOffset,maxX=$(document).width()-dragdrop.dragProxy.outerWidth()-leftOffset,minY=-topOffset,minX=-leftOffset,initial=dragdrop.initialPosition,position={top:Math.max(minY,Math.min(maxY,initial.top+(pageY-dragdrop.initialY)-topOffset)),left:Math.max(minX,Math.min(maxX,initial.left+(pageX-dragdrop.initialX)-leftOffset))};dragdrop.dragProxy.css(position),dragdrop.onMove(pageX,pageY,dragdrop.dragProxy)},touchEnd:function(e){e.preventDefault();for(var i=0;i<e.changedTouches.length;i++)e.changedTouches[i].identifier===dragdrop.touching&&dragdrop.handleEnd(e.changedTouches[i].pageX,e.changedTouches[i].pageY)},mouseUp:function(e){dragdrop.handleEnd(e.pageX,e.pageY)},handleEnd:function(pageX,pageY){null!==dragdrop.touching?(window.removeEventListener("touchend",dragdrop.touchEnd,dragdrop.eventCaptureOptions),window.removeEventListener("touchcancel",dragdrop.touchEnd,dragdrop.eventCaptureOptions),window.removeEventListener("touchmove",dragdrop.touchMove,dragdrop.eventCaptureOptions),dragdrop.touching=null):(window.removeEventListener("mousemove",dragdrop.mouseMove,dragdrop.eventCaptureOptions),window.removeEventListener("mouseup",dragdrop.mouseUp,dragdrop.eventCaptureOptions)),autoScroll.stop(),dragdrop.onDrop(pageX,pageY,dragdrop.dragProxy)},scroll:function(offset){var maxY=$(document).height()-dragdrop.dragProxy.outerHeight(),currentPosition=dragdrop.dragProxy.offset();currentPosition.top=Math.min(maxY,currentPosition.top+offset),dragdrop.dragProxy.css(currentPosition)}};return{prepare:dragdrop.prepare,start:dragdrop.start}})); define("core/drawer",["exports","jquery","core/pubsub","core/aria","core/drawer_events"],(function(_exports,_jquery,PubSub,Aria,_drawer_events){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Controls the drawer. * * @module core/drawer * @copyright 2019 Jun Pataleta <jun@moodle.com> * @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),PubSub=_interopRequireWildcard(PubSub),Aria=_interopRequireWildcard(Aria),_drawer_events=_interopRequireDefault(_drawer_events);const show=root=>{root=(0,_jquery.default)(root),Aria.unhide(root.get()),root.removeClass("hidden"),root.attr("aria-expanded",!0),root.focus(),PubSub.publish(_drawer_events.default.DRAWER_SHOWN,root)},hide=root=>{(root=(0,_jquery.default)(root)).addClass("hidden"),root.attr("aria-expanded",!1),Aria.hide(root.get()),PubSub.publish(_drawer_events.default.DRAWER_HIDDEN,root)},isVisible=root=>!root.hasClass("hidden"),toggle=root=>{isVisible(root)?hide(root):show(root)};var _default={hide:hide,show:show,isVisible:isVisible,toggle:toggle,registerToggles:(root,toggleElements)=>{let openTrigger=null;toggleElements.attr("aria-expanded",isVisible(root)),toggleElements.on("click",(e=>{e.preventDefault();const wasVisible=isVisible(root);toggle(root),toggleElements.attr("aria-expanded",!wasVisible),wasVisible?openTrigger&&(openTrigger.focus(),openTrigger=null):openTrigger=toggleElements.filter(((index,element)=>element==e.target||element.contains(e.target)))}))},getDrawerRoot:contentRoot=>(contentRoot=(0,_jquery.default)(contentRoot)).closest('[data-region="right-hand-drawer"]')};return _exports.default=_default,_exports.default})); define("core/drawer_events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={DRAWER_SHOWN:"drawer-shown",DRAWER_HIDDEN:"drawer-hidden"},_exports.default})); define("core/edit_switch",["exports","core/ajax","core/event_dispatcher","core/notification"],(function(_exports,_ajax,_event_dispatcher,_notification){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=_exports.eventTypes=void 0; /** * Controls the edit switch. * * @module core/edit_switch * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const eventTypes={editModeSet:"core/edit_switch/editModeSet"};_exports.eventTypes=eventTypes;const notifyEditModeSet=(container,editMode)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.editModeSet,{editMode:editMode},container,{cancelable:!0});_exports.init=editingSwitchId=>{const editSwitch=document.getElementById(editingSwitchId);editSwitch.addEventListener("change",(()=>{var context,setmode;(context=editSwitch.dataset.context,setmode=editSwitch.checked,(0,_ajax.call)([{methodname:"core_change_editmode",args:{context:context,setmode:setmode}}])[0]).then((result=>{result.success?(editSwitch=>{editSwitch.checked?editSwitch.setAttribute("aria-checked",!0):editSwitch.setAttribute("aria-checked",!1),notifyEditModeSet(editSwitch,editSwitch.checked).defaultPrevented||(editSwitch.setAttribute("disabled",!0),window.location=editSwitch.dataset.pageurl)})(editSwitch):editSwitch.checked=!1})).catch(_notification.exception)}))}})); define("core/emoji/auto_complete",["exports","core/emoji/data","core/templates","core/utils","core/localstorage","core/key_codes"],(function(_exports,EmojiData,_templates,_utils,_localstorage,_key_codes){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,EmojiData=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Emoji auto complete. * * @module core/emoji/auto_complete * @copyright 2019 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(EmojiData),_localstorage=_interopRequireDefault(_localstorage),_key_codes=_interopRequireDefault(_key_codes);const SELECTORS_EMOJI_BUTTON='[data-region="emoji-button"]',SELECTORS_ACTIVE_EMOJI_BUTTON='[data-region="emoji-button"].active',getRecentEmojis=()=>{const storedData=_localstorage.default.get("moodle-recent-emojis");return storedData?JSON.parse(storedData):[]},addRecentEmoji=(unified,shortName)=>{const newEmoji={unified:unified,shortnames:[shortName]},recentEmojis=getRecentEmojis();let newRecentEmojis=[newEmoji,...recentEmojis.filter((emoji=>emoji.unified!=newEmoji.unified))];newRecentEmojis=newRecentEmojis.slice(0,27),_localstorage.default.set("moodle-recent-emojis",JSON.stringify(newRecentEmojis))},getEmojiTextFromShortName=shortName=>{const unified=EmojiData.byShortName[shortName];if(unified){const charCodes=unified.split("-").map((code=>"0x".concat(code)));return String.fromCodePoint.apply(null,charCodes)}return null},getShortNameFromText=text=>text.replace(/:/g,""),getActiveEmojiSuggestion=root=>root.querySelector(SELECTORS_ACTIVE_EMOJI_BUTTON),selectEmojiElement=(element,selectCallback)=>{const shortName=element.getAttribute("data-short-name"),unified=element.getAttribute("data-unified");addRecentEmoji(unified,shortName),selectCallback(element.innerHTML.trim())};return _exports.default=(root,textArea,hasSuggestionCallback,selectCallback)=>{let hasSuggestions=!1,previousSearchText="";textArea.addEventListener("keyup",(0,_utils.debounce)((()=>{const searchText=((text,position)=>{const startMatches=text.slice(0,position).match(/(\S*)$/),endMatches=text.slice(position).match(/^(\S*)/);let startText="",endText="";return startMatches&&(startText=startMatches[startMatches.length-1]),endMatches&&(endText=endMatches[endMatches.length-1]),"".concat(startText).concat(endText)})(textArea.value,textArea.selectionStart);if(searchText!==previousSearchText){if(previousSearchText=searchText,(text=>/^:[^:\s]+:$/.test(text))(searchText)){const shortName=getShortNameFromText(searchText),emojiText=getEmojiTextFromShortName(shortName);hasSuggestions=!1,emojiText&&(addRecentEmoji(EmojiData.byShortName[shortName],shortName),selectCallback(emojiText))}else if((text=>/^:[^:\s]*$/.test(text))(searchText)){const suggestions=(searchTerm=getShortNameFromText(searchText),limit=50,""===searchTerm?getRecentEmojis().map((data=>data.shortnames[0])).slice(0,limit):(searchTerm=searchTerm.toLowerCase(),Object.keys(EmojiData.byShortName).filter((shortName=>shortName.includes(searchTerm))).slice(0,limit)));suggestions.length?((async(root,shortNames)=>{const renderContext={emojis:shortNames.map(((shortName,index)=>({active:0===index,emojitext:getEmojiTextFromShortName(shortName),displayshortname:":".concat(shortName,":"),shortname:shortName,unified:EmojiData.byShortName[shortName]})))},html=await(0,_templates.render)("core/emoji/auto_complete",renderContext);root.innerHTML=html})(root,suggestions),hasSuggestions=!0):hasSuggestions=!1}else hasSuggestions=!1;var searchTerm,limit;hasSuggestionCallback(hasSuggestions)}}),200)),textArea.addEventListener("keydown",(e=>{if(hasSuggestions){if(!(e.shiftKey||e.metaKey||e.altKey||e.ctrlKey))switch(e.which){case _key_codes.default.escape:hasSuggestions=!1,hasSuggestionCallback(!1);break;case _key_codes.default.arrowLeft:(root=>{const activeEmojiSuggestion=getActiveEmojiSuggestion(root),previousSuggestion=activeEmojiSuggestion.previousElementSibling;previousSuggestion&&(activeEmojiSuggestion.classList.remove("active"),previousSuggestion.classList.add("active"),previousSuggestion.scrollIntoView({behaviour:"smooth",inline:"center"}))})(root),e.preventDefault();break;case _key_codes.default.arrowRight:(root=>{const activeEmojiSuggestion=getActiveEmojiSuggestion(root),nextSuggestion=activeEmojiSuggestion.nextElementSibling;nextSuggestion&&(activeEmojiSuggestion.classList.remove("active"),nextSuggestion.classList.add("active"),nextSuggestion.scrollIntoView({behaviour:"smooth",inline:"center"}))})(root),e.preventDefault();break;case _key_codes.default.enter:selectEmojiElement(getActiveEmojiSuggestion(root),selectCallback),e.preventDefault(),e.stopPropagation()}}})),root.addEventListener("click",(e=>{const target=e.target;target.matches(SELECTORS_EMOJI_BUTTON)&&selectEmojiElement(target,selectCallback)}))},_exports.default})); define("core/emoji/data",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.byShortName=_exports.byCategory=void 0;_exports.byCategory=[{name:"Smileys & Emotion",emojis:[{unified:"1F600",shortnames:["grinning"]},{unified:"1F603",shortnames:["smiley"]},{unified:"1F604",shortnames:["smile"]},{unified:"1F601",shortnames:["grin"]},{unified:"1F606",shortnames:["laughing"]},{unified:"1F605",shortnames:["sweat_smile"]},{unified:"1F923",shortnames:["rolling_on_the_floor_laughing"]},{unified:"1F602",shortnames:["joy"]},{unified:"1F642",shortnames:["slightly_smiling_face"]},{unified:"1F643",shortnames:["upside_down_face"]},{unified:"1FAE0",shortnames:["melting_face"]},{unified:"1F609",shortnames:["wink"]},{unified:"1F60A",shortnames:["blush"]},{unified:"1F607",shortnames:["innocent"]},{unified:"1F970",shortnames:["smiling_face_with_3_hearts"]},{unified:"1F60D",shortnames:["heart_eyes"]},{unified:"1F929",shortnames:["star-struck"]},{unified:"1F618",shortnames:["kissing_heart"]},{unified:"1F617",shortnames:["kissing"]},{unified:"263A-FE0F",shortnames:["relaxed"]},{unified:"1F61A",shortnames:["kissing_closed_eyes"]},{unified:"1F619",shortnames:["kissing_smiling_eyes"]},{unified:"1F972",shortnames:["smiling_face_with_tear"]},{unified:"1F60B",shortnames:["yum"]},{unified:"1F61B",shortnames:["stuck_out_tongue"]},{unified:"1F61C",shortnames:["stuck_out_tongue_winking_eye"]},{unified:"1F92A",shortnames:["zany_face"]},{unified:"1F61D",shortnames:["stuck_out_tongue_closed_eyes"]},{unified:"1F911",shortnames:["money_mouth_face"]},{unified:"1F917",shortnames:["hugging_face"]},{unified:"1F92D",shortnames:["face_with_hand_over_mouth"]},{unified:"1FAE2",shortnames:["face_with_open_eyes_and_hand_over_mouth"]},{unified:"1FAE3",shortnames:["face_with_peeking_eye"]},{unified:"1F92B",shortnames:["shushing_face"]},{unified:"1F914",shortnames:["thinking_face"]},{unified:"1FAE1",shortnames:["saluting_face"]},{unified:"1F910",shortnames:["zipper_mouth_face"]},{unified:"1F928",shortnames:["face_with_raised_eyebrow"]},{unified:"1F610",shortnames:["neutral_face"]},{unified:"1F611",shortnames:["expressionless"]},{unified:"1F636",shortnames:["no_mouth"]},{unified:"1FAE5",shortnames:["dotted_line_face"]},{unified:"1F636-200D-1F32B-FE0F",shortnames:["face_in_clouds"]},{unified:"1F60F",shortnames:["smirk"]},{unified:"1F612",shortnames:["unamused"]},{unified:"1F644",shortnames:["face_with_rolling_eyes"]},{unified:"1F62C",shortnames:["grimacing"]},{unified:"1F62E-200D-1F4A8",shortnames:["face_exhaling"]},{unified:"1F925",shortnames:["lying_face"]},{unified:"1F60C",shortnames:["relieved"]},{unified:"1F614",shortnames:["pensive"]},{unified:"1F62A",shortnames:["sleepy"]},{unified:"1F924",shortnames:["drooling_face"]},{unified:"1F634",shortnames:["sleeping"]},{unified:"1F637",shortnames:["mask"]},{unified:"1F912",shortnames:["face_with_thermometer"]},{unified:"1F915",shortnames:["face_with_head_bandage"]},{unified:"1F922",shortnames:["nauseated_face"]},{unified:"1F92E",shortnames:["face_vomiting"]},{unified:"1F927",shortnames:["sneezing_face"]},{unified:"1F975",shortnames:["hot_face"]},{unified:"1F976",shortnames:["cold_face"]},{unified:"1F974",shortnames:["woozy_face"]},{unified:"1F635",shortnames:["dizzy_face"]},{unified:"1F635-200D-1F4AB",shortnames:["face_with_spiral_eyes"]},{unified:"1F92F",shortnames:["exploding_head"]},{unified:"1F920",shortnames:["face_with_cowboy_hat"]},{unified:"1F973",shortnames:["partying_face"]},{unified:"1F978",shortnames:["disguised_face"]},{unified:"1F60E",shortnames:["sunglasses"]},{unified:"1F913",shortnames:["nerd_face"]},{unified:"1F9D0",shortnames:["face_with_monocle"]},{unified:"1F615",shortnames:["confused"]},{unified:"1FAE4",shortnames:["face_with_diagonal_mouth"]},{unified:"1F61F",shortnames:["worried"]},{unified:"1F641",shortnames:["slightly_frowning_face"]},{unified:"2639-FE0F",shortnames:["white_frowning_face"]},{unified:"1F62E",shortnames:["open_mouth"]},{unified:"1F62F",shortnames:["hushed"]},{unified:"1F632",shortnames:["astonished"]},{unified:"1F633",shortnames:["flushed"]},{unified:"1F97A",shortnames:["pleading_face"]},{unified:"1F979",shortnames:["face_holding_back_tears"]},{unified:"1F626",shortnames:["frowning"]},{unified:"1F627",shortnames:["anguished"]},{unified:"1F628",shortnames:["fearful"]},{unified:"1F630",shortnames:["cold_sweat"]},{unified:"1F625",shortnames:["disappointed_relieved"]},{unified:"1F622",shortnames:["cry"]},{unified:"1F62D",shortnames:["sob"]},{unified:"1F631",shortnames:["scream"]},{unified:"1F616",shortnames:["confounded"]},{unified:"1F623",shortnames:["persevere"]},{unified:"1F61E",shortnames:["disappointed"]},{unified:"1F613",shortnames:["sweat"]},{unified:"1F629",shortnames:["weary"]},{unified:"1F62B",shortnames:["tired_face"]},{unified:"1F971",shortnames:["yawning_face"]},{unified:"1F624",shortnames:["triumph"]},{unified:"1F621",shortnames:["rage"]},{unified:"1F620",shortnames:["angry"]},{unified:"1F92C",shortnames:["face_with_symbols_on_mouth"]},{unified:"1F608",shortnames:["smiling_imp"]},{unified:"1F47F",shortnames:["imp"]},{unified:"1F480",shortnames:["skull"]},{unified:"2620-FE0F",shortnames:["skull_and_crossbones"]},{unified:"1F4A9",shortnames:["hankey"]},{unified:"1F921",shortnames:["clown_face"]},{unified:"1F479",shortnames:["japanese_ogre"]},{unified:"1F47A",shortnames:["japanese_goblin"]},{unified:"1F47B",shortnames:["ghost"]},{unified:"1F47D",shortnames:["alien"]},{unified:"1F47E",shortnames:["space_invader"]},{unified:"1F916",shortnames:["robot_face"]},{unified:"1F63A",shortnames:["smiley_cat"]},{unified:"1F638",shortnames:["smile_cat"]},{unified:"1F639",shortnames:["joy_cat"]},{unified:"1F63B",shortnames:["heart_eyes_cat"]},{unified:"1F63C",shortnames:["smirk_cat"]},{unified:"1F63D",shortnames:["kissing_cat"]},{unified:"1F640",shortnames:["scream_cat"]},{unified:"1F63F",shortnames:["crying_cat_face"]},{unified:"1F63E",shortnames:["pouting_cat"]},{unified:"1F648",shortnames:["see_no_evil"]},{unified:"1F649",shortnames:["hear_no_evil"]},{unified:"1F64A",shortnames:["speak_no_evil"]},{unified:"1F48B",shortnames:["kiss"]},{unified:"1F48C",shortnames:["love_letter"]},{unified:"1F498",shortnames:["cupid"]},{unified:"1F49D",shortnames:["gift_heart"]},{unified:"1F496",shortnames:["sparkling_heart"]},{unified:"1F497",shortnames:["heartpulse"]},{unified:"1F493",shortnames:["heartbeat"]},{unified:"1F49E",shortnames:["revolving_hearts"]},{unified:"1F495",shortnames:["two_hearts"]},{unified:"1F49F",shortnames:["heart_decoration"]},{unified:"2763-FE0F",shortnames:["heavy_heart_exclamation_mark_ornament"]},{unified:"1F494",shortnames:["broken_heart"]},{unified:"2764-FE0F-200D-1F525",shortnames:["heart_on_fire"]},{unified:"2764-FE0F-200D-1FA79",shortnames:["mending_heart"]},{unified:"2764-FE0F",shortnames:["heart"]},{unified:"1F9E1",shortnames:["orange_heart"]},{unified:"1F49B",shortnames:["yellow_heart"]},{unified:"1F49A",shortnames:["green_heart"]},{unified:"1F499",shortnames:["blue_heart"]},{unified:"1F49C",shortnames:["purple_heart"]},{unified:"1F90E",shortnames:["brown_heart"]},{unified:"1F5A4",shortnames:["black_heart"]},{unified:"1F90D",shortnames:["white_heart"]},{unified:"1F4AF",shortnames:["100"]},{unified:"1F4A2",shortnames:["anger"]},{unified:"1F4A5",shortnames:["boom"]},{unified:"1F4AB",shortnames:["dizzy"]},{unified:"1F4A6",shortnames:["sweat_drops"]},{unified:"1F4A8",shortnames:["dash"]},{unified:"1F573-FE0F",shortnames:["hole"]},{unified:"1F4A3",shortnames:["bomb"]},{unified:"1F4AC",shortnames:["speech_balloon"]},{unified:"1F441-FE0F-200D-1F5E8-FE0F",shortnames:["eye-in-speech-bubble"]},{unified:"1F5E8-FE0F",shortnames:["left_speech_bubble"]},{unified:"1F5EF-FE0F",shortnames:["right_anger_bubble"]},{unified:"1F4AD",shortnames:["thought_balloon"]},{unified:"1F4A4",shortnames:["zzz"]}]},{name:"People & Body",emojis:[{unified:"1F44B",shortnames:["wave"]},{unified:"1F91A",shortnames:["raised_back_of_hand"]},{unified:"1F590-FE0F",shortnames:["raised_hand_with_fingers_splayed"]},{unified:"270B",shortnames:["hand"]},{unified:"1F596",shortnames:["spock-hand"]},{unified:"1FAF1",shortnames:["rightwards_hand"]},{unified:"1FAF2",shortnames:["leftwards_hand"]},{unified:"1FAF3",shortnames:["palm_down_hand"]},{unified:"1FAF4",shortnames:["palm_up_hand"]},{unified:"1F44C",shortnames:["ok_hand"]},{unified:"1F90C",shortnames:["pinched_fingers"]},{unified:"1F90F",shortnames:["pinching_hand"]},{unified:"270C-FE0F",shortnames:["v"]},{unified:"1F91E",shortnames:["crossed_fingers"]},{unified:"1FAF0",shortnames:["hand_with_index_finger_and_thumb_crossed"]},{unified:"1F91F",shortnames:["i_love_you_hand_sign"]},{unified:"1F918",shortnames:["the_horns"]},{unified:"1F919",shortnames:["call_me_hand"]},{unified:"1F448",shortnames:["point_left"]},{unified:"1F449",shortnames:["point_right"]},{unified:"1F446",shortnames:["point_up_2"]},{unified:"1F595",shortnames:["middle_finger"]},{unified:"1F447",shortnames:["point_down"]},{unified:"261D-FE0F",shortnames:["point_up"]},{unified:"1FAF5",shortnames:["index_pointing_at_the_viewer"]},{unified:"1F44D",shortnames:["+1"]},{unified:"1F44E",shortnames:["-1"]},{unified:"270A",shortnames:["fist"]},{unified:"1F44A",shortnames:["facepunch"]},{unified:"1F91B",shortnames:["left-facing_fist"]},{unified:"1F91C",shortnames:["right-facing_fist"]},{unified:"1F44F",shortnames:["clap"]},{unified:"1F64C",shortnames:["raised_hands"]},{unified:"1FAF6",shortnames:["heart_hands"]},{unified:"1F450",shortnames:["open_hands"]},{unified:"1F932",shortnames:["palms_up_together"]},{unified:"1F91D",shortnames:["handshake"]},{unified:"1F64F",shortnames:["pray"]},{unified:"270D-FE0F",shortnames:["writing_hand"]},{unified:"1F485",shortnames:["nail_care"]},{unified:"1F933",shortnames:["selfie"]},{unified:"1F4AA",shortnames:["muscle"]},{unified:"1F9BE",shortnames:["mechanical_arm"]},{unified:"1F9BF",shortnames:["mechanical_leg"]},{unified:"1F9B5",shortnames:["leg"]},{unified:"1F9B6",shortnames:["foot"]},{unified:"1F442",shortnames:["ear"]},{unified:"1F9BB",shortnames:["ear_with_hearing_aid"]},{unified:"1F443",shortnames:["nose"]},{unified:"1F9E0",shortnames:["brain"]},{unified:"1FAC0",shortnames:["anatomical_heart"]},{unified:"1FAC1",shortnames:["lungs"]},{unified:"1F9B7",shortnames:["tooth"]},{unified:"1F9B4",shortnames:["bone"]},{unified:"1F440",shortnames:["eyes"]},{unified:"1F441-FE0F",shortnames:["eye"]},{unified:"1F445",shortnames:["tongue"]},{unified:"1F444",shortnames:["lips"]},{unified:"1FAE6",shortnames:["biting_lip"]},{unified:"1F476",shortnames:["baby"]},{unified:"1F9D2",shortnames:["child"]},{unified:"1F466",shortnames:["boy"]},{unified:"1F467",shortnames:["girl"]},{unified:"1F9D1",shortnames:["adult"]},{unified:"1F468",shortnames:["man"]},{unified:"1F9D4",shortnames:["bearded_person"]},{unified:"1F9D4-200D-2642-FE0F",shortnames:["man_with_beard"]},{unified:"1F9D4-200D-2640-FE0F",shortnames:["woman_with_beard"]},{unified:"1F468-200D-1F9B0",shortnames:["red_haired_man"]},{unified:"1F468-200D-1F9B1",shortnames:["curly_haired_man"]},{unified:"1F468-200D-1F9B3",shortnames:["white_haired_man"]},{unified:"1F468-200D-1F9B2",shortnames:["bald_man"]},{unified:"1F469",shortnames:["woman"]},{unified:"1F469-200D-1F9B0",shortnames:["red_haired_woman"]},{unified:"1F9D1-200D-1F9B0",shortnames:["red_haired_person"]},{unified:"1F469-200D-1F9B1",shortnames:["curly_haired_woman"]},{unified:"1F9D1-200D-1F9B1",shortnames:["curly_haired_person"]},{unified:"1F469-200D-1F9B3",shortnames:["white_haired_woman"]},{unified:"1F9D1-200D-1F9B3",shortnames:["white_haired_person"]},{unified:"1F469-200D-1F9B2",shortnames:["bald_woman"]},{unified:"1F9D1-200D-1F9B2",shortnames:["bald_person"]},{unified:"1F471-200D-2640-FE0F",shortnames:["blond-haired-woman"]},{unified:"1F471-200D-2642-FE0F",shortnames:["blond-haired-man","person_with_blond_hair"]},{unified:"1F9D3",shortnames:["older_adult"]},{unified:"1F474",shortnames:["older_man"]},{unified:"1F475",shortnames:["older_woman"]},{unified:"1F64D-200D-2642-FE0F",shortnames:["man-frowning"]},{unified:"1F64D-200D-2640-FE0F",shortnames:["woman-frowning","person_frowning"]},{unified:"1F64E-200D-2642-FE0F",shortnames:["man-pouting"]},{unified:"1F64E-200D-2640-FE0F",shortnames:["woman-pouting","person_with_pouting_face"]},{unified:"1F645-200D-2642-FE0F",shortnames:["man-gesturing-no"]},{unified:"1F645-200D-2640-FE0F",shortnames:["woman-gesturing-no","no_good"]},{unified:"1F646-200D-2642-FE0F",shortnames:["man-gesturing-ok"]},{unified:"1F646-200D-2640-FE0F",shortnames:["woman-gesturing-ok","ok_woman"]},{unified:"1F481-200D-2642-FE0F",shortnames:["man-tipping-hand"]},{unified:"1F481-200D-2640-FE0F",shortnames:["woman-tipping-hand","information_desk_person"]},{unified:"1F64B-200D-2642-FE0F",shortnames:["man-raising-hand"]},{unified:"1F64B-200D-2640-FE0F",shortnames:["woman-raising-hand","raising_hand"]},{unified:"1F9CF",shortnames:["deaf_person"]},{unified:"1F9CF-200D-2642-FE0F",shortnames:["deaf_man"]},{unified:"1F9CF-200D-2640-FE0F",shortnames:["deaf_woman"]},{unified:"1F647",shortnames:["bow"]},{unified:"1F647-200D-2642-FE0F",shortnames:["man-bowing"]},{unified:"1F647-200D-2640-FE0F",shortnames:["woman-bowing"]},{unified:"1F926",shortnames:["face_palm"]},{unified:"1F926-200D-2642-FE0F",shortnames:["man-facepalming"]},{unified:"1F926-200D-2640-FE0F",shortnames:["woman-facepalming"]},{unified:"1F937",shortnames:["shrug"]},{unified:"1F937-200D-2642-FE0F",shortnames:["man-shrugging"]},{unified:"1F937-200D-2640-FE0F",shortnames:["woman-shrugging"]},{unified:"1F9D1-200D-2695-FE0F",shortnames:["health_worker"]},{unified:"1F468-200D-2695-FE0F",shortnames:["male-doctor"]},{unified:"1F469-200D-2695-FE0F",shortnames:["female-doctor"]},{unified:"1F9D1-200D-1F393",shortnames:["student"]},{unified:"1F468-200D-1F393",shortnames:["male-student"]},{unified:"1F469-200D-1F393",shortnames:["female-student"]},{unified:"1F9D1-200D-1F3EB",shortnames:["teacher"]},{unified:"1F468-200D-1F3EB",shortnames:["male-teacher"]},{unified:"1F469-200D-1F3EB",shortnames:["female-teacher"]},{unified:"1F9D1-200D-2696-FE0F",shortnames:["judge"]},{unified:"1F468-200D-2696-FE0F",shortnames:["male-judge"]},{unified:"1F469-200D-2696-FE0F",shortnames:["female-judge"]},{unified:"1F9D1-200D-1F33E",shortnames:["farmer"]},{unified:"1F468-200D-1F33E",shortnames:["male-farmer"]},{unified:"1F469-200D-1F33E",shortnames:["female-farmer"]},{unified:"1F9D1-200D-1F373",shortnames:["cook"]},{unified:"1F468-200D-1F373",shortnames:["male-cook"]},{unified:"1F469-200D-1F373",shortnames:["female-cook"]},{unified:"1F9D1-200D-1F527",shortnames:["mechanic"]},{unified:"1F468-200D-1F527",shortnames:["male-mechanic"]},{unified:"1F469-200D-1F527",shortnames:["female-mechanic"]},{unified:"1F9D1-200D-1F3ED",shortnames:["factory_worker"]},{unified:"1F468-200D-1F3ED",shortnames:["male-factory-worker"]},{unified:"1F469-200D-1F3ED",shortnames:["female-factory-worker"]},{unified:"1F9D1-200D-1F4BC",shortnames:["office_worker"]},{unified:"1F468-200D-1F4BC",shortnames:["male-office-worker"]},{unified:"1F469-200D-1F4BC",shortnames:["female-office-worker"]},{unified:"1F9D1-200D-1F52C",shortnames:["scientist"]},{unified:"1F468-200D-1F52C",shortnames:["male-scientist"]},{unified:"1F469-200D-1F52C",shortnames:["female-scientist"]},{unified:"1F9D1-200D-1F4BB",shortnames:["technologist"]},{unified:"1F468-200D-1F4BB",shortnames:["male-technologist"]},{unified:"1F469-200D-1F4BB",shortnames:["female-technologist"]},{unified:"1F9D1-200D-1F3A4",shortnames:["singer"]},{unified:"1F468-200D-1F3A4",shortnames:["male-singer"]},{unified:"1F469-200D-1F3A4",shortnames:["female-singer"]},{unified:"1F9D1-200D-1F3A8",shortnames:["artist"]},{unified:"1F468-200D-1F3A8",shortnames:["male-artist"]},{unified:"1F469-200D-1F3A8",shortnames:["female-artist"]},{unified:"1F9D1-200D-2708-FE0F",shortnames:["pilot"]},{unified:"1F468-200D-2708-FE0F",shortnames:["male-pilot"]},{unified:"1F469-200D-2708-FE0F",shortnames:["female-pilot"]},{unified:"1F9D1-200D-1F680",shortnames:["astronaut"]},{unified:"1F468-200D-1F680",shortnames:["male-astronaut"]},{unified:"1F469-200D-1F680",shortnames:["female-astronaut"]},{unified:"1F9D1-200D-1F692",shortnames:["firefighter"]},{unified:"1F468-200D-1F692",shortnames:["male-firefighter"]},{unified:"1F469-200D-1F692",shortnames:["female-firefighter"]},{unified:"1F46E-200D-2642-FE0F",shortnames:["male-police-officer","cop"]},{unified:"1F46E-200D-2640-FE0F",shortnames:["female-police-officer"]},{unified:"1F575-FE0F-200D-2642-FE0F",shortnames:["male-detective","sleuth_or_spy"]},{unified:"1F575-FE0F-200D-2640-FE0F",shortnames:["female-detective"]},{unified:"1F482-200D-2642-FE0F",shortnames:["male-guard","guardsman"]},{unified:"1F482-200D-2640-FE0F",shortnames:["female-guard"]},{unified:"1F977",shortnames:["ninja"]},{unified:"1F477-200D-2642-FE0F",shortnames:["male-construction-worker","construction_worker"]},{unified:"1F477-200D-2640-FE0F",shortnames:["female-construction-worker"]},{unified:"1FAC5",shortnames:["person_with_crown"]},{unified:"1F934",shortnames:["prince"]},{unified:"1F478",shortnames:["princess"]},{unified:"1F473-200D-2642-FE0F",shortnames:["man-wearing-turban","man_with_turban"]},{unified:"1F473-200D-2640-FE0F",shortnames:["woman-wearing-turban"]},{unified:"1F472",shortnames:["man_with_gua_pi_mao"]},{unified:"1F9D5",shortnames:["person_with_headscarf"]},{unified:"1F935",shortnames:["person_in_tuxedo"]},{unified:"1F935-200D-2642-FE0F",shortnames:["man_in_tuxedo"]},{unified:"1F935-200D-2640-FE0F",shortnames:["woman_in_tuxedo"]},{unified:"1F470",shortnames:["bride_with_veil"]},{unified:"1F470-200D-2642-FE0F",shortnames:["man_with_veil"]},{unified:"1F470-200D-2640-FE0F",shortnames:["woman_with_veil"]},{unified:"1F930",shortnames:["pregnant_woman"]},{unified:"1FAC3",shortnames:["pregnant_man"]},{unified:"1FAC4",shortnames:["pregnant_person"]},{unified:"1F931",shortnames:["breast-feeding"]},{unified:"1F469-200D-1F37C",shortnames:["woman_feeding_baby"]},{unified:"1F468-200D-1F37C",shortnames:["man_feeding_baby"]},{unified:"1F9D1-200D-1F37C",shortnames:["person_feeding_baby"]},{unified:"1F47C",shortnames:["angel"]},{unified:"1F385",shortnames:["santa"]},{unified:"1F936",shortnames:["mrs_claus"]},{unified:"1F9D1-200D-1F384",shortnames:["mx_claus"]},{unified:"1F9B8",shortnames:["superhero"]},{unified:"1F9B8-200D-2642-FE0F",shortnames:["male_superhero"]},{unified:"1F9B8-200D-2640-FE0F",shortnames:["female_superhero"]},{unified:"1F9B9",shortnames:["supervillain"]},{unified:"1F9B9-200D-2642-FE0F",shortnames:["male_supervillain"]},{unified:"1F9B9-200D-2640-FE0F",shortnames:["female_supervillain"]},{unified:"1F9D9-200D-2642-FE0F",shortnames:["male_mage"]},{unified:"1F9D9-200D-2640-FE0F",shortnames:["female_mage","mage"]},{unified:"1F9DA-200D-2642-FE0F",shortnames:["male_fairy"]},{unified:"1F9DA-200D-2640-FE0F",shortnames:["female_fairy","fairy"]},{unified:"1F9DB-200D-2642-FE0F",shortnames:["male_vampire"]},{unified:"1F9DB-200D-2640-FE0F",shortnames:["female_vampire","vampire"]},{unified:"1F9DC-200D-2642-FE0F",shortnames:["merman","merperson"]},{unified:"1F9DC-200D-2640-FE0F",shortnames:["mermaid"]},{unified:"1F9DD-200D-2642-FE0F",shortnames:["male_elf","elf"]},{unified:"1F9DD-200D-2640-FE0F",shortnames:["female_elf"]},{unified:"1F9DE-200D-2642-FE0F",shortnames:["male_genie","genie"]},{unified:"1F9DE-200D-2640-FE0F",shortnames:["female_genie"]},{unified:"1F9DF-200D-2642-FE0F",shortnames:["male_zombie","zombie"]},{unified:"1F9DF-200D-2640-FE0F",shortnames:["female_zombie"]},{unified:"1F9CC",shortnames:["troll"]},{unified:"1F486-200D-2642-FE0F",shortnames:["man-getting-massage"]},{unified:"1F486-200D-2640-FE0F",shortnames:["woman-getting-massage","massage"]},{unified:"1F487-200D-2642-FE0F",shortnames:["man-getting-haircut"]},{unified:"1F487-200D-2640-FE0F",shortnames:["woman-getting-haircut","haircut"]},{unified:"1F6B6-200D-2642-FE0F",shortnames:["man-walking","walking"]},{unified:"1F6B6-200D-2640-FE0F",shortnames:["woman-walking"]},{unified:"1F9CD",shortnames:["standing_person"]},{unified:"1F9CD-200D-2642-FE0F",shortnames:["man_standing"]},{unified:"1F9CD-200D-2640-FE0F",shortnames:["woman_standing"]},{unified:"1F9CE",shortnames:["kneeling_person"]},{unified:"1F9CE-200D-2642-FE0F",shortnames:["man_kneeling"]},{unified:"1F9CE-200D-2640-FE0F",shortnames:["woman_kneeling"]},{unified:"1F9D1-200D-1F9AF",shortnames:["person_with_probing_cane"]},{unified:"1F468-200D-1F9AF",shortnames:["man_with_probing_cane"]},{unified:"1F469-200D-1F9AF",shortnames:["woman_with_probing_cane"]},{unified:"1F9D1-200D-1F9BC",shortnames:["person_in_motorized_wheelchair"]},{unified:"1F468-200D-1F9BC",shortnames:["man_in_motorized_wheelchair"]},{unified:"1F469-200D-1F9BC",shortnames:["woman_in_motorized_wheelchair"]},{unified:"1F9D1-200D-1F9BD",shortnames:["person_in_manual_wheelchair"]},{unified:"1F468-200D-1F9BD",shortnames:["man_in_manual_wheelchair"]},{unified:"1F469-200D-1F9BD",shortnames:["woman_in_manual_wheelchair"]},{unified:"1F3C3-200D-2642-FE0F",shortnames:["man-running","runner"]},{unified:"1F3C3-200D-2640-FE0F",shortnames:["woman-running"]},{unified:"1F483",shortnames:["dancer"]},{unified:"1F57A",shortnames:["man_dancing"]},{unified:"1F574-FE0F",shortnames:["man_in_business_suit_levitating"]},{unified:"1F46F-200D-2642-FE0F",shortnames:["men-with-bunny-ears-partying"]},{unified:"1F46F-200D-2640-FE0F",shortnames:["women-with-bunny-ears-partying","dancers"]},{unified:"1F9D6-200D-2642-FE0F",shortnames:["man_in_steamy_room","person_in_steamy_room"]},{unified:"1F9D6-200D-2640-FE0F",shortnames:["woman_in_steamy_room"]},{unified:"1F9D7-200D-2642-FE0F",shortnames:["man_climbing"]},{unified:"1F9D7-200D-2640-FE0F",shortnames:["woman_climbing","person_climbing"]},{unified:"1F93A",shortnames:["fencer"]},{unified:"1F3C7",shortnames:["horse_racing"]},{unified:"26F7-FE0F",shortnames:["skier"]},{unified:"1F3C2",shortnames:["snowboarder"]},{unified:"1F3CC-FE0F-200D-2642-FE0F",shortnames:["man-golfing","golfer"]},{unified:"1F3CC-FE0F-200D-2640-FE0F",shortnames:["woman-golfing"]},{unified:"1F3C4-200D-2642-FE0F",shortnames:["man-surfing","surfer"]},{unified:"1F3C4-200D-2640-FE0F",shortnames:["woman-surfing"]},{unified:"1F6A3-200D-2642-FE0F",shortnames:["man-rowing-boat","rowboat"]},{unified:"1F6A3-200D-2640-FE0F",shortnames:["woman-rowing-boat"]},{unified:"1F3CA-200D-2642-FE0F",shortnames:["man-swimming","swimmer"]},{unified:"1F3CA-200D-2640-FE0F",shortnames:["woman-swimming"]},{unified:"26F9-FE0F-200D-2642-FE0F",shortnames:["man-bouncing-ball","person_with_ball"]},{unified:"26F9-FE0F-200D-2640-FE0F",shortnames:["woman-bouncing-ball"]},{unified:"1F3CB-FE0F-200D-2642-FE0F",shortnames:["man-lifting-weights","weight_lifter"]},{unified:"1F3CB-FE0F-200D-2640-FE0F",shortnames:["woman-lifting-weights"]},{unified:"1F6B4-200D-2642-FE0F",shortnames:["man-biking","bicyclist"]},{unified:"1F6B4-200D-2640-FE0F",shortnames:["woman-biking"]},{unified:"1F6B5-200D-2642-FE0F",shortnames:["man-mountain-biking","mountain_bicyclist"]},{unified:"1F6B5-200D-2640-FE0F",shortnames:["woman-mountain-biking"]},{unified:"1F938",shortnames:["person_doing_cartwheel"]},{unified:"1F938-200D-2642-FE0F",shortnames:["man-cartwheeling"]},{unified:"1F938-200D-2640-FE0F",shortnames:["woman-cartwheeling"]},{unified:"1F93C",shortnames:["wrestlers"]},{unified:"1F93C-200D-2642-FE0F",shortnames:["man-wrestling"]},{unified:"1F93C-200D-2640-FE0F",shortnames:["woman-wrestling"]},{unified:"1F93D",shortnames:["water_polo"]},{unified:"1F93D-200D-2642-FE0F",shortnames:["man-playing-water-polo"]},{unified:"1F93D-200D-2640-FE0F",shortnames:["woman-playing-water-polo"]},{unified:"1F93E",shortnames:["handball"]},{unified:"1F93E-200D-2642-FE0F",shortnames:["man-playing-handball"]},{unified:"1F93E-200D-2640-FE0F",shortnames:["woman-playing-handball"]},{unified:"1F939",shortnames:["juggling"]},{unified:"1F939-200D-2642-FE0F",shortnames:["man-juggling"]},{unified:"1F939-200D-2640-FE0F",shortnames:["woman-juggling"]},{unified:"1F9D8-200D-2642-FE0F",shortnames:["man_in_lotus_position"]},{unified:"1F9D8-200D-2640-FE0F",shortnames:["woman_in_lotus_position","person_in_lotus_position"]},{unified:"1F6C0",shortnames:["bath"]},{unified:"1F6CC",shortnames:["sleeping_accommodation"]},{unified:"1F9D1-200D-1F91D-200D-1F9D1",shortnames:["people_holding_hands"]},{unified:"1F46D",shortnames:["two_women_holding_hands"]},{unified:"1F46B",shortnames:["man_and_woman_holding_hands"]},{unified:"1F46C",shortnames:["two_men_holding_hands"]},{unified:"1F48F",shortnames:["couplekiss"]},{unified:"1F469-200D-2764-FE0F-200D-1F48B-200D-1F468",shortnames:["woman-kiss-man"]},{unified:"1F468-200D-2764-FE0F-200D-1F48B-200D-1F468",shortnames:["man-kiss-man"]},{unified:"1F469-200D-2764-FE0F-200D-1F48B-200D-1F469",shortnames:["woman-kiss-woman"]},{unified:"1F491",shortnames:["couple_with_heart"]},{unified:"1F469-200D-2764-FE0F-200D-1F468",shortnames:["woman-heart-man"]},{unified:"1F468-200D-2764-FE0F-200D-1F468",shortnames:["man-heart-man"]},{unified:"1F469-200D-2764-FE0F-200D-1F469",shortnames:["woman-heart-woman"]},{unified:"1F468-200D-1F469-200D-1F466",shortnames:["man-woman-boy","family"]},{unified:"1F468-200D-1F469-200D-1F467",shortnames:["man-woman-girl"]},{unified:"1F468-200D-1F469-200D-1F467-200D-1F466",shortnames:["man-woman-girl-boy"]},{unified:"1F468-200D-1F469-200D-1F466-200D-1F466",shortnames:["man-woman-boy-boy"]},{unified:"1F468-200D-1F469-200D-1F467-200D-1F467",shortnames:["man-woman-girl-girl"]},{unified:"1F468-200D-1F468-200D-1F466",shortnames:["man-man-boy"]},{unified:"1F468-200D-1F468-200D-1F467",shortnames:["man-man-girl"]},{unified:"1F468-200D-1F468-200D-1F467-200D-1F466",shortnames:["man-man-girl-boy"]},{unified:"1F468-200D-1F468-200D-1F466-200D-1F466",shortnames:["man-man-boy-boy"]},{unified:"1F468-200D-1F468-200D-1F467-200D-1F467",shortnames:["man-man-girl-girl"]},{unified:"1F469-200D-1F469-200D-1F466",shortnames:["woman-woman-boy"]},{unified:"1F469-200D-1F469-200D-1F467",shortnames:["woman-woman-girl"]},{unified:"1F469-200D-1F469-200D-1F467-200D-1F466",shortnames:["woman-woman-girl-boy"]},{unified:"1F469-200D-1F469-200D-1F466-200D-1F466",shortnames:["woman-woman-boy-boy"]},{unified:"1F469-200D-1F469-200D-1F467-200D-1F467",shortnames:["woman-woman-girl-girl"]},{unified:"1F468-200D-1F466",shortnames:["man-boy"]},{unified:"1F468-200D-1F466-200D-1F466",shortnames:["man-boy-boy"]},{unified:"1F468-200D-1F467",shortnames:["man-girl"]},{unified:"1F468-200D-1F467-200D-1F466",shortnames:["man-girl-boy"]},{unified:"1F468-200D-1F467-200D-1F467",shortnames:["man-girl-girl"]},{unified:"1F469-200D-1F466",shortnames:["woman-boy"]},{unified:"1F469-200D-1F466-200D-1F466",shortnames:["woman-boy-boy"]},{unified:"1F469-200D-1F467",shortnames:["woman-girl"]},{unified:"1F469-200D-1F467-200D-1F466",shortnames:["woman-girl-boy"]},{unified:"1F469-200D-1F467-200D-1F467",shortnames:["woman-girl-girl"]},{unified:"1F5E3-FE0F",shortnames:["speaking_head_in_silhouette"]},{unified:"1F464",shortnames:["bust_in_silhouette"]},{unified:"1F465",shortnames:["busts_in_silhouette"]},{unified:"1FAC2",shortnames:["people_hugging"]},{unified:"1F463",shortnames:["footprints"]}]},{name:"Animals & Nature",emojis:[{unified:"1F435",shortnames:["monkey_face"]},{unified:"1F412",shortnames:["monkey"]},{unified:"1F98D",shortnames:["gorilla"]},{unified:"1F9A7",shortnames:["orangutan"]},{unified:"1F436",shortnames:["dog"]},{unified:"1F415",shortnames:["dog2"]},{unified:"1F9AE",shortnames:["guide_dog"]},{unified:"1F415-200D-1F9BA",shortnames:["service_dog"]},{unified:"1F429",shortnames:["poodle"]},{unified:"1F43A",shortnames:["wolf"]},{unified:"1F98A",shortnames:["fox_face"]},{unified:"1F99D",shortnames:["raccoon"]},{unified:"1F431",shortnames:["cat"]},{unified:"1F408",shortnames:["cat2"]},{unified:"1F408-200D-2B1B",shortnames:["black_cat"]},{unified:"1F981",shortnames:["lion_face"]},{unified:"1F42F",shortnames:["tiger"]},{unified:"1F405",shortnames:["tiger2"]},{unified:"1F406",shortnames:["leopard"]},{unified:"1F434",shortnames:["horse"]},{unified:"1F40E",shortnames:["racehorse"]},{unified:"1F984",shortnames:["unicorn_face"]},{unified:"1F993",shortnames:["zebra_face"]},{unified:"1F98C",shortnames:["deer"]},{unified:"1F9AC",shortnames:["bison"]},{unified:"1F42E",shortnames:["cow"]},{unified:"1F402",shortnames:["ox"]},{unified:"1F403",shortnames:["water_buffalo"]},{unified:"1F404",shortnames:["cow2"]},{unified:"1F437",shortnames:["pig"]},{unified:"1F416",shortnames:["pig2"]},{unified:"1F417",shortnames:["boar"]},{unified:"1F43D",shortnames:["pig_nose"]},{unified:"1F40F",shortnames:["ram"]},{unified:"1F411",shortnames:["sheep"]},{unified:"1F410",shortnames:["goat"]},{unified:"1F42A",shortnames:["dromedary_camel"]},{unified:"1F42B",shortnames:["camel"]},{unified:"1F999",shortnames:["llama"]},{unified:"1F992",shortnames:["giraffe_face"]},{unified:"1F418",shortnames:["elephant"]},{unified:"1F9A3",shortnames:["mammoth"]},{unified:"1F98F",shortnames:["rhinoceros"]},{unified:"1F99B",shortnames:["hippopotamus"]},{unified:"1F42D",shortnames:["mouse"]},{unified:"1F401",shortnames:["mouse2"]},{unified:"1F400",shortnames:["rat"]},{unified:"1F439",shortnames:["hamster"]},{unified:"1F430",shortnames:["rabbit"]},{unified:"1F407",shortnames:["rabbit2"]},{unified:"1F43F-FE0F",shortnames:["chipmunk"]},{unified:"1F9AB",shortnames:["beaver"]},{unified:"1F994",shortnames:["hedgehog"]},{unified:"1F987",shortnames:["bat"]},{unified:"1F43B",shortnames:["bear"]},{unified:"1F43B-200D-2744-FE0F",shortnames:["polar_bear"]},{unified:"1F428",shortnames:["koala"]},{unified:"1F43C",shortnames:["panda_face"]},{unified:"1F9A5",shortnames:["sloth"]},{unified:"1F9A6",shortnames:["otter"]},{unified:"1F9A8",shortnames:["skunk"]},{unified:"1F998",shortnames:["kangaroo"]},{unified:"1F9A1",shortnames:["badger"]},{unified:"1F43E",shortnames:["feet"]},{unified:"1F983",shortnames:["turkey"]},{unified:"1F414",shortnames:["chicken"]},{unified:"1F413",shortnames:["rooster"]},{unified:"1F423",shortnames:["hatching_chick"]},{unified:"1F424",shortnames:["baby_chick"]},{unified:"1F425",shortnames:["hatched_chick"]},{unified:"1F426",shortnames:["bird"]},{unified:"1F427",shortnames:["penguin"]},{unified:"1F54A-FE0F",shortnames:["dove_of_peace"]},{unified:"1F985",shortnames:["eagle"]},{unified:"1F986",shortnames:["duck"]},{unified:"1F9A2",shortnames:["swan"]},{unified:"1F989",shortnames:["owl"]},{unified:"1F9A4",shortnames:["dodo"]},{unified:"1FAB6",shortnames:["feather"]},{unified:"1F9A9",shortnames:["flamingo"]},{unified:"1F99A",shortnames:["peacock"]},{unified:"1F99C",shortnames:["parrot"]},{unified:"1F438",shortnames:["frog"]},{unified:"1F40A",shortnames:["crocodile"]},{unified:"1F422",shortnames:["turtle"]},{unified:"1F98E",shortnames:["lizard"]},{unified:"1F40D",shortnames:["snake"]},{unified:"1F432",shortnames:["dragon_face"]},{unified:"1F409",shortnames:["dragon"]},{unified:"1F995",shortnames:["sauropod"]},{unified:"1F996",shortnames:["t-rex"]},{unified:"1F433",shortnames:["whale"]},{unified:"1F40B",shortnames:["whale2"]},{unified:"1F42C",shortnames:["dolphin"]},{unified:"1F9AD",shortnames:["seal"]},{unified:"1F41F",shortnames:["fish"]},{unified:"1F420",shortnames:["tropical_fish"]},{unified:"1F421",shortnames:["blowfish"]},{unified:"1F988",shortnames:["shark"]},{unified:"1F419",shortnames:["octopus"]},{unified:"1F41A",shortnames:["shell"]},{unified:"1FAB8",shortnames:["coral"]},{unified:"1F40C",shortnames:["snail"]},{unified:"1F98B",shortnames:["butterfly"]},{unified:"1F41B",shortnames:["bug"]},{unified:"1F41C",shortnames:["ant"]},{unified:"1F41D",shortnames:["bee"]},{unified:"1FAB2",shortnames:["beetle"]},{unified:"1F41E",shortnames:["ladybug"]},{unified:"1F997",shortnames:["cricket"]},{unified:"1FAB3",shortnames:["cockroach"]},{unified:"1F577-FE0F",shortnames:["spider"]},{unified:"1F578-FE0F",shortnames:["spider_web"]},{unified:"1F982",shortnames:["scorpion"]},{unified:"1F99F",shortnames:["mosquito"]},{unified:"1FAB0",shortnames:["fly"]},{unified:"1FAB1",shortnames:["worm"]},{unified:"1F9A0",shortnames:["microbe"]},{unified:"1F490",shortnames:["bouquet"]},{unified:"1F338",shortnames:["cherry_blossom"]},{unified:"1F4AE",shortnames:["white_flower"]},{unified:"1FAB7",shortnames:["lotus"]},{unified:"1F3F5-FE0F",shortnames:["rosette"]},{unified:"1F339",shortnames:["rose"]},{unified:"1F940",shortnames:["wilted_flower"]},{unified:"1F33A",shortnames:["hibiscus"]},{unified:"1F33B",shortnames:["sunflower"]},{unified:"1F33C",shortnames:["blossom"]},{unified:"1F337",shortnames:["tulip"]},{unified:"1F331",shortnames:["seedling"]},{unified:"1FAB4",shortnames:["potted_plant"]},{unified:"1F332",shortnames:["evergreen_tree"]},{unified:"1F333",shortnames:["deciduous_tree"]},{unified:"1F334",shortnames:["palm_tree"]},{unified:"1F335",shortnames:["cactus"]},{unified:"1F33E",shortnames:["ear_of_rice"]},{unified:"1F33F",shortnames:["herb"]},{unified:"2618-FE0F",shortnames:["shamrock"]},{unified:"1F340",shortnames:["four_leaf_clover"]},{unified:"1F341",shortnames:["maple_leaf"]},{unified:"1F342",shortnames:["fallen_leaf"]},{unified:"1F343",shortnames:["leaves"]},{unified:"1FAB9",shortnames:["empty_nest"]},{unified:"1FABA",shortnames:["nest_with_eggs"]}]},{name:"Food & Drink",emojis:[{unified:"1F347",shortnames:["grapes"]},{unified:"1F348",shortnames:["melon"]},{unified:"1F349",shortnames:["watermelon"]},{unified:"1F34A",shortnames:["tangerine"]},{unified:"1F34B",shortnames:["lemon"]},{unified:"1F34C",shortnames:["banana"]},{unified:"1F34D",shortnames:["pineapple"]},{unified:"1F96D",shortnames:["mango"]},{unified:"1F34E",shortnames:["apple"]},{unified:"1F34F",shortnames:["green_apple"]},{unified:"1F350",shortnames:["pear"]},{unified:"1F351",shortnames:["peach"]},{unified:"1F352",shortnames:["cherries"]},{unified:"1F353",shortnames:["strawberry"]},{unified:"1FAD0",shortnames:["blueberries"]},{unified:"1F95D",shortnames:["kiwifruit"]},{unified:"1F345",shortnames:["tomato"]},{unified:"1FAD2",shortnames:["olive"]},{unified:"1F965",shortnames:["coconut"]},{unified:"1F951",shortnames:["avocado"]},{unified:"1F346",shortnames:["eggplant"]},{unified:"1F954",shortnames:["potato"]},{unified:"1F955",shortnames:["carrot"]},{unified:"1F33D",shortnames:["corn"]},{unified:"1F336-FE0F",shortnames:["hot_pepper"]},{unified:"1FAD1",shortnames:["bell_pepper"]},{unified:"1F952",shortnames:["cucumber"]},{unified:"1F96C",shortnames:["leafy_green"]},{unified:"1F966",shortnames:["broccoli"]},{unified:"1F9C4",shortnames:["garlic"]},{unified:"1F9C5",shortnames:["onion"]},{unified:"1F344",shortnames:["mushroom"]},{unified:"1F95C",shortnames:["peanuts"]},{unified:"1FAD8",shortnames:["beans"]},{unified:"1F330",shortnames:["chestnut"]},{unified:"1F35E",shortnames:["bread"]},{unified:"1F950",shortnames:["croissant"]},{unified:"1F956",shortnames:["baguette_bread"]},{unified:"1FAD3",shortnames:["flatbread"]},{unified:"1F968",shortnames:["pretzel"]},{unified:"1F96F",shortnames:["bagel"]},{unified:"1F95E",shortnames:["pancakes"]},{unified:"1F9C7",shortnames:["waffle"]},{unified:"1F9C0",shortnames:["cheese_wedge"]},{unified:"1F356",shortnames:["meat_on_bone"]},{unified:"1F357",shortnames:["poultry_leg"]},{unified:"1F969",shortnames:["cut_of_meat"]},{unified:"1F953",shortnames:["bacon"]},{unified:"1F354",shortnames:["hamburger"]},{unified:"1F35F",shortnames:["fries"]},{unified:"1F355",shortnames:["pizza"]},{unified:"1F32D",shortnames:["hotdog"]},{unified:"1F96A",shortnames:["sandwich"]},{unified:"1F32E",shortnames:["taco"]},{unified:"1F32F",shortnames:["burrito"]},{unified:"1FAD4",shortnames:["tamale"]},{unified:"1F959",shortnames:["stuffed_flatbread"]},{unified:"1F9C6",shortnames:["falafel"]},{unified:"1F95A",shortnames:["egg"]},{unified:"1F373",shortnames:["fried_egg"]},{unified:"1F958",shortnames:["shallow_pan_of_food"]},{unified:"1F372",shortnames:["stew"]},{unified:"1FAD5",shortnames:["fondue"]},{unified:"1F963",shortnames:["bowl_with_spoon"]},{unified:"1F957",shortnames:["green_salad"]},{unified:"1F37F",shortnames:["popcorn"]},{unified:"1F9C8",shortnames:["butter"]},{unified:"1F9C2",shortnames:["salt"]},{unified:"1F96B",shortnames:["canned_food"]},{unified:"1F371",shortnames:["bento"]},{unified:"1F358",shortnames:["rice_cracker"]},{unified:"1F359",shortnames:["rice_ball"]},{unified:"1F35A",shortnames:["rice"]},{unified:"1F35B",shortnames:["curry"]},{unified:"1F35C",shortnames:["ramen"]},{unified:"1F35D",shortnames:["spaghetti"]},{unified:"1F360",shortnames:["sweet_potato"]},{unified:"1F362",shortnames:["oden"]},{unified:"1F363",shortnames:["sushi"]},{unified:"1F364",shortnames:["fried_shrimp"]},{unified:"1F365",shortnames:["fish_cake"]},{unified:"1F96E",shortnames:["moon_cake"]},{unified:"1F361",shortnames:["dango"]},{unified:"1F95F",shortnames:["dumpling"]},{unified:"1F960",shortnames:["fortune_cookie"]},{unified:"1F961",shortnames:["takeout_box"]},{unified:"1F980",shortnames:["crab"]},{unified:"1F99E",shortnames:["lobster"]},{unified:"1F990",shortnames:["shrimp"]},{unified:"1F991",shortnames:["squid"]},{unified:"1F9AA",shortnames:["oyster"]},{unified:"1F366",shortnames:["icecream"]},{unified:"1F367",shortnames:["shaved_ice"]},{unified:"1F368",shortnames:["ice_cream"]},{unified:"1F369",shortnames:["doughnut"]},{unified:"1F36A",shortnames:["cookie"]},{unified:"1F382",shortnames:["birthday"]},{unified:"1F370",shortnames:["cake"]},{unified:"1F9C1",shortnames:["cupcake"]},{unified:"1F967",shortnames:["pie"]},{unified:"1F36B",shortnames:["chocolate_bar"]},{unified:"1F36C",shortnames:["candy"]},{unified:"1F36D",shortnames:["lollipop"]},{unified:"1F36E",shortnames:["custard"]},{unified:"1F36F",shortnames:["honey_pot"]},{unified:"1F37C",shortnames:["baby_bottle"]},{unified:"1F95B",shortnames:["glass_of_milk"]},{unified:"2615",shortnames:["coffee"]},{unified:"1FAD6",shortnames:["teapot"]},{unified:"1F375",shortnames:["tea"]},{unified:"1F376",shortnames:["sake"]},{unified:"1F37E",shortnames:["champagne"]},{unified:"1F377",shortnames:["wine_glass"]},{unified:"1F378",shortnames:["cocktail"]},{unified:"1F379",shortnames:["tropical_drink"]},{unified:"1F37A",shortnames:["beer"]},{unified:"1F37B",shortnames:["beers"]},{unified:"1F942",shortnames:["clinking_glasses"]},{unified:"1F943",shortnames:["tumbler_glass"]},{unified:"1FAD7",shortnames:["pouring_liquid"]},{unified:"1F964",shortnames:["cup_with_straw"]},{unified:"1F9CB",shortnames:["bubble_tea"]},{unified:"1F9C3",shortnames:["beverage_box"]},{unified:"1F9C9",shortnames:["mate_drink"]},{unified:"1F9CA",shortnames:["ice_cube"]},{unified:"1F962",shortnames:["chopsticks"]},{unified:"1F37D-FE0F",shortnames:["knife_fork_plate"]},{unified:"1F374",shortnames:["fork_and_knife"]},{unified:"1F944",shortnames:["spoon"]},{unified:"1F52A",shortnames:["hocho"]},{unified:"1FAD9",shortnames:["jar"]},{unified:"1F3FA",shortnames:["amphora"]}]},{name:"Travel & Places",emojis:[{unified:"1F30D",shortnames:["earth_africa"]},{unified:"1F30E",shortnames:["earth_americas"]},{unified:"1F30F",shortnames:["earth_asia"]},{unified:"1F310",shortnames:["globe_with_meridians"]},{unified:"1F5FA-FE0F",shortnames:["world_map"]},{unified:"1F5FE",shortnames:["japan"]},{unified:"1F9ED",shortnames:["compass"]},{unified:"1F3D4-FE0F",shortnames:["snow_capped_mountain"]},{unified:"26F0-FE0F",shortnames:["mountain"]},{unified:"1F30B",shortnames:["volcano"]},{unified:"1F5FB",shortnames:["mount_fuji"]},{unified:"1F3D5-FE0F",shortnames:["camping"]},{unified:"1F3D6-FE0F",shortnames:["beach_with_umbrella"]},{unified:"1F3DC-FE0F",shortnames:["desert"]},{unified:"1F3DD-FE0F",shortnames:["desert_island"]},{unified:"1F3DE-FE0F",shortnames:["national_park"]},{unified:"1F3DF-FE0F",shortnames:["stadium"]},{unified:"1F3DB-FE0F",shortnames:["classical_building"]},{unified:"1F3D7-FE0F",shortnames:["building_construction"]},{unified:"1F9F1",shortnames:["bricks"]},{unified:"1FAA8",shortnames:["rock"]},{unified:"1FAB5",shortnames:["wood"]},{unified:"1F6D6",shortnames:["hut"]},{unified:"1F3D8-FE0F",shortnames:["house_buildings"]},{unified:"1F3DA-FE0F",shortnames:["derelict_house_building"]},{unified:"1F3E0",shortnames:["house"]},{unified:"1F3E1",shortnames:["house_with_garden"]},{unified:"1F3E2",shortnames:["office"]},{unified:"1F3E3",shortnames:["post_office"]},{unified:"1F3E4",shortnames:["european_post_office"]},{unified:"1F3E5",shortnames:["hospital"]},{unified:"1F3E6",shortnames:["bank"]},{unified:"1F3E8",shortnames:["hotel"]},{unified:"1F3E9",shortnames:["love_hotel"]},{unified:"1F3EA",shortnames:["convenience_store"]},{unified:"1F3EB",shortnames:["school"]},{unified:"1F3EC",shortnames:["department_store"]},{unified:"1F3ED",shortnames:["factory"]},{unified:"1F3EF",shortnames:["japanese_castle"]},{unified:"1F3F0",shortnames:["european_castle"]},{unified:"1F492",shortnames:["wedding"]},{unified:"1F5FC",shortnames:["tokyo_tower"]},{unified:"1F5FD",shortnames:["statue_of_liberty"]},{unified:"26EA",shortnames:["church"]},{unified:"1F54C",shortnames:["mosque"]},{unified:"1F6D5",shortnames:["hindu_temple"]},{unified:"1F54D",shortnames:["synagogue"]},{unified:"26E9-FE0F",shortnames:["shinto_shrine"]},{unified:"1F54B",shortnames:["kaaba"]},{unified:"26F2",shortnames:["fountain"]},{unified:"26FA",shortnames:["tent"]},{unified:"1F301",shortnames:["foggy"]},{unified:"1F303",shortnames:["night_with_stars"]},{unified:"1F3D9-FE0F",shortnames:["cityscape"]},{unified:"1F304",shortnames:["sunrise_over_mountains"]},{unified:"1F305",shortnames:["sunrise"]},{unified:"1F306",shortnames:["city_sunset"]},{unified:"1F307",shortnames:["city_sunrise"]},{unified:"1F309",shortnames:["bridge_at_night"]},{unified:"2668-FE0F",shortnames:["hotsprings"]},{unified:"1F3A0",shortnames:["carousel_horse"]},{unified:"1F6DD",shortnames:["playground_slide"]},{unified:"1F3A1",shortnames:["ferris_wheel"]},{unified:"1F3A2",shortnames:["roller_coaster"]},{unified:"1F488",shortnames:["barber"]},{unified:"1F3AA",shortnames:["circus_tent"]},{unified:"1F682",shortnames:["steam_locomotive"]},{unified:"1F683",shortnames:["railway_car"]},{unified:"1F684",shortnames:["bullettrain_side"]},{unified:"1F685",shortnames:["bullettrain_front"]},{unified:"1F686",shortnames:["train2"]},{unified:"1F687",shortnames:["metro"]},{unified:"1F688",shortnames:["light_rail"]},{unified:"1F689",shortnames:["station"]},{unified:"1F68A",shortnames:["tram"]},{unified:"1F69D",shortnames:["monorail"]},{unified:"1F69E",shortnames:["mountain_railway"]},{unified:"1F68B",shortnames:["train"]},{unified:"1F68C",shortnames:["bus"]},{unified:"1F68D",shortnames:["oncoming_bus"]},{unified:"1F68E",shortnames:["trolleybus"]},{unified:"1F690",shortnames:["minibus"]},{unified:"1F691",shortnames:["ambulance"]},{unified:"1F692",shortnames:["fire_engine"]},{unified:"1F693",shortnames:["police_car"]},{unified:"1F694",shortnames:["oncoming_police_car"]},{unified:"1F695",shortnames:["taxi"]},{unified:"1F696",shortnames:["oncoming_taxi"]},{unified:"1F697",shortnames:["car"]},{unified:"1F698",shortnames:["oncoming_automobile"]},{unified:"1F699",shortnames:["blue_car"]},{unified:"1F6FB",shortnames:["pickup_truck"]},{unified:"1F69A",shortnames:["truck"]},{unified:"1F69B",shortnames:["articulated_lorry"]},{unified:"1F69C",shortnames:["tractor"]},{unified:"1F3CE-FE0F",shortnames:["racing_car"]},{unified:"1F3CD-FE0F",shortnames:["racing_motorcycle"]},{unified:"1F6F5",shortnames:["motor_scooter"]},{unified:"1F9BD",shortnames:["manual_wheelchair"]},{unified:"1F9BC",shortnames:["motorized_wheelchair"]},{unified:"1F6FA",shortnames:["auto_rickshaw"]},{unified:"1F6B2",shortnames:["bike"]},{unified:"1F6F4",shortnames:["scooter"]},{unified:"1F6F9",shortnames:["skateboard"]},{unified:"1F6FC",shortnames:["roller_skate"]},{unified:"1F68F",shortnames:["busstop"]},{unified:"1F6E3-FE0F",shortnames:["motorway"]},{unified:"1F6E4-FE0F",shortnames:["railway_track"]},{unified:"1F6E2-FE0F",shortnames:["oil_drum"]},{unified:"26FD",shortnames:["fuelpump"]},{unified:"1F6DE",shortnames:["wheel"]},{unified:"1F6A8",shortnames:["rotating_light"]},{unified:"1F6A5",shortnames:["traffic_light"]},{unified:"1F6A6",shortnames:["vertical_traffic_light"]},{unified:"1F6D1",shortnames:["octagonal_sign"]},{unified:"1F6A7",shortnames:["construction"]},{unified:"2693",shortnames:["anchor"]},{unified:"1F6DF",shortnames:["ring_buoy"]},{unified:"26F5",shortnames:["boat"]},{unified:"1F6F6",shortnames:["canoe"]},{unified:"1F6A4",shortnames:["speedboat"]},{unified:"1F6F3-FE0F",shortnames:["passenger_ship"]},{unified:"26F4-FE0F",shortnames:["ferry"]},{unified:"1F6E5-FE0F",shortnames:["motor_boat"]},{unified:"1F6A2",shortnames:["ship"]},{unified:"2708-FE0F",shortnames:["airplane"]},{unified:"1F6E9-FE0F",shortnames:["small_airplane"]},{unified:"1F6EB",shortnames:["airplane_departure"]},{unified:"1F6EC",shortnames:["airplane_arriving"]},{unified:"1FA82",shortnames:["parachute"]},{unified:"1F4BA",shortnames:["seat"]},{unified:"1F681",shortnames:["helicopter"]},{unified:"1F69F",shortnames:["suspension_railway"]},{unified:"1F6A0",shortnames:["mountain_cableway"]},{unified:"1F6A1",shortnames:["aerial_tramway"]},{unified:"1F6F0-FE0F",shortnames:["satellite"]},{unified:"1F680",shortnames:["rocket"]},{unified:"1F6F8",shortnames:["flying_saucer"]},{unified:"1F6CE-FE0F",shortnames:["bellhop_bell"]},{unified:"1F9F3",shortnames:["luggage"]},{unified:"231B",shortnames:["hourglass"]},{unified:"23F3",shortnames:["hourglass_flowing_sand"]},{unified:"231A",shortnames:["watch"]},{unified:"23F0",shortnames:["alarm_clock"]},{unified:"23F1-FE0F",shortnames:["stopwatch"]},{unified:"23F2-FE0F",shortnames:["timer_clock"]},{unified:"1F570-FE0F",shortnames:["mantelpiece_clock"]},{unified:"1F55B",shortnames:["clock12"]},{unified:"1F567",shortnames:["clock1230"]},{unified:"1F550",shortnames:["clock1"]},{unified:"1F55C",shortnames:["clock130"]},{unified:"1F551",shortnames:["clock2"]},{unified:"1F55D",shortnames:["clock230"]},{unified:"1F552",shortnames:["clock3"]},{unified:"1F55E",shortnames:["clock330"]},{unified:"1F553",shortnames:["clock4"]},{unified:"1F55F",shortnames:["clock430"]},{unified:"1F554",shortnames:["clock5"]},{unified:"1F560",shortnames:["clock530"]},{unified:"1F555",shortnames:["clock6"]},{unified:"1F561",shortnames:["clock630"]},{unified:"1F556",shortnames:["clock7"]},{unified:"1F562",shortnames:["clock730"]},{unified:"1F557",shortnames:["clock8"]},{unified:"1F563",shortnames:["clock830"]},{unified:"1F558",shortnames:["clock9"]},{unified:"1F564",shortnames:["clock930"]},{unified:"1F559",shortnames:["clock10"]},{unified:"1F565",shortnames:["clock1030"]},{unified:"1F55A",shortnames:["clock11"]},{unified:"1F566",shortnames:["clock1130"]},{unified:"1F311",shortnames:["new_moon"]},{unified:"1F312",shortnames:["waxing_crescent_moon"]},{unified:"1F313",shortnames:["first_quarter_moon"]},{unified:"1F314",shortnames:["moon"]},{unified:"1F315",shortnames:["full_moon"]},{unified:"1F316",shortnames:["waning_gibbous_moon"]},{unified:"1F317",shortnames:["last_quarter_moon"]},{unified:"1F318",shortnames:["waning_crescent_moon"]},{unified:"1F319",shortnames:["crescent_moon"]},{unified:"1F31A",shortnames:["new_moon_with_face"]},{unified:"1F31B",shortnames:["first_quarter_moon_with_face"]},{unified:"1F31C",shortnames:["last_quarter_moon_with_face"]},{unified:"1F321-FE0F",shortnames:["thermometer"]},{unified:"2600-FE0F",shortnames:["sunny"]},{unified:"1F31D",shortnames:["full_moon_with_face"]},{unified:"1F31E",shortnames:["sun_with_face"]},{unified:"1FA90",shortnames:["ringed_planet"]},{unified:"2B50",shortnames:["star"]},{unified:"1F31F",shortnames:["star2"]},{unified:"1F320",shortnames:["stars"]},{unified:"1F30C",shortnames:["milky_way"]},{unified:"2601-FE0F",shortnames:["cloud"]},{unified:"26C5",shortnames:["partly_sunny"]},{unified:"26C8-FE0F",shortnames:["thunder_cloud_and_rain"]},{unified:"1F324-FE0F",shortnames:["mostly_sunny"]},{unified:"1F325-FE0F",shortnames:["barely_sunny"]},{unified:"1F326-FE0F",shortnames:["partly_sunny_rain"]},{unified:"1F327-FE0F",shortnames:["rain_cloud"]},{unified:"1F328-FE0F",shortnames:["snow_cloud"]},{unified:"1F329-FE0F",shortnames:["lightning"]},{unified:"1F32A-FE0F",shortnames:["tornado"]},{unified:"1F32B-FE0F",shortnames:["fog"]},{unified:"1F32C-FE0F",shortnames:["wind_blowing_face"]},{unified:"1F300",shortnames:["cyclone"]},{unified:"1F308",shortnames:["rainbow"]},{unified:"1F302",shortnames:["closed_umbrella"]},{unified:"2602-FE0F",shortnames:["umbrella"]},{unified:"2614",shortnames:["umbrella_with_rain_drops"]},{unified:"26F1-FE0F",shortnames:["umbrella_on_ground"]},{unified:"26A1",shortnames:["zap"]},{unified:"2744-FE0F",shortnames:["snowflake"]},{unified:"2603-FE0F",shortnames:["snowman"]},{unified:"26C4",shortnames:["snowman_without_snow"]},{unified:"2604-FE0F",shortnames:["comet"]},{unified:"1F525",shortnames:["fire"]},{unified:"1F4A7",shortnames:["droplet"]},{unified:"1F30A",shortnames:["ocean"]}]},{name:"Activities",emojis:[{unified:"1F383",shortnames:["jack_o_lantern"]},{unified:"1F384",shortnames:["christmas_tree"]},{unified:"1F386",shortnames:["fireworks"]},{unified:"1F387",shortnames:["sparkler"]},{unified:"1F9E8",shortnames:["firecracker"]},{unified:"2728",shortnames:["sparkles"]},{unified:"1F388",shortnames:["balloon"]},{unified:"1F389",shortnames:["tada"]},{unified:"1F38A",shortnames:["confetti_ball"]},{unified:"1F38B",shortnames:["tanabata_tree"]},{unified:"1F38D",shortnames:["bamboo"]},{unified:"1F38E",shortnames:["dolls"]},{unified:"1F38F",shortnames:["flags"]},{unified:"1F390",shortnames:["wind_chime"]},{unified:"1F391",shortnames:["rice_scene"]},{unified:"1F9E7",shortnames:["red_envelope"]},{unified:"1F380",shortnames:["ribbon"]},{unified:"1F381",shortnames:["gift"]},{unified:"1F397-FE0F",shortnames:["reminder_ribbon"]},{unified:"1F39F-FE0F",shortnames:["admission_tickets"]},{unified:"1F3AB",shortnames:["ticket"]},{unified:"1F396-FE0F",shortnames:["medal"]},{unified:"1F3C6",shortnames:["trophy"]},{unified:"1F3C5",shortnames:["sports_medal"]},{unified:"1F947",shortnames:["first_place_medal"]},{unified:"1F948",shortnames:["second_place_medal"]},{unified:"1F949",shortnames:["third_place_medal"]},{unified:"26BD",shortnames:["soccer"]},{unified:"26BE",shortnames:["baseball"]},{unified:"1F94E",shortnames:["softball"]},{unified:"1F3C0",shortnames:["basketball"]},{unified:"1F3D0",shortnames:["volleyball"]},{unified:"1F3C8",shortnames:["football"]},{unified:"1F3C9",shortnames:["rugby_football"]},{unified:"1F3BE",shortnames:["tennis"]},{unified:"1F94F",shortnames:["flying_disc"]},{unified:"1F3B3",shortnames:["bowling"]},{unified:"1F3CF",shortnames:["cricket_bat_and_ball"]},{unified:"1F3D1",shortnames:["field_hockey_stick_and_ball"]},{unified:"1F3D2",shortnames:["ice_hockey_stick_and_puck"]},{unified:"1F94D",shortnames:["lacrosse"]},{unified:"1F3D3",shortnames:["table_tennis_paddle_and_ball"]},{unified:"1F3F8",shortnames:["badminton_racquet_and_shuttlecock"]},{unified:"1F94A",shortnames:["boxing_glove"]},{unified:"1F94B",shortnames:["martial_arts_uniform"]},{unified:"1F945",shortnames:["goal_net"]},{unified:"26F3",shortnames:["golf"]},{unified:"26F8-FE0F",shortnames:["ice_skate"]},{unified:"1F3A3",shortnames:["fishing_pole_and_fish"]},{unified:"1F93F",shortnames:["diving_mask"]},{unified:"1F3BD",shortnames:["running_shirt_with_sash"]},{unified:"1F3BF",shortnames:["ski"]},{unified:"1F6F7",shortnames:["sled"]},{unified:"1F94C",shortnames:["curling_stone"]},{unified:"1F3AF",shortnames:["dart"]},{unified:"1FA80",shortnames:["yo-yo"]},{unified:"1FA81",shortnames:["kite"]},{unified:"1F3B1",shortnames:["8ball"]},{unified:"1F52E",shortnames:["crystal_ball"]},{unified:"1FA84",shortnames:["magic_wand"]},{unified:"1F9FF",shortnames:["nazar_amulet"]},{unified:"1FAAC",shortnames:["hamsa"]},{unified:"1F3AE",shortnames:["video_game"]},{unified:"1F579-FE0F",shortnames:["joystick"]},{unified:"1F3B0",shortnames:["slot_machine"]},{unified:"1F3B2",shortnames:["game_die"]},{unified:"1F9E9",shortnames:["jigsaw"]},{unified:"1F9F8",shortnames:["teddy_bear"]},{unified:"1FA85",shortnames:["pinata"]},{unified:"1FAA9",shortnames:["mirror_ball"]},{unified:"1FA86",shortnames:["nesting_dolls"]},{unified:"2660-FE0F",shortnames:["spades"]},{unified:"2665-FE0F",shortnames:["hearts"]},{unified:"2666-FE0F",shortnames:["diamonds"]},{unified:"2663-FE0F",shortnames:["clubs"]},{unified:"265F-FE0F",shortnames:["chess_pawn"]},{unified:"1F0CF",shortnames:["black_joker"]},{unified:"1F004",shortnames:["mahjong"]},{unified:"1F3B4",shortnames:["flower_playing_cards"]},{unified:"1F3AD",shortnames:["performing_arts"]},{unified:"1F5BC-FE0F",shortnames:["frame_with_picture"]},{unified:"1F3A8",shortnames:["art"]},{unified:"1F9F5",shortnames:["thread"]},{unified:"1FAA1",shortnames:["sewing_needle"]},{unified:"1F9F6",shortnames:["yarn"]},{unified:"1FAA2",shortnames:["knot"]}]},{name:"Objects",emojis:[{unified:"1F453",shortnames:["eyeglasses"]},{unified:"1F576-FE0F",shortnames:["dark_sunglasses"]},{unified:"1F97D",shortnames:["goggles"]},{unified:"1F97C",shortnames:["lab_coat"]},{unified:"1F9BA",shortnames:["safety_vest"]},{unified:"1F454",shortnames:["necktie"]},{unified:"1F455",shortnames:["shirt"]},{unified:"1F456",shortnames:["jeans"]},{unified:"1F9E3",shortnames:["scarf"]},{unified:"1F9E4",shortnames:["gloves"]},{unified:"1F9E5",shortnames:["coat"]},{unified:"1F9E6",shortnames:["socks"]},{unified:"1F457",shortnames:["dress"]},{unified:"1F458",shortnames:["kimono"]},{unified:"1F97B",shortnames:["sari"]},{unified:"1FA71",shortnames:["one-piece_swimsuit"]},{unified:"1FA72",shortnames:["briefs"]},{unified:"1FA73",shortnames:["shorts"]},{unified:"1F459",shortnames:["bikini"]},{unified:"1F45A",shortnames:["womans_clothes"]},{unified:"1F45B",shortnames:["purse"]},{unified:"1F45C",shortnames:["handbag"]},{unified:"1F45D",shortnames:["pouch"]},{unified:"1F6CD-FE0F",shortnames:["shopping_bags"]},{unified:"1F392",shortnames:["school_satchel"]},{unified:"1FA74",shortnames:["thong_sandal"]},{unified:"1F45E",shortnames:["mans_shoe"]},{unified:"1F45F",shortnames:["athletic_shoe"]},{unified:"1F97E",shortnames:["hiking_boot"]},{unified:"1F97F",shortnames:["womans_flat_shoe"]},{unified:"1F460",shortnames:["high_heel"]},{unified:"1F461",shortnames:["sandal"]},{unified:"1FA70",shortnames:["ballet_shoes"]},{unified:"1F462",shortnames:["boot"]},{unified:"1F451",shortnames:["crown"]},{unified:"1F452",shortnames:["womans_hat"]},{unified:"1F3A9",shortnames:["tophat"]},{unified:"1F393",shortnames:["mortar_board"]},{unified:"1F9E2",shortnames:["billed_cap"]},{unified:"1FA96",shortnames:["military_helmet"]},{unified:"26D1-FE0F",shortnames:["helmet_with_white_cross"]},{unified:"1F4FF",shortnames:["prayer_beads"]},{unified:"1F484",shortnames:["lipstick"]},{unified:"1F48D",shortnames:["ring"]},{unified:"1F48E",shortnames:["gem"]},{unified:"1F507",shortnames:["mute"]},{unified:"1F508",shortnames:["speaker"]},{unified:"1F509",shortnames:["sound"]},{unified:"1F50A",shortnames:["loud_sound"]},{unified:"1F4E2",shortnames:["loudspeaker"]},{unified:"1F4E3",shortnames:["mega"]},{unified:"1F4EF",shortnames:["postal_horn"]},{unified:"1F514",shortnames:["bell"]},{unified:"1F515",shortnames:["no_bell"]},{unified:"1F3BC",shortnames:["musical_score"]},{unified:"1F3B5",shortnames:["musical_note"]},{unified:"1F3B6",shortnames:["notes"]},{unified:"1F399-FE0F",shortnames:["studio_microphone"]},{unified:"1F39A-FE0F",shortnames:["level_slider"]},{unified:"1F39B-FE0F",shortnames:["control_knobs"]},{unified:"1F3A4",shortnames:["microphone"]},{unified:"1F3A7",shortnames:["headphones"]},{unified:"1F4FB",shortnames:["radio"]},{unified:"1F3B7",shortnames:["saxophone"]},{unified:"1FA97",shortnames:["accordion"]},{unified:"1F3B8",shortnames:["guitar"]},{unified:"1F3B9",shortnames:["musical_keyboard"]},{unified:"1F3BA",shortnames:["trumpet"]},{unified:"1F3BB",shortnames:["violin"]},{unified:"1FA95",shortnames:["banjo"]},{unified:"1F941",shortnames:["drum_with_drumsticks"]},{unified:"1FA98",shortnames:["long_drum"]},{unified:"1F4F1",shortnames:["iphone"]},{unified:"1F4F2",shortnames:["calling"]},{unified:"260E-FE0F",shortnames:["phone"]},{unified:"1F4DE",shortnames:["telephone_receiver"]},{unified:"1F4DF",shortnames:["pager"]},{unified:"1F4E0",shortnames:["fax"]},{unified:"1F50B",shortnames:["battery"]},{unified:"1FAAB",shortnames:["low_battery"]},{unified:"1F50C",shortnames:["electric_plug"]},{unified:"1F4BB",shortnames:["computer"]},{unified:"1F5A5-FE0F",shortnames:["desktop_computer"]},{unified:"1F5A8-FE0F",shortnames:["printer"]},{unified:"2328-FE0F",shortnames:["keyboard"]},{unified:"1F5B1-FE0F",shortnames:["three_button_mouse"]},{unified:"1F5B2-FE0F",shortnames:["trackball"]},{unified:"1F4BD",shortnames:["minidisc"]},{unified:"1F4BE",shortnames:["floppy_disk"]},{unified:"1F4BF",shortnames:["cd"]},{unified:"1F4C0",shortnames:["dvd"]},{unified:"1F9EE",shortnames:["abacus"]},{unified:"1F3A5",shortnames:["movie_camera"]},{unified:"1F39E-FE0F",shortnames:["film_frames"]},{unified:"1F4FD-FE0F",shortnames:["film_projector"]},{unified:"1F3AC",shortnames:["clapper"]},{unified:"1F4FA",shortnames:["tv"]},{unified:"1F4F7",shortnames:["camera"]},{unified:"1F4F8",shortnames:["camera_with_flash"]},{unified:"1F4F9",shortnames:["video_camera"]},{unified:"1F4FC",shortnames:["vhs"]},{unified:"1F50D",shortnames:["mag"]},{unified:"1F50E",shortnames:["mag_right"]},{unified:"1F56F-FE0F",shortnames:["candle"]},{unified:"1F4A1",shortnames:["bulb"]},{unified:"1F526",shortnames:["flashlight"]},{unified:"1F3EE",shortnames:["izakaya_lantern"]},{unified:"1FA94",shortnames:["diya_lamp"]},{unified:"1F4D4",shortnames:["notebook_with_decorative_cover"]},{unified:"1F4D5",shortnames:["closed_book"]},{unified:"1F4D6",shortnames:["book"]},{unified:"1F4D7",shortnames:["green_book"]},{unified:"1F4D8",shortnames:["blue_book"]},{unified:"1F4D9",shortnames:["orange_book"]},{unified:"1F4DA",shortnames:["books"]},{unified:"1F4D3",shortnames:["notebook"]},{unified:"1F4D2",shortnames:["ledger"]},{unified:"1F4C3",shortnames:["page_with_curl"]},{unified:"1F4DC",shortnames:["scroll"]},{unified:"1F4C4",shortnames:["page_facing_up"]},{unified:"1F4F0",shortnames:["newspaper"]},{unified:"1F5DE-FE0F",shortnames:["rolled_up_newspaper"]},{unified:"1F4D1",shortnames:["bookmark_tabs"]},{unified:"1F516",shortnames:["bookmark"]},{unified:"1F3F7-FE0F",shortnames:["label"]},{unified:"1F4B0",shortnames:["moneybag"]},{unified:"1FA99",shortnames:["coin"]},{unified:"1F4B4",shortnames:["yen"]},{unified:"1F4B5",shortnames:["dollar"]},{unified:"1F4B6",shortnames:["euro"]},{unified:"1F4B7",shortnames:["pound"]},{unified:"1F4B8",shortnames:["money_with_wings"]},{unified:"1F4B3",shortnames:["credit_card"]},{unified:"1F9FE",shortnames:["receipt"]},{unified:"1F4B9",shortnames:["chart"]},{unified:"2709-FE0F",shortnames:["email"]},{unified:"1F4E7",shortnames:["e-mail"]},{unified:"1F4E8",shortnames:["incoming_envelope"]},{unified:"1F4E9",shortnames:["envelope_with_arrow"]},{unified:"1F4E4",shortnames:["outbox_tray"]},{unified:"1F4E5",shortnames:["inbox_tray"]},{unified:"1F4E6",shortnames:["package"]},{unified:"1F4EB",shortnames:["mailbox"]},{unified:"1F4EA",shortnames:["mailbox_closed"]},{unified:"1F4EC",shortnames:["mailbox_with_mail"]},{unified:"1F4ED",shortnames:["mailbox_with_no_mail"]},{unified:"1F4EE",shortnames:["postbox"]},{unified:"1F5F3-FE0F",shortnames:["ballot_box_with_ballot"]},{unified:"270F-FE0F",shortnames:["pencil2"]},{unified:"2712-FE0F",shortnames:["black_nib"]},{unified:"1F58B-FE0F",shortnames:["lower_left_fountain_pen"]},{unified:"1F58A-FE0F",shortnames:["lower_left_ballpoint_pen"]},{unified:"1F58C-FE0F",shortnames:["lower_left_paintbrush"]},{unified:"1F58D-FE0F",shortnames:["lower_left_crayon"]},{unified:"1F4DD",shortnames:["memo"]},{unified:"1F4BC",shortnames:["briefcase"]},{unified:"1F4C1",shortnames:["file_folder"]},{unified:"1F4C2",shortnames:["open_file_folder"]},{unified:"1F5C2-FE0F",shortnames:["card_index_dividers"]},{unified:"1F4C5",shortnames:["date"]},{unified:"1F4C6",shortnames:["calendar"]},{unified:"1F5D2-FE0F",shortnames:["spiral_note_pad"]},{unified:"1F5D3-FE0F",shortnames:["spiral_calendar_pad"]},{unified:"1F4C7",shortnames:["card_index"]},{unified:"1F4C8",shortnames:["chart_with_upwards_trend"]},{unified:"1F4C9",shortnames:["chart_with_downwards_trend"]},{unified:"1F4CA",shortnames:["bar_chart"]},{unified:"1F4CB",shortnames:["clipboard"]},{unified:"1F4CC",shortnames:["pushpin"]},{unified:"1F4CD",shortnames:["round_pushpin"]},{unified:"1F4CE",shortnames:["paperclip"]},{unified:"1F587-FE0F",shortnames:["linked_paperclips"]},{unified:"1F4CF",shortnames:["straight_ruler"]},{unified:"1F4D0",shortnames:["triangular_ruler"]},{unified:"2702-FE0F",shortnames:["scissors"]},{unified:"1F5C3-FE0F",shortnames:["card_file_box"]},{unified:"1F5C4-FE0F",shortnames:["file_cabinet"]},{unified:"1F5D1-FE0F",shortnames:["wastebasket"]},{unified:"1F512",shortnames:["lock"]},{unified:"1F513",shortnames:["unlock"]},{unified:"1F50F",shortnames:["lock_with_ink_pen"]},{unified:"1F510",shortnames:["closed_lock_with_key"]},{unified:"1F511",shortnames:["key"]},{unified:"1F5DD-FE0F",shortnames:["old_key"]},{unified:"1F528",shortnames:["hammer"]},{unified:"1FA93",shortnames:["axe"]},{unified:"26CF-FE0F",shortnames:["pick"]},{unified:"2692-FE0F",shortnames:["hammer_and_pick"]},{unified:"1F6E0-FE0F",shortnames:["hammer_and_wrench"]},{unified:"1F5E1-FE0F",shortnames:["dagger_knife"]},{unified:"2694-FE0F",shortnames:["crossed_swords"]},{unified:"1F52B",shortnames:["gun"]},{unified:"1FA83",shortnames:["boomerang"]},{unified:"1F3F9",shortnames:["bow_and_arrow"]},{unified:"1F6E1-FE0F",shortnames:["shield"]},{unified:"1FA9A",shortnames:["carpentry_saw"]},{unified:"1F527",shortnames:["wrench"]},{unified:"1FA9B",shortnames:["screwdriver"]},{unified:"1F529",shortnames:["nut_and_bolt"]},{unified:"2699-FE0F",shortnames:["gear"]},{unified:"1F5DC-FE0F",shortnames:["compression"]},{unified:"2696-FE0F",shortnames:["scales"]},{unified:"1F9AF",shortnames:["probing_cane"]},{unified:"1F517",shortnames:["link"]},{unified:"26D3-FE0F",shortnames:["chains"]},{unified:"1FA9D",shortnames:["hook"]},{unified:"1F9F0",shortnames:["toolbox"]},{unified:"1F9F2",shortnames:["magnet"]},{unified:"1FA9C",shortnames:["ladder"]},{unified:"2697-FE0F",shortnames:["alembic"]},{unified:"1F9EA",shortnames:["test_tube"]},{unified:"1F9EB",shortnames:["petri_dish"]},{unified:"1F9EC",shortnames:["dna"]},{unified:"1F52C",shortnames:["microscope"]},{unified:"1F52D",shortnames:["telescope"]},{unified:"1F4E1",shortnames:["satellite_antenna"]},{unified:"1F489",shortnames:["syringe"]},{unified:"1FA78",shortnames:["drop_of_blood"]},{unified:"1F48A",shortnames:["pill"]},{unified:"1FA79",shortnames:["adhesive_bandage"]},{unified:"1FA7C",shortnames:["crutch"]},{unified:"1FA7A",shortnames:["stethoscope"]},{unified:"1FA7B",shortnames:["x-ray"]},{unified:"1F6AA",shortnames:["door"]},{unified:"1F6D7",shortnames:["elevator"]},{unified:"1FA9E",shortnames:["mirror"]},{unified:"1FA9F",shortnames:["window"]},{unified:"1F6CF-FE0F",shortnames:["bed"]},{unified:"1F6CB-FE0F",shortnames:["couch_and_lamp"]},{unified:"1FA91",shortnames:["chair"]},{unified:"1F6BD",shortnames:["toilet"]},{unified:"1FAA0",shortnames:["plunger"]},{unified:"1F6BF",shortnames:["shower"]},{unified:"1F6C1",shortnames:["bathtub"]},{unified:"1FAA4",shortnames:["mouse_trap"]},{unified:"1FA92",shortnames:["razor"]},{unified:"1F9F4",shortnames:["lotion_bottle"]},{unified:"1F9F7",shortnames:["safety_pin"]},{unified:"1F9F9",shortnames:["broom"]},{unified:"1F9FA",shortnames:["basket"]},{unified:"1F9FB",shortnames:["roll_of_paper"]},{unified:"1FAA3",shortnames:["bucket"]},{unified:"1F9FC",shortnames:["soap"]},{unified:"1FAE7",shortnames:["bubbles"]},{unified:"1FAA5",shortnames:["toothbrush"]},{unified:"1F9FD",shortnames:["sponge"]},{unified:"1F9EF",shortnames:["fire_extinguisher"]},{unified:"1F6D2",shortnames:["shopping_trolley"]},{unified:"1F6AC",shortnames:["smoking"]},{unified:"26B0-FE0F",shortnames:["coffin"]},{unified:"1FAA6",shortnames:["headstone"]},{unified:"26B1-FE0F",shortnames:["funeral_urn"]},{unified:"1F5FF",shortnames:["moyai"]},{unified:"1FAA7",shortnames:["placard"]},{unified:"1FAAA",shortnames:["identification_card"]}]},{name:"Symbols",emojis:[{unified:"1F3E7",shortnames:["atm"]},{unified:"1F6AE",shortnames:["put_litter_in_its_place"]},{unified:"1F6B0",shortnames:["potable_water"]},{unified:"267F",shortnames:["wheelchair"]},{unified:"1F6B9",shortnames:["mens"]},{unified:"1F6BA",shortnames:["womens"]},{unified:"1F6BB",shortnames:["restroom"]},{unified:"1F6BC",shortnames:["baby_symbol"]},{unified:"1F6BE",shortnames:["wc"]},{unified:"1F6C2",shortnames:["passport_control"]},{unified:"1F6C3",shortnames:["customs"]},{unified:"1F6C4",shortnames:["baggage_claim"]},{unified:"1F6C5",shortnames:["left_luggage"]},{unified:"26A0-FE0F",shortnames:["warning"]},{unified:"1F6B8",shortnames:["children_crossing"]},{unified:"26D4",shortnames:["no_entry"]},{unified:"1F6AB",shortnames:["no_entry_sign"]},{unified:"1F6B3",shortnames:["no_bicycles"]},{unified:"1F6AD",shortnames:["no_smoking"]},{unified:"1F6AF",shortnames:["do_not_litter"]},{unified:"1F6B1",shortnames:["non-potable_water"]},{unified:"1F6B7",shortnames:["no_pedestrians"]},{unified:"1F4F5",shortnames:["no_mobile_phones"]},{unified:"1F51E",shortnames:["underage"]},{unified:"2622-FE0F",shortnames:["radioactive_sign"]},{unified:"2623-FE0F",shortnames:["biohazard_sign"]},{unified:"2B06-FE0F",shortnames:["arrow_up"]},{unified:"2197-FE0F",shortnames:["arrow_upper_right"]},{unified:"27A1-FE0F",shortnames:["arrow_right"]},{unified:"2198-FE0F",shortnames:["arrow_lower_right"]},{unified:"2B07-FE0F",shortnames:["arrow_down"]},{unified:"2199-FE0F",shortnames:["arrow_lower_left"]},{unified:"2B05-FE0F",shortnames:["arrow_left"]},{unified:"2196-FE0F",shortnames:["arrow_upper_left"]},{unified:"2195-FE0F",shortnames:["arrow_up_down"]},{unified:"2194-FE0F",shortnames:["left_right_arrow"]},{unified:"21A9-FE0F",shortnames:["leftwards_arrow_with_hook"]},{unified:"21AA-FE0F",shortnames:["arrow_right_hook"]},{unified:"2934-FE0F",shortnames:["arrow_heading_up"]},{unified:"2935-FE0F",shortnames:["arrow_heading_down"]},{unified:"1F503",shortnames:["arrows_clockwise"]},{unified:"1F504",shortnames:["arrows_counterclockwise"]},{unified:"1F519",shortnames:["back"]},{unified:"1F51A",shortnames:["end"]},{unified:"1F51B",shortnames:["on"]},{unified:"1F51C",shortnames:["soon"]},{unified:"1F51D",shortnames:["top"]},{unified:"1F6D0",shortnames:["place_of_worship"]},{unified:"269B-FE0F",shortnames:["atom_symbol"]},{unified:"1F549-FE0F",shortnames:["om_symbol"]},{unified:"2721-FE0F",shortnames:["star_of_david"]},{unified:"2638-FE0F",shortnames:["wheel_of_dharma"]},{unified:"262F-FE0F",shortnames:["yin_yang"]},{unified:"271D-FE0F",shortnames:["latin_cross"]},{unified:"2626-FE0F",shortnames:["orthodox_cross"]},{unified:"262A-FE0F",shortnames:["star_and_crescent"]},{unified:"262E-FE0F",shortnames:["peace_symbol"]},{unified:"1F54E",shortnames:["menorah_with_nine_branches"]},{unified:"1F52F",shortnames:["six_pointed_star"]},{unified:"2648",shortnames:["aries"]},{unified:"2649",shortnames:["taurus"]},{unified:"264A",shortnames:["gemini"]},{unified:"264B",shortnames:["cancer"]},{unified:"264C",shortnames:["leo"]},{unified:"264D",shortnames:["virgo"]},{unified:"264E",shortnames:["libra"]},{unified:"264F",shortnames:["scorpius"]},{unified:"2650",shortnames:["sagittarius"]},{unified:"2651",shortnames:["capricorn"]},{unified:"2652",shortnames:["aquarius"]},{unified:"2653",shortnames:["pisces"]},{unified:"26CE",shortnames:["ophiuchus"]},{unified:"1F500",shortnames:["twisted_rightwards_arrows"]},{unified:"1F501",shortnames:["repeat"]},{unified:"1F502",shortnames:["repeat_one"]},{unified:"25B6-FE0F",shortnames:["arrow_forward"]},{unified:"23E9",shortnames:["fast_forward"]},{unified:"23ED-FE0F",shortnames:["black_right_pointing_double_triangle_with_vertical_bar"]},{unified:"23EF-FE0F",shortnames:["black_right_pointing_triangle_with_double_vertical_bar"]},{unified:"25C0-FE0F",shortnames:["arrow_backward"]},{unified:"23EA",shortnames:["rewind"]},{unified:"23EE-FE0F",shortnames:["black_left_pointing_double_triangle_with_vertical_bar"]},{unified:"1F53C",shortnames:["arrow_up_small"]},{unified:"23EB",shortnames:["arrow_double_up"]},{unified:"1F53D",shortnames:["arrow_down_small"]},{unified:"23EC",shortnames:["arrow_double_down"]},{unified:"23F8-FE0F",shortnames:["double_vertical_bar"]},{unified:"23F9-FE0F",shortnames:["black_square_for_stop"]},{unified:"23FA-FE0F",shortnames:["black_circle_for_record"]},{unified:"23CF-FE0F",shortnames:["eject"]},{unified:"1F3A6",shortnames:["cinema"]},{unified:"1F505",shortnames:["low_brightness"]},{unified:"1F506",shortnames:["high_brightness"]},{unified:"1F4F6",shortnames:["signal_strength"]},{unified:"1F4F3",shortnames:["vibration_mode"]},{unified:"1F4F4",shortnames:["mobile_phone_off"]},{unified:"2640-FE0F",shortnames:["female_sign"]},{unified:"2642-FE0F",shortnames:["male_sign"]},{unified:"26A7-FE0F",shortnames:["transgender_symbol"]},{unified:"2716-FE0F",shortnames:["heavy_multiplication_x"]},{unified:"2795",shortnames:["heavy_plus_sign"]},{unified:"2796",shortnames:["heavy_minus_sign"]},{unified:"2797",shortnames:["heavy_division_sign"]},{unified:"1F7F0",shortnames:["heavy_equals_sign"]},{unified:"267E-FE0F",shortnames:["infinity"]},{unified:"203C-FE0F",shortnames:["bangbang"]},{unified:"2049-FE0F",shortnames:["interrobang"]},{unified:"2753",shortnames:["question"]},{unified:"2754",shortnames:["grey_question"]},{unified:"2755",shortnames:["grey_exclamation"]},{unified:"2757",shortnames:["exclamation"]},{unified:"3030-FE0F",shortnames:["wavy_dash"]},{unified:"1F4B1",shortnames:["currency_exchange"]},{unified:"1F4B2",shortnames:["heavy_dollar_sign"]},{unified:"2695-FE0F",shortnames:["medical_symbol"]},{unified:"267B-FE0F",shortnames:["recycle"]},{unified:"269C-FE0F",shortnames:["fleur_de_lis"]},{unified:"1F531",shortnames:["trident"]},{unified:"1F4DB",shortnames:["name_badge"]},{unified:"1F530",shortnames:["beginner"]},{unified:"2B55",shortnames:["o"]},{unified:"2705",shortnames:["white_check_mark"]},{unified:"2611-FE0F",shortnames:["ballot_box_with_check"]},{unified:"2714-FE0F",shortnames:["heavy_check_mark"]},{unified:"274C",shortnames:["x"]},{unified:"274E",shortnames:["negative_squared_cross_mark"]},{unified:"27B0",shortnames:["curly_loop"]},{unified:"27BF",shortnames:["loop"]},{unified:"303D-FE0F",shortnames:["part_alternation_mark"]},{unified:"2733-FE0F",shortnames:["eight_spoked_asterisk"]},{unified:"2734-FE0F",shortnames:["eight_pointed_black_star"]},{unified:"2747-FE0F",shortnames:["sparkle"]},{unified:"00A9-FE0F",shortnames:["copyright"]},{unified:"00AE-FE0F",shortnames:["registered"]},{unified:"2122-FE0F",shortnames:["tm"]},{unified:"0023-FE0F-20E3",shortnames:["hash"]},{unified:"002A-FE0F-20E3",shortnames:["keycap_star"]},{unified:"0030-FE0F-20E3",shortnames:["zero"]},{unified:"0031-FE0F-20E3",shortnames:["one"]},{unified:"0032-FE0F-20E3",shortnames:["two"]},{unified:"0033-FE0F-20E3",shortnames:["three"]},{unified:"0034-FE0F-20E3",shortnames:["four"]},{unified:"0035-FE0F-20E3",shortnames:["five"]},{unified:"0036-FE0F-20E3",shortnames:["six"]},{unified:"0037-FE0F-20E3",shortnames:["seven"]},{unified:"0038-FE0F-20E3",shortnames:["eight"]},{unified:"0039-FE0F-20E3",shortnames:["nine"]},{unified:"1F51F",shortnames:["keycap_ten"]},{unified:"1F520",shortnames:["capital_abcd"]},{unified:"1F521",shortnames:["abcd"]},{unified:"1F522",shortnames:["1234"]},{unified:"1F523",shortnames:["symbols"]},{unified:"1F524",shortnames:["abc"]},{unified:"1F170-FE0F",shortnames:["a"]},{unified:"1F18E",shortnames:["ab"]},{unified:"1F171-FE0F",shortnames:["b"]},{unified:"1F191",shortnames:["cl"]},{unified:"1F192",shortnames:["cool"]},{unified:"1F193",shortnames:["free"]},{unified:"2139-FE0F",shortnames:["information_source"]},{unified:"1F194",shortnames:["id"]},{unified:"24C2-FE0F",shortnames:["m"]},{unified:"1F195",shortnames:["new"]},{unified:"1F196",shortnames:["ng"]},{unified:"1F17E-FE0F",shortnames:["o2"]},{unified:"1F197",shortnames:["ok"]},{unified:"1F17F-FE0F",shortnames:["parking"]},{unified:"1F198",shortnames:["sos"]},{unified:"1F199",shortnames:["up"]},{unified:"1F19A",shortnames:["vs"]},{unified:"1F201",shortnames:["koko"]},{unified:"1F202-FE0F",shortnames:["sa"]},{unified:"1F237-FE0F",shortnames:["u6708"]},{unified:"1F236",shortnames:["u6709"]},{unified:"1F22F",shortnames:["u6307"]},{unified:"1F250",shortnames:["ideograph_advantage"]},{unified:"1F239",shortnames:["u5272"]},{unified:"1F21A",shortnames:["u7121"]},{unified:"1F232",shortnames:["u7981"]},{unified:"1F251",shortnames:["accept"]},{unified:"1F238",shortnames:["u7533"]},{unified:"1F234",shortnames:["u5408"]},{unified:"1F233",shortnames:["u7a7a"]},{unified:"3297-FE0F",shortnames:["congratulations"]},{unified:"3299-FE0F",shortnames:["secret"]},{unified:"1F23A",shortnames:["u55b6"]},{unified:"1F235",shortnames:["u6e80"]},{unified:"1F534",shortnames:["red_circle"]},{unified:"1F7E0",shortnames:["large_orange_circle"]},{unified:"1F7E1",shortnames:["large_yellow_circle"]},{unified:"1F7E2",shortnames:["large_green_circle"]},{unified:"1F535",shortnames:["large_blue_circle"]},{unified:"1F7E3",shortnames:["large_purple_circle"]},{unified:"1F7E4",shortnames:["large_brown_circle"]},{unified:"26AB",shortnames:["black_circle"]},{unified:"26AA",shortnames:["white_circle"]},{unified:"1F7E5",shortnames:["large_red_square"]},{unified:"1F7E7",shortnames:["large_orange_square"]},{unified:"1F7E8",shortnames:["large_yellow_square"]},{unified:"1F7E9",shortnames:["large_green_square"]},{unified:"1F7E6",shortnames:["large_blue_square"]},{unified:"1F7EA",shortnames:["large_purple_square"]},{unified:"1F7EB",shortnames:["large_brown_square"]},{unified:"2B1B",shortnames:["black_large_square"]},{unified:"2B1C",shortnames:["white_large_square"]},{unified:"25FC-FE0F",shortnames:["black_medium_square"]},{unified:"25FB-FE0F",shortnames:["white_medium_square"]},{unified:"25FE",shortnames:["black_medium_small_square"]},{unified:"25FD",shortnames:["white_medium_small_square"]},{unified:"25AA-FE0F",shortnames:["black_small_square"]},{unified:"25AB-FE0F",shortnames:["white_small_square"]},{unified:"1F536",shortnames:["large_orange_diamond"]},{unified:"1F537",shortnames:["large_blue_diamond"]},{unified:"1F538",shortnames:["small_orange_diamond"]},{unified:"1F539",shortnames:["small_blue_diamond"]},{unified:"1F53A",shortnames:["small_red_triangle"]},{unified:"1F53B",shortnames:["small_red_triangle_down"]},{unified:"1F4A0",shortnames:["diamond_shape_with_a_dot_inside"]},{unified:"1F518",shortnames:["radio_button"]},{unified:"1F533",shortnames:["white_square_button"]},{unified:"1F532",shortnames:["black_square_button"]}]},{name:"Flags",emojis:[{unified:"1F3C1",shortnames:["checkered_flag"]},{unified:"1F6A9",shortnames:["triangular_flag_on_post"]},{unified:"1F38C",shortnames:["crossed_flags"]},{unified:"1F3F4",shortnames:["waving_black_flag"]},{unified:"1F3F3-FE0F",shortnames:["waving_white_flag"]},{unified:"1F3F3-FE0F-200D-1F308",shortnames:["rainbow-flag"]},{unified:"1F3F3-FE0F-200D-26A7-FE0F",shortnames:["transgender_flag"]},{unified:"1F3F4-200D-2620-FE0F",shortnames:["pirate_flag"]},{unified:"1F1E6-1F1E8",shortnames:["flag-ac"]},{unified:"1F1E6-1F1E9",shortnames:["flag-ad"]},{unified:"1F1E6-1F1EA",shortnames:["flag-ae"]},{unified:"1F1E6-1F1EB",shortnames:["flag-af"]},{unified:"1F1E6-1F1EC",shortnames:["flag-ag"]},{unified:"1F1E6-1F1EE",shortnames:["flag-ai"]},{unified:"1F1E6-1F1F1",shortnames:["flag-al"]},{unified:"1F1E6-1F1F2",shortnames:["flag-am"]},{unified:"1F1E6-1F1F4",shortnames:["flag-ao"]},{unified:"1F1E6-1F1F6",shortnames:["flag-aq"]},{unified:"1F1E6-1F1F7",shortnames:["flag-ar"]},{unified:"1F1E6-1F1F8",shortnames:["flag-as"]},{unified:"1F1E6-1F1F9",shortnames:["flag-at"]},{unified:"1F1E6-1F1FA",shortnames:["flag-au"]},{unified:"1F1E6-1F1FC",shortnames:["flag-aw"]},{unified:"1F1E6-1F1FD",shortnames:["flag-ax"]},{unified:"1F1E6-1F1FF",shortnames:["flag-az"]},{unified:"1F1E7-1F1E6",shortnames:["flag-ba"]},{unified:"1F1E7-1F1E7",shortnames:["flag-bb"]},{unified:"1F1E7-1F1E9",shortnames:["flag-bd"]},{unified:"1F1E7-1F1EA",shortnames:["flag-be"]},{unified:"1F1E7-1F1EB",shortnames:["flag-bf"]},{unified:"1F1E7-1F1EC",shortnames:["flag-bg"]},{unified:"1F1E7-1F1ED",shortnames:["flag-bh"]},{unified:"1F1E7-1F1EE",shortnames:["flag-bi"]},{unified:"1F1E7-1F1EF",shortnames:["flag-bj"]},{unified:"1F1E7-1F1F1",shortnames:["flag-bl"]},{unified:"1F1E7-1F1F2",shortnames:["flag-bm"]},{unified:"1F1E7-1F1F3",shortnames:["flag-bn"]},{unified:"1F1E7-1F1F4",shortnames:["flag-bo"]},{unified:"1F1E7-1F1F6",shortnames:["flag-bq"]},{unified:"1F1E7-1F1F7",shortnames:["flag-br"]},{unified:"1F1E7-1F1F8",shortnames:["flag-bs"]},{unified:"1F1E7-1F1F9",shortnames:["flag-bt"]},{unified:"1F1E7-1F1FB",shortnames:["flag-bv"]},{unified:"1F1E7-1F1FC",shortnames:["flag-bw"]},{unified:"1F1E7-1F1FE",shortnames:["flag-by"]},{unified:"1F1E7-1F1FF",shortnames:["flag-bz"]},{unified:"1F1E8-1F1E6",shortnames:["flag-ca"]},{unified:"1F1E8-1F1E8",shortnames:["flag-cc"]},{unified:"1F1E8-1F1E9",shortnames:["flag-cd"]},{unified:"1F1E8-1F1EB",shortnames:["flag-cf"]},{unified:"1F1E8-1F1EC",shortnames:["flag-cg"]},{unified:"1F1E8-1F1ED",shortnames:["flag-ch"]},{unified:"1F1E8-1F1EE",shortnames:["flag-ci"]},{unified:"1F1E8-1F1F0",shortnames:["flag-ck"]},{unified:"1F1E8-1F1F1",shortnames:["flag-cl"]},{unified:"1F1E8-1F1F2",shortnames:["flag-cm"]},{unified:"1F1E8-1F1F3",shortnames:["cn"]},{unified:"1F1E8-1F1F4",shortnames:["flag-co"]},{unified:"1F1E8-1F1F5",shortnames:["flag-cp"]},{unified:"1F1E8-1F1F7",shortnames:["flag-cr"]},{unified:"1F1E8-1F1FA",shortnames:["flag-cu"]},{unified:"1F1E8-1F1FB",shortnames:["flag-cv"]},{unified:"1F1E8-1F1FC",shortnames:["flag-cw"]},{unified:"1F1E8-1F1FD",shortnames:["flag-cx"]},{unified:"1F1E8-1F1FE",shortnames:["flag-cy"]},{unified:"1F1E8-1F1FF",shortnames:["flag-cz"]},{unified:"1F1E9-1F1EA",shortnames:["de"]},{unified:"1F1E9-1F1EC",shortnames:["flag-dg"]},{unified:"1F1E9-1F1EF",shortnames:["flag-dj"]},{unified:"1F1E9-1F1F0",shortnames:["flag-dk"]},{unified:"1F1E9-1F1F2",shortnames:["flag-dm"]},{unified:"1F1E9-1F1F4",shortnames:["flag-do"]},{unified:"1F1E9-1F1FF",shortnames:["flag-dz"]},{unified:"1F1EA-1F1E6",shortnames:["flag-ea"]},{unified:"1F1EA-1F1E8",shortnames:["flag-ec"]},{unified:"1F1EA-1F1EA",shortnames:["flag-ee"]},{unified:"1F1EA-1F1EC",shortnames:["flag-eg"]},{unified:"1F1EA-1F1ED",shortnames:["flag-eh"]},{unified:"1F1EA-1F1F7",shortnames:["flag-er"]},{unified:"1F1EA-1F1F8",shortnames:["es"]},{unified:"1F1EA-1F1F9",shortnames:["flag-et"]},{unified:"1F1EA-1F1FA",shortnames:["flag-eu"]},{unified:"1F1EB-1F1EE",shortnames:["flag-fi"]},{unified:"1F1EB-1F1EF",shortnames:["flag-fj"]},{unified:"1F1EB-1F1F0",shortnames:["flag-fk"]},{unified:"1F1EB-1F1F2",shortnames:["flag-fm"]},{unified:"1F1EB-1F1F4",shortnames:["flag-fo"]},{unified:"1F1EB-1F1F7",shortnames:["fr"]},{unified:"1F1EC-1F1E6",shortnames:["flag-ga"]},{unified:"1F1EC-1F1E7",shortnames:["gb"]},{unified:"1F1EC-1F1E9",shortnames:["flag-gd"]},{unified:"1F1EC-1F1EA",shortnames:["flag-ge"]},{unified:"1F1EC-1F1EB",shortnames:["flag-gf"]},{unified:"1F1EC-1F1EC",shortnames:["flag-gg"]},{unified:"1F1EC-1F1ED",shortnames:["flag-gh"]},{unified:"1F1EC-1F1EE",shortnames:["flag-gi"]},{unified:"1F1EC-1F1F1",shortnames:["flag-gl"]},{unified:"1F1EC-1F1F2",shortnames:["flag-gm"]},{unified:"1F1EC-1F1F3",shortnames:["flag-gn"]},{unified:"1F1EC-1F1F5",shortnames:["flag-gp"]},{unified:"1F1EC-1F1F6",shortnames:["flag-gq"]},{unified:"1F1EC-1F1F7",shortnames:["flag-gr"]},{unified:"1F1EC-1F1F8",shortnames:["flag-gs"]},{unified:"1F1EC-1F1F9",shortnames:["flag-gt"]},{unified:"1F1EC-1F1FA",shortnames:["flag-gu"]},{unified:"1F1EC-1F1FC",shortnames:["flag-gw"]},{unified:"1F1EC-1F1FE",shortnames:["flag-gy"]},{unified:"1F1ED-1F1F0",shortnames:["flag-hk"]},{unified:"1F1ED-1F1F2",shortnames:["flag-hm"]},{unified:"1F1ED-1F1F3",shortnames:["flag-hn"]},{unified:"1F1ED-1F1F7",shortnames:["flag-hr"]},{unified:"1F1ED-1F1F9",shortnames:["flag-ht"]},{unified:"1F1ED-1F1FA",shortnames:["flag-hu"]},{unified:"1F1EE-1F1E8",shortnames:["flag-ic"]},{unified:"1F1EE-1F1E9",shortnames:["flag-id"]},{unified:"1F1EE-1F1EA",shortnames:["flag-ie"]},{unified:"1F1EE-1F1F1",shortnames:["flag-il"]},{unified:"1F1EE-1F1F2",shortnames:["flag-im"]},{unified:"1F1EE-1F1F3",shortnames:["flag-in"]},{unified:"1F1EE-1F1F4",shortnames:["flag-io"]},{unified:"1F1EE-1F1F6",shortnames:["flag-iq"]},{unified:"1F1EE-1F1F7",shortnames:["flag-ir"]},{unified:"1F1EE-1F1F8",shortnames:["flag-is"]},{unified:"1F1EE-1F1F9",shortnames:["it"]},{unified:"1F1EF-1F1EA",shortnames:["flag-je"]},{unified:"1F1EF-1F1F2",shortnames:["flag-jm"]},{unified:"1F1EF-1F1F4",shortnames:["flag-jo"]},{unified:"1F1EF-1F1F5",shortnames:["jp"]},{unified:"1F1F0-1F1EA",shortnames:["flag-ke"]},{unified:"1F1F0-1F1EC",shortnames:["flag-kg"]},{unified:"1F1F0-1F1ED",shortnames:["flag-kh"]},{unified:"1F1F0-1F1EE",shortnames:["flag-ki"]},{unified:"1F1F0-1F1F2",shortnames:["flag-km"]},{unified:"1F1F0-1F1F3",shortnames:["flag-kn"]},{unified:"1F1F0-1F1F5",shortnames:["flag-kp"]},{unified:"1F1F0-1F1F7",shortnames:["kr"]},{unified:"1F1F0-1F1FC",shortnames:["flag-kw"]},{unified:"1F1F0-1F1FE",shortnames:["flag-ky"]},{unified:"1F1F0-1F1FF",shortnames:["flag-kz"]},{unified:"1F1F1-1F1E6",shortnames:["flag-la"]},{unified:"1F1F1-1F1E7",shortnames:["flag-lb"]},{unified:"1F1F1-1F1E8",shortnames:["flag-lc"]},{unified:"1F1F1-1F1EE",shortnames:["flag-li"]},{unified:"1F1F1-1F1F0",shortnames:["flag-lk"]},{unified:"1F1F1-1F1F7",shortnames:["flag-lr"]},{unified:"1F1F1-1F1F8",shortnames:["flag-ls"]},{unified:"1F1F1-1F1F9",shortnames:["flag-lt"]},{unified:"1F1F1-1F1FA",shortnames:["flag-lu"]},{unified:"1F1F1-1F1FB",shortnames:["flag-lv"]},{unified:"1F1F1-1F1FE",shortnames:["flag-ly"]},{unified:"1F1F2-1F1E6",shortnames:["flag-ma"]},{unified:"1F1F2-1F1E8",shortnames:["flag-mc"]},{unified:"1F1F2-1F1E9",shortnames:["flag-md"]},{unified:"1F1F2-1F1EA",shortnames:["flag-me"]},{unified:"1F1F2-1F1EB",shortnames:["flag-mf"]},{unified:"1F1F2-1F1EC",shortnames:["flag-mg"]},{unified:"1F1F2-1F1ED",shortnames:["flag-mh"]},{unified:"1F1F2-1F1F0",shortnames:["flag-mk"]},{unified:"1F1F2-1F1F1",shortnames:["flag-ml"]},{unified:"1F1F2-1F1F2",shortnames:["flag-mm"]},{unified:"1F1F2-1F1F3",shortnames:["flag-mn"]},{unified:"1F1F2-1F1F4",shortnames:["flag-mo"]},{unified:"1F1F2-1F1F5",shortnames:["flag-mp"]},{unified:"1F1F2-1F1F6",shortnames:["flag-mq"]},{unified:"1F1F2-1F1F7",shortnames:["flag-mr"]},{unified:"1F1F2-1F1F8",shortnames:["flag-ms"]},{unified:"1F1F2-1F1F9",shortnames:["flag-mt"]},{unified:"1F1F2-1F1FA",shortnames:["flag-mu"]},{unified:"1F1F2-1F1FB",shortnames:["flag-mv"]},{unified:"1F1F2-1F1FC",shortnames:["flag-mw"]},{unified:"1F1F2-1F1FD",shortnames:["flag-mx"]},{unified:"1F1F2-1F1FE",shortnames:["flag-my"]},{unified:"1F1F2-1F1FF",shortnames:["flag-mz"]},{unified:"1F1F3-1F1E6",shortnames:["flag-na"]},{unified:"1F1F3-1F1E8",shortnames:["flag-nc"]},{unified:"1F1F3-1F1EA",shortnames:["flag-ne"]},{unified:"1F1F3-1F1EB",shortnames:["flag-nf"]},{unified:"1F1F3-1F1EC",shortnames:["flag-ng"]},{unified:"1F1F3-1F1EE",shortnames:["flag-ni"]},{unified:"1F1F3-1F1F1",shortnames:["flag-nl"]},{unified:"1F1F3-1F1F4",shortnames:["flag-no"]},{unified:"1F1F3-1F1F5",shortnames:["flag-np"]},{unified:"1F1F3-1F1F7",shortnames:["flag-nr"]},{unified:"1F1F3-1F1FA",shortnames:["flag-nu"]},{unified:"1F1F3-1F1FF",shortnames:["flag-nz"]},{unified:"1F1F4-1F1F2",shortnames:["flag-om"]},{unified:"1F1F5-1F1E6",shortnames:["flag-pa"]},{unified:"1F1F5-1F1EA",shortnames:["flag-pe"]},{unified:"1F1F5-1F1EB",shortnames:["flag-pf"]},{unified:"1F1F5-1F1EC",shortnames:["flag-pg"]},{unified:"1F1F5-1F1ED",shortnames:["flag-ph"]},{unified:"1F1F5-1F1F0",shortnames:["flag-pk"]},{unified:"1F1F5-1F1F1",shortnames:["flag-pl"]},{unified:"1F1F5-1F1F2",shortnames:["flag-pm"]},{unified:"1F1F5-1F1F3",shortnames:["flag-pn"]},{unified:"1F1F5-1F1F7",shortnames:["flag-pr"]},{unified:"1F1F5-1F1F8",shortnames:["flag-ps"]},{unified:"1F1F5-1F1F9",shortnames:["flag-pt"]},{unified:"1F1F5-1F1FC",shortnames:["flag-pw"]},{unified:"1F1F5-1F1FE",shortnames:["flag-py"]},{unified:"1F1F6-1F1E6",shortnames:["flag-qa"]},{unified:"1F1F7-1F1EA",shortnames:["flag-re"]},{unified:"1F1F7-1F1F4",shortnames:["flag-ro"]},{unified:"1F1F7-1F1F8",shortnames:["flag-rs"]},{unified:"1F1F7-1F1FA",shortnames:["ru"]},{unified:"1F1F7-1F1FC",shortnames:["flag-rw"]},{unified:"1F1F8-1F1E6",shortnames:["flag-sa"]},{unified:"1F1F8-1F1E7",shortnames:["flag-sb"]},{unified:"1F1F8-1F1E8",shortnames:["flag-sc"]},{unified:"1F1F8-1F1E9",shortnames:["flag-sd"]},{unified:"1F1F8-1F1EA",shortnames:["flag-se"]},{unified:"1F1F8-1F1EC",shortnames:["flag-sg"]},{unified:"1F1F8-1F1ED",shortnames:["flag-sh"]},{unified:"1F1F8-1F1EE",shortnames:["flag-si"]},{unified:"1F1F8-1F1EF",shortnames:["flag-sj"]},{unified:"1F1F8-1F1F0",shortnames:["flag-sk"]},{unified:"1F1F8-1F1F1",shortnames:["flag-sl"]},{unified:"1F1F8-1F1F2",shortnames:["flag-sm"]},{unified:"1F1F8-1F1F3",shortnames:["flag-sn"]},{unified:"1F1F8-1F1F4",shortnames:["flag-so"]},{unified:"1F1F8-1F1F7",shortnames:["flag-sr"]},{unified:"1F1F8-1F1F8",shortnames:["flag-ss"]},{unified:"1F1F8-1F1F9",shortnames:["flag-st"]},{unified:"1F1F8-1F1FB",shortnames:["flag-sv"]},{unified:"1F1F8-1F1FD",shortnames:["flag-sx"]},{unified:"1F1F8-1F1FE",shortnames:["flag-sy"]},{unified:"1F1F8-1F1FF",shortnames:["flag-sz"]},{unified:"1F1F9-1F1E6",shortnames:["flag-ta"]},{unified:"1F1F9-1F1E8",shortnames:["flag-tc"]},{unified:"1F1F9-1F1E9",shortnames:["flag-td"]},{unified:"1F1F9-1F1EB",shortnames:["flag-tf"]},{unified:"1F1F9-1F1EC",shortnames:["flag-tg"]},{unified:"1F1F9-1F1ED",shortnames:["flag-th"]},{unified:"1F1F9-1F1EF",shortnames:["flag-tj"]},{unified:"1F1F9-1F1F0",shortnames:["flag-tk"]},{unified:"1F1F9-1F1F1",shortnames:["flag-tl"]},{unified:"1F1F9-1F1F2",shortnames:["flag-tm"]},{unified:"1F1F9-1F1F3",shortnames:["flag-tn"]},{unified:"1F1F9-1F1F4",shortnames:["flag-to"]},{unified:"1F1F9-1F1F7",shortnames:["flag-tr"]},{unified:"1F1F9-1F1F9",shortnames:["flag-tt"]},{unified:"1F1F9-1F1FB",shortnames:["flag-tv"]},{unified:"1F1F9-1F1FC",shortnames:["flag-tw"]},{unified:"1F1F9-1F1FF",shortnames:["flag-tz"]},{unified:"1F1FA-1F1E6",shortnames:["flag-ua"]},{unified:"1F1FA-1F1EC",shortnames:["flag-ug"]},{unified:"1F1FA-1F1F2",shortnames:["flag-um"]},{unified:"1F1FA-1F1F3",shortnames:["flag-un"]},{unified:"1F1FA-1F1F8",shortnames:["us"]},{unified:"1F1FA-1F1FE",shortnames:["flag-uy"]},{unified:"1F1FA-1F1FF",shortnames:["flag-uz"]},{unified:"1F1FB-1F1E6",shortnames:["flag-va"]},{unified:"1F1FB-1F1E8",shortnames:["flag-vc"]},{unified:"1F1FB-1F1EA",shortnames:["flag-ve"]},{unified:"1F1FB-1F1EC",shortnames:["flag-vg"]},{unified:"1F1FB-1F1EE",shortnames:["flag-vi"]},{unified:"1F1FB-1F1F3",shortnames:["flag-vn"]},{unified:"1F1FB-1F1FA",shortnames:["flag-vu"]},{unified:"1F1FC-1F1EB",shortnames:["flag-wf"]},{unified:"1F1FC-1F1F8",shortnames:["flag-ws"]},{unified:"1F1FD-1F1F0",shortnames:["flag-xk"]},{unified:"1F1FE-1F1EA",shortnames:["flag-ye"]},{unified:"1F1FE-1F1F9",shortnames:["flag-yt"]},{unified:"1F1FF-1F1E6",shortnames:["flag-za"]},{unified:"1F1FF-1F1F2",shortnames:["flag-zm"]},{unified:"1F1FF-1F1FC",shortnames:["flag-zw"]},{unified:"1F3F4-E0067-E0062-E0065-E006E-E0067-E007F",shortnames:["flag-england"]},{unified:"1F3F4-E0067-E0062-E0073-E0063-E0074-E007F",shortnames:["flag-scotland"]},{unified:"1F3F4-E0067-E0062-E0077-E006C-E0073-E007F",shortnames:["flag-wales"]}]}];_exports.byShortName={hash:"0023-FE0F-20E3",keycap_star:"002A-FE0F-20E3",zero:"0030-FE0F-20E3",one:"0031-FE0F-20E3",two:"0032-FE0F-20E3",three:"0033-FE0F-20E3",four:"0034-FE0F-20E3",five:"0035-FE0F-20E3",six:"0036-FE0F-20E3",seven:"0037-FE0F-20E3",eight:"0038-FE0F-20E3",nine:"0039-FE0F-20E3",copyright:"00A9-FE0F",registered:"00AE-FE0F",mahjong:"1F004",black_joker:"1F0CF",a:"1F170-FE0F",b:"1F171-FE0F",o2:"1F17E-FE0F",parking:"1F17F-FE0F",ab:"1F18E",cl:"1F191",cool:"1F192",free:"1F193",id:"1F194",new:"1F195",ng:"1F196",ok:"1F197",sos:"1F198",up:"1F199",vs:"1F19A","flag-ac":"1F1E6-1F1E8","flag-ad":"1F1E6-1F1E9","flag-ae":"1F1E6-1F1EA","flag-af":"1F1E6-1F1EB","flag-ag":"1F1E6-1F1EC","flag-ai":"1F1E6-1F1EE","flag-al":"1F1E6-1F1F1","flag-am":"1F1E6-1F1F2","flag-ao":"1F1E6-1F1F4","flag-aq":"1F1E6-1F1F6","flag-ar":"1F1E6-1F1F7","flag-as":"1F1E6-1F1F8","flag-at":"1F1E6-1F1F9","flag-au":"1F1E6-1F1FA","flag-aw":"1F1E6-1F1FC","flag-ax":"1F1E6-1F1FD","flag-az":"1F1E6-1F1FF","flag-ba":"1F1E7-1F1E6","flag-bb":"1F1E7-1F1E7","flag-bd":"1F1E7-1F1E9","flag-be":"1F1E7-1F1EA","flag-bf":"1F1E7-1F1EB","flag-bg":"1F1E7-1F1EC","flag-bh":"1F1E7-1F1ED","flag-bi":"1F1E7-1F1EE","flag-bj":"1F1E7-1F1EF","flag-bl":"1F1E7-1F1F1","flag-bm":"1F1E7-1F1F2","flag-bn":"1F1E7-1F1F3","flag-bo":"1F1E7-1F1F4","flag-bq":"1F1E7-1F1F6","flag-br":"1F1E7-1F1F7","flag-bs":"1F1E7-1F1F8","flag-bt":"1F1E7-1F1F9","flag-bv":"1F1E7-1F1FB","flag-bw":"1F1E7-1F1FC","flag-by":"1F1E7-1F1FE","flag-bz":"1F1E7-1F1FF","flag-ca":"1F1E8-1F1E6","flag-cc":"1F1E8-1F1E8","flag-cd":"1F1E8-1F1E9","flag-cf":"1F1E8-1F1EB","flag-cg":"1F1E8-1F1EC","flag-ch":"1F1E8-1F1ED","flag-ci":"1F1E8-1F1EE","flag-ck":"1F1E8-1F1F0","flag-cl":"1F1E8-1F1F1","flag-cm":"1F1E8-1F1F2",cn:"1F1E8-1F1F3","flag-co":"1F1E8-1F1F4","flag-cp":"1F1E8-1F1F5","flag-cr":"1F1E8-1F1F7","flag-cu":"1F1E8-1F1FA","flag-cv":"1F1E8-1F1FB","flag-cw":"1F1E8-1F1FC","flag-cx":"1F1E8-1F1FD","flag-cy":"1F1E8-1F1FE","flag-cz":"1F1E8-1F1FF",de:"1F1E9-1F1EA","flag-dg":"1F1E9-1F1EC","flag-dj":"1F1E9-1F1EF","flag-dk":"1F1E9-1F1F0","flag-dm":"1F1E9-1F1F2","flag-do":"1F1E9-1F1F4","flag-dz":"1F1E9-1F1FF","flag-ea":"1F1EA-1F1E6","flag-ec":"1F1EA-1F1E8","flag-ee":"1F1EA-1F1EA","flag-eg":"1F1EA-1F1EC","flag-eh":"1F1EA-1F1ED","flag-er":"1F1EA-1F1F7",es:"1F1EA-1F1F8","flag-et":"1F1EA-1F1F9","flag-eu":"1F1EA-1F1FA","flag-fi":"1F1EB-1F1EE","flag-fj":"1F1EB-1F1EF","flag-fk":"1F1EB-1F1F0","flag-fm":"1F1EB-1F1F2","flag-fo":"1F1EB-1F1F4",fr:"1F1EB-1F1F7","flag-ga":"1F1EC-1F1E6",gb:"1F1EC-1F1E7","flag-gd":"1F1EC-1F1E9","flag-ge":"1F1EC-1F1EA","flag-gf":"1F1EC-1F1EB","flag-gg":"1F1EC-1F1EC","flag-gh":"1F1EC-1F1ED","flag-gi":"1F1EC-1F1EE","flag-gl":"1F1EC-1F1F1","flag-gm":"1F1EC-1F1F2","flag-gn":"1F1EC-1F1F3","flag-gp":"1F1EC-1F1F5","flag-gq":"1F1EC-1F1F6","flag-gr":"1F1EC-1F1F7","flag-gs":"1F1EC-1F1F8","flag-gt":"1F1EC-1F1F9","flag-gu":"1F1EC-1F1FA","flag-gw":"1F1EC-1F1FC","flag-gy":"1F1EC-1F1FE","flag-hk":"1F1ED-1F1F0","flag-hm":"1F1ED-1F1F2","flag-hn":"1F1ED-1F1F3","flag-hr":"1F1ED-1F1F7","flag-ht":"1F1ED-1F1F9","flag-hu":"1F1ED-1F1FA","flag-ic":"1F1EE-1F1E8","flag-id":"1F1EE-1F1E9","flag-ie":"1F1EE-1F1EA","flag-il":"1F1EE-1F1F1","flag-im":"1F1EE-1F1F2","flag-in":"1F1EE-1F1F3","flag-io":"1F1EE-1F1F4","flag-iq":"1F1EE-1F1F6","flag-ir":"1F1EE-1F1F7","flag-is":"1F1EE-1F1F8",it:"1F1EE-1F1F9","flag-je":"1F1EF-1F1EA","flag-jm":"1F1EF-1F1F2","flag-jo":"1F1EF-1F1F4",jp:"1F1EF-1F1F5","flag-ke":"1F1F0-1F1EA","flag-kg":"1F1F0-1F1EC","flag-kh":"1F1F0-1F1ED","flag-ki":"1F1F0-1F1EE","flag-km":"1F1F0-1F1F2","flag-kn":"1F1F0-1F1F3","flag-kp":"1F1F0-1F1F5",kr:"1F1F0-1F1F7","flag-kw":"1F1F0-1F1FC","flag-ky":"1F1F0-1F1FE","flag-kz":"1F1F0-1F1FF","flag-la":"1F1F1-1F1E6","flag-lb":"1F1F1-1F1E7","flag-lc":"1F1F1-1F1E8","flag-li":"1F1F1-1F1EE","flag-lk":"1F1F1-1F1F0","flag-lr":"1F1F1-1F1F7","flag-ls":"1F1F1-1F1F8","flag-lt":"1F1F1-1F1F9","flag-lu":"1F1F1-1F1FA","flag-lv":"1F1F1-1F1FB","flag-ly":"1F1F1-1F1FE","flag-ma":"1F1F2-1F1E6","flag-mc":"1F1F2-1F1E8","flag-md":"1F1F2-1F1E9","flag-me":"1F1F2-1F1EA","flag-mf":"1F1F2-1F1EB","flag-mg":"1F1F2-1F1EC","flag-mh":"1F1F2-1F1ED","flag-mk":"1F1F2-1F1F0","flag-ml":"1F1F2-1F1F1","flag-mm":"1F1F2-1F1F2","flag-mn":"1F1F2-1F1F3","flag-mo":"1F1F2-1F1F4","flag-mp":"1F1F2-1F1F5","flag-mq":"1F1F2-1F1F6","flag-mr":"1F1F2-1F1F7","flag-ms":"1F1F2-1F1F8","flag-mt":"1F1F2-1F1F9","flag-mu":"1F1F2-1F1FA","flag-mv":"1F1F2-1F1FB","flag-mw":"1F1F2-1F1FC","flag-mx":"1F1F2-1F1FD","flag-my":"1F1F2-1F1FE","flag-mz":"1F1F2-1F1FF","flag-na":"1F1F3-1F1E6","flag-nc":"1F1F3-1F1E8","flag-ne":"1F1F3-1F1EA","flag-nf":"1F1F3-1F1EB","flag-ng":"1F1F3-1F1EC","flag-ni":"1F1F3-1F1EE","flag-nl":"1F1F3-1F1F1","flag-no":"1F1F3-1F1F4","flag-np":"1F1F3-1F1F5","flag-nr":"1F1F3-1F1F7","flag-nu":"1F1F3-1F1FA","flag-nz":"1F1F3-1F1FF","flag-om":"1F1F4-1F1F2","flag-pa":"1F1F5-1F1E6","flag-pe":"1F1F5-1F1EA","flag-pf":"1F1F5-1F1EB","flag-pg":"1F1F5-1F1EC","flag-ph":"1F1F5-1F1ED","flag-pk":"1F1F5-1F1F0","flag-pl":"1F1F5-1F1F1","flag-pm":"1F1F5-1F1F2","flag-pn":"1F1F5-1F1F3","flag-pr":"1F1F5-1F1F7","flag-ps":"1F1F5-1F1F8","flag-pt":"1F1F5-1F1F9","flag-pw":"1F1F5-1F1FC","flag-py":"1F1F5-1F1FE","flag-qa":"1F1F6-1F1E6","flag-re":"1F1F7-1F1EA","flag-ro":"1F1F7-1F1F4","flag-rs":"1F1F7-1F1F8",ru:"1F1F7-1F1FA","flag-rw":"1F1F7-1F1FC","flag-sa":"1F1F8-1F1E6","flag-sb":"1F1F8-1F1E7","flag-sc":"1F1F8-1F1E8","flag-sd":"1F1F8-1F1E9","flag-se":"1F1F8-1F1EA","flag-sg":"1F1F8-1F1EC","flag-sh":"1F1F8-1F1ED","flag-si":"1F1F8-1F1EE","flag-sj":"1F1F8-1F1EF","flag-sk":"1F1F8-1F1F0","flag-sl":"1F1F8-1F1F1","flag-sm":"1F1F8-1F1F2","flag-sn":"1F1F8-1F1F3","flag-so":"1F1F8-1F1F4","flag-sr":"1F1F8-1F1F7","flag-ss":"1F1F8-1F1F8","flag-st":"1F1F8-1F1F9","flag-sv":"1F1F8-1F1FB","flag-sx":"1F1F8-1F1FD","flag-sy":"1F1F8-1F1FE","flag-sz":"1F1F8-1F1FF","flag-ta":"1F1F9-1F1E6","flag-tc":"1F1F9-1F1E8","flag-td":"1F1F9-1F1E9","flag-tf":"1F1F9-1F1EB","flag-tg":"1F1F9-1F1EC","flag-th":"1F1F9-1F1ED","flag-tj":"1F1F9-1F1EF","flag-tk":"1F1F9-1F1F0","flag-tl":"1F1F9-1F1F1","flag-tm":"1F1F9-1F1F2","flag-tn":"1F1F9-1F1F3","flag-to":"1F1F9-1F1F4","flag-tr":"1F1F9-1F1F7","flag-tt":"1F1F9-1F1F9","flag-tv":"1F1F9-1F1FB","flag-tw":"1F1F9-1F1FC","flag-tz":"1F1F9-1F1FF","flag-ua":"1F1FA-1F1E6","flag-ug":"1F1FA-1F1EC","flag-um":"1F1FA-1F1F2","flag-un":"1F1FA-1F1F3",us:"1F1FA-1F1F8","flag-uy":"1F1FA-1F1FE","flag-uz":"1F1FA-1F1FF","flag-va":"1F1FB-1F1E6","flag-vc":"1F1FB-1F1E8","flag-ve":"1F1FB-1F1EA","flag-vg":"1F1FB-1F1EC","flag-vi":"1F1FB-1F1EE","flag-vn":"1F1FB-1F1F3","flag-vu":"1F1FB-1F1FA","flag-wf":"1F1FC-1F1EB","flag-ws":"1F1FC-1F1F8","flag-xk":"1F1FD-1F1F0","flag-ye":"1F1FE-1F1EA","flag-yt":"1F1FE-1F1F9","flag-za":"1F1FF-1F1E6","flag-zm":"1F1FF-1F1F2","flag-zw":"1F1FF-1F1FC",koko:"1F201",sa:"1F202-FE0F",u7121:"1F21A",u6307:"1F22F",u7981:"1F232",u7a7a:"1F233",u5408:"1F234",u6e80:"1F235",u6709:"1F236",u6708:"1F237-FE0F",u7533:"1F238",u5272:"1F239",u55b6:"1F23A",ideograph_advantage:"1F250",accept:"1F251",cyclone:"1F300",foggy:"1F301",closed_umbrella:"1F302",night_with_stars:"1F303",sunrise_over_mountains:"1F304",sunrise:"1F305",city_sunset:"1F306",city_sunrise:"1F307",rainbow:"1F308",bridge_at_night:"1F309",ocean:"1F30A",volcano:"1F30B",milky_way:"1F30C",earth_africa:"1F30D",earth_americas:"1F30E",earth_asia:"1F30F",globe_with_meridians:"1F310",new_moon:"1F311",waxing_crescent_moon:"1F312",first_quarter_moon:"1F313",moon:"1F314",full_moon:"1F315",waning_gibbous_moon:"1F316",last_quarter_moon:"1F317",waning_crescent_moon:"1F318",crescent_moon:"1F319",new_moon_with_face:"1F31A",first_quarter_moon_with_face:"1F31B",last_quarter_moon_with_face:"1F31C",full_moon_with_face:"1F31D",sun_with_face:"1F31E",star2:"1F31F",stars:"1F320",thermometer:"1F321-FE0F",mostly_sunny:"1F324-FE0F",barely_sunny:"1F325-FE0F",partly_sunny_rain:"1F326-FE0F",rain_cloud:"1F327-FE0F",snow_cloud:"1F328-FE0F",lightning:"1F329-FE0F",tornado:"1F32A-FE0F",fog:"1F32B-FE0F",wind_blowing_face:"1F32C-FE0F",hotdog:"1F32D",taco:"1F32E",burrito:"1F32F",chestnut:"1F330",seedling:"1F331",evergreen_tree:"1F332",deciduous_tree:"1F333",palm_tree:"1F334",cactus:"1F335",hot_pepper:"1F336-FE0F",tulip:"1F337",cherry_blossom:"1F338",rose:"1F339",hibiscus:"1F33A",sunflower:"1F33B",blossom:"1F33C",corn:"1F33D",ear_of_rice:"1F33E",herb:"1F33F",four_leaf_clover:"1F340",maple_leaf:"1F341",fallen_leaf:"1F342",leaves:"1F343",mushroom:"1F344",tomato:"1F345",eggplant:"1F346",grapes:"1F347",melon:"1F348",watermelon:"1F349",tangerine:"1F34A",lemon:"1F34B",banana:"1F34C",pineapple:"1F34D",apple:"1F34E",green_apple:"1F34F",pear:"1F350",peach:"1F351",cherries:"1F352",strawberry:"1F353",hamburger:"1F354",pizza:"1F355",meat_on_bone:"1F356",poultry_leg:"1F357",rice_cracker:"1F358",rice_ball:"1F359",rice:"1F35A",curry:"1F35B",ramen:"1F35C",spaghetti:"1F35D",bread:"1F35E",fries:"1F35F",sweet_potato:"1F360",dango:"1F361",oden:"1F362",sushi:"1F363",fried_shrimp:"1F364",fish_cake:"1F365",icecream:"1F366",shaved_ice:"1F367",ice_cream:"1F368",doughnut:"1F369",cookie:"1F36A",chocolate_bar:"1F36B",candy:"1F36C",lollipop:"1F36D",custard:"1F36E",honey_pot:"1F36F",cake:"1F370",bento:"1F371",stew:"1F372",fried_egg:"1F373",fork_and_knife:"1F374",tea:"1F375",sake:"1F376",wine_glass:"1F377",cocktail:"1F378",tropical_drink:"1F379",beer:"1F37A",beers:"1F37B",baby_bottle:"1F37C",knife_fork_plate:"1F37D-FE0F",champagne:"1F37E",popcorn:"1F37F",ribbon:"1F380",gift:"1F381",birthday:"1F382",jack_o_lantern:"1F383",christmas_tree:"1F384",santa:"1F385",fireworks:"1F386",sparkler:"1F387",balloon:"1F388",tada:"1F389",confetti_ball:"1F38A",tanabata_tree:"1F38B",crossed_flags:"1F38C",bamboo:"1F38D",dolls:"1F38E",flags:"1F38F",wind_chime:"1F390",rice_scene:"1F391",school_satchel:"1F392",mortar_board:"1F393",medal:"1F396-FE0F",reminder_ribbon:"1F397-FE0F",studio_microphone:"1F399-FE0F",level_slider:"1F39A-FE0F",control_knobs:"1F39B-FE0F",film_frames:"1F39E-FE0F",admission_tickets:"1F39F-FE0F",carousel_horse:"1F3A0",ferris_wheel:"1F3A1",roller_coaster:"1F3A2",fishing_pole_and_fish:"1F3A3",microphone:"1F3A4",movie_camera:"1F3A5",cinema:"1F3A6",headphones:"1F3A7",art:"1F3A8",tophat:"1F3A9",circus_tent:"1F3AA",ticket:"1F3AB",clapper:"1F3AC",performing_arts:"1F3AD",video_game:"1F3AE",dart:"1F3AF",slot_machine:"1F3B0","8ball":"1F3B1",game_die:"1F3B2",bowling:"1F3B3",flower_playing_cards:"1F3B4",musical_note:"1F3B5",notes:"1F3B6",saxophone:"1F3B7",guitar:"1F3B8",musical_keyboard:"1F3B9",trumpet:"1F3BA",violin:"1F3BB",musical_score:"1F3BC",running_shirt_with_sash:"1F3BD",tennis:"1F3BE",ski:"1F3BF",basketball:"1F3C0",checkered_flag:"1F3C1",snowboarder:"1F3C2","woman-running":"1F3C3-200D-2640-FE0F","man-running":"1F3C3-200D-2642-FE0F",runner:"1F3C3-200D-2642-FE0F","woman-surfing":"1F3C4-200D-2640-FE0F","man-surfing":"1F3C4-200D-2642-FE0F",surfer:"1F3C4-200D-2642-FE0F",sports_medal:"1F3C5",trophy:"1F3C6",horse_racing:"1F3C7",football:"1F3C8",rugby_football:"1F3C9","woman-swimming":"1F3CA-200D-2640-FE0F","man-swimming":"1F3CA-200D-2642-FE0F",swimmer:"1F3CA-200D-2642-FE0F","woman-lifting-weights":"1F3CB-FE0F-200D-2640-FE0F","man-lifting-weights":"1F3CB-FE0F-200D-2642-FE0F",weight_lifter:"1F3CB-FE0F-200D-2642-FE0F","woman-golfing":"1F3CC-FE0F-200D-2640-FE0F","man-golfing":"1F3CC-FE0F-200D-2642-FE0F",golfer:"1F3CC-FE0F-200D-2642-FE0F",racing_motorcycle:"1F3CD-FE0F",racing_car:"1F3CE-FE0F",cricket_bat_and_ball:"1F3CF",volleyball:"1F3D0",field_hockey_stick_and_ball:"1F3D1",ice_hockey_stick_and_puck:"1F3D2",table_tennis_paddle_and_ball:"1F3D3",snow_capped_mountain:"1F3D4-FE0F",camping:"1F3D5-FE0F",beach_with_umbrella:"1F3D6-FE0F",building_construction:"1F3D7-FE0F",house_buildings:"1F3D8-FE0F",cityscape:"1F3D9-FE0F",derelict_house_building:"1F3DA-FE0F",classical_building:"1F3DB-FE0F",desert:"1F3DC-FE0F",desert_island:"1F3DD-FE0F",national_park:"1F3DE-FE0F",stadium:"1F3DF-FE0F",house:"1F3E0",house_with_garden:"1F3E1",office:"1F3E2",post_office:"1F3E3",european_post_office:"1F3E4",hospital:"1F3E5",bank:"1F3E6",atm:"1F3E7",hotel:"1F3E8",love_hotel:"1F3E9",convenience_store:"1F3EA",school:"1F3EB",department_store:"1F3EC",factory:"1F3ED",izakaya_lantern:"1F3EE",japanese_castle:"1F3EF",european_castle:"1F3F0","rainbow-flag":"1F3F3-FE0F-200D-1F308",transgender_flag:"1F3F3-FE0F-200D-26A7-FE0F",waving_white_flag:"1F3F3-FE0F",pirate_flag:"1F3F4-200D-2620-FE0F","flag-england":"1F3F4-E0067-E0062-E0065-E006E-E0067-E007F","flag-scotland":"1F3F4-E0067-E0062-E0073-E0063-E0074-E007F","flag-wales":"1F3F4-E0067-E0062-E0077-E006C-E0073-E007F",waving_black_flag:"1F3F4",rosette:"1F3F5-FE0F",label:"1F3F7-FE0F",badminton_racquet_and_shuttlecock:"1F3F8",bow_and_arrow:"1F3F9",amphora:"1F3FA","skin-tone-2":"1F3FB","skin-tone-3":"1F3FC","skin-tone-4":"1F3FD","skin-tone-5":"1F3FE","skin-tone-6":"1F3FF",rat:"1F400",mouse2:"1F401",ox:"1F402",water_buffalo:"1F403",cow2:"1F404",tiger2:"1F405",leopard:"1F406",rabbit2:"1F407",black_cat:"1F408-200D-2B1B",cat2:"1F408",dragon:"1F409",crocodile:"1F40A",whale2:"1F40B",snail:"1F40C",snake:"1F40D",racehorse:"1F40E",ram:"1F40F",goat:"1F410",sheep:"1F411",monkey:"1F412",rooster:"1F413",chicken:"1F414",service_dog:"1F415-200D-1F9BA",dog2:"1F415",pig2:"1F416",boar:"1F417",elephant:"1F418",octopus:"1F419",shell:"1F41A",bug:"1F41B",ant:"1F41C",bee:"1F41D",ladybug:"1F41E",fish:"1F41F",tropical_fish:"1F420",blowfish:"1F421",turtle:"1F422",hatching_chick:"1F423",baby_chick:"1F424",hatched_chick:"1F425",bird:"1F426",penguin:"1F427",koala:"1F428",poodle:"1F429",dromedary_camel:"1F42A",camel:"1F42B",dolphin:"1F42C",mouse:"1F42D",cow:"1F42E",tiger:"1F42F",rabbit:"1F430",cat:"1F431",dragon_face:"1F432",whale:"1F433",horse:"1F434",monkey_face:"1F435",dog:"1F436",pig:"1F437",frog:"1F438",hamster:"1F439",wolf:"1F43A",polar_bear:"1F43B-200D-2744-FE0F",bear:"1F43B",panda_face:"1F43C",pig_nose:"1F43D",feet:"1F43E",chipmunk:"1F43F-FE0F",eyes:"1F440","eye-in-speech-bubble":"1F441-FE0F-200D-1F5E8-FE0F",eye:"1F441-FE0F",ear:"1F442",nose:"1F443",lips:"1F444",tongue:"1F445",point_up_2:"1F446",point_down:"1F447",point_left:"1F448",point_right:"1F449",facepunch:"1F44A",wave:"1F44B",ok_hand:"1F44C","+1":"1F44D","-1":"1F44E",clap:"1F44F",open_hands:"1F450",crown:"1F451",womans_hat:"1F452",eyeglasses:"1F453",necktie:"1F454",shirt:"1F455",jeans:"1F456",dress:"1F457",kimono:"1F458",bikini:"1F459",womans_clothes:"1F45A",purse:"1F45B",handbag:"1F45C",pouch:"1F45D",mans_shoe:"1F45E",athletic_shoe:"1F45F",high_heel:"1F460",sandal:"1F461",boot:"1F462",footprints:"1F463",bust_in_silhouette:"1F464",busts_in_silhouette:"1F465",boy:"1F466",girl:"1F467","male-farmer":"1F468-200D-1F33E","male-cook":"1F468-200D-1F373",man_feeding_baby:"1F468-200D-1F37C","male-student":"1F468-200D-1F393","male-singer":"1F468-200D-1F3A4","male-artist":"1F468-200D-1F3A8","male-teacher":"1F468-200D-1F3EB","male-factory-worker":"1F468-200D-1F3ED","man-boy-boy":"1F468-200D-1F466-200D-1F466","man-boy":"1F468-200D-1F466","man-girl-boy":"1F468-200D-1F467-200D-1F466","man-girl-girl":"1F468-200D-1F467-200D-1F467","man-girl":"1F468-200D-1F467","man-man-boy":"1F468-200D-1F468-200D-1F466","man-man-boy-boy":"1F468-200D-1F468-200D-1F466-200D-1F466","man-man-girl":"1F468-200D-1F468-200D-1F467","man-man-girl-boy":"1F468-200D-1F468-200D-1F467-200D-1F466","man-man-girl-girl":"1F468-200D-1F468-200D-1F467-200D-1F467","man-woman-boy":"1F468-200D-1F469-200D-1F466","man-woman-boy-boy":"1F468-200D-1F469-200D-1F466-200D-1F466","man-woman-girl":"1F468-200D-1F469-200D-1F467","man-woman-girl-boy":"1F468-200D-1F469-200D-1F467-200D-1F466","man-woman-girl-girl":"1F468-200D-1F469-200D-1F467-200D-1F467","male-technologist":"1F468-200D-1F4BB","male-office-worker":"1F468-200D-1F4BC","male-mechanic":"1F468-200D-1F527","male-scientist":"1F468-200D-1F52C","male-astronaut":"1F468-200D-1F680","male-firefighter":"1F468-200D-1F692",man_with_probing_cane:"1F468-200D-1F9AF",red_haired_man:"1F468-200D-1F9B0",curly_haired_man:"1F468-200D-1F9B1",bald_man:"1F468-200D-1F9B2",white_haired_man:"1F468-200D-1F9B3",man_in_motorized_wheelchair:"1F468-200D-1F9BC",man_in_manual_wheelchair:"1F468-200D-1F9BD","male-doctor":"1F468-200D-2695-FE0F","male-judge":"1F468-200D-2696-FE0F","male-pilot":"1F468-200D-2708-FE0F","man-heart-man":"1F468-200D-2764-FE0F-200D-1F468","man-kiss-man":"1F468-200D-2764-FE0F-200D-1F48B-200D-1F468",man:"1F468","female-farmer":"1F469-200D-1F33E","female-cook":"1F469-200D-1F373",woman_feeding_baby:"1F469-200D-1F37C","female-student":"1F469-200D-1F393","female-singer":"1F469-200D-1F3A4","female-artist":"1F469-200D-1F3A8","female-teacher":"1F469-200D-1F3EB","female-factory-worker":"1F469-200D-1F3ED","woman-boy-boy":"1F469-200D-1F466-200D-1F466","woman-boy":"1F469-200D-1F466","woman-girl-boy":"1F469-200D-1F467-200D-1F466","woman-girl-girl":"1F469-200D-1F467-200D-1F467","woman-girl":"1F469-200D-1F467","woman-woman-boy":"1F469-200D-1F469-200D-1F466","woman-woman-boy-boy":"1F469-200D-1F469-200D-1F466-200D-1F466","woman-woman-girl":"1F469-200D-1F469-200D-1F467","woman-woman-girl-boy":"1F469-200D-1F469-200D-1F467-200D-1F466","woman-woman-girl-girl":"1F469-200D-1F469-200D-1F467-200D-1F467","female-technologist":"1F469-200D-1F4BB","female-office-worker":"1F469-200D-1F4BC","female-mechanic":"1F469-200D-1F527","female-scientist":"1F469-200D-1F52C","female-astronaut":"1F469-200D-1F680","female-firefighter":"1F469-200D-1F692",woman_with_probing_cane:"1F469-200D-1F9AF",red_haired_woman:"1F469-200D-1F9B0",curly_haired_woman:"1F469-200D-1F9B1",bald_woman:"1F469-200D-1F9B2",white_haired_woman:"1F469-200D-1F9B3",woman_in_motorized_wheelchair:"1F469-200D-1F9BC",woman_in_manual_wheelchair:"1F469-200D-1F9BD","female-doctor":"1F469-200D-2695-FE0F","female-judge":"1F469-200D-2696-FE0F","female-pilot":"1F469-200D-2708-FE0F","woman-heart-man":"1F469-200D-2764-FE0F-200D-1F468","woman-heart-woman":"1F469-200D-2764-FE0F-200D-1F469","woman-kiss-man":"1F469-200D-2764-FE0F-200D-1F48B-200D-1F468","woman-kiss-woman":"1F469-200D-2764-FE0F-200D-1F48B-200D-1F469",woman:"1F469",family:"1F468-200D-1F469-200D-1F466",man_and_woman_holding_hands:"1F46B",two_men_holding_hands:"1F46C",two_women_holding_hands:"1F46D","female-police-officer":"1F46E-200D-2640-FE0F","male-police-officer":"1F46E-200D-2642-FE0F",cop:"1F46E-200D-2642-FE0F","women-with-bunny-ears-partying":"1F46F-200D-2640-FE0F","men-with-bunny-ears-partying":"1F46F-200D-2642-FE0F",dancers:"1F46F-200D-2640-FE0F",woman_with_veil:"1F470-200D-2640-FE0F",man_with_veil:"1F470-200D-2642-FE0F",bride_with_veil:"1F470","blond-haired-woman":"1F471-200D-2640-FE0F","blond-haired-man":"1F471-200D-2642-FE0F",person_with_blond_hair:"1F471-200D-2642-FE0F",man_with_gua_pi_mao:"1F472","woman-wearing-turban":"1F473-200D-2640-FE0F","man-wearing-turban":"1F473-200D-2642-FE0F",man_with_turban:"1F473-200D-2642-FE0F",older_man:"1F474",older_woman:"1F475",baby:"1F476","female-construction-worker":"1F477-200D-2640-FE0F","male-construction-worker":"1F477-200D-2642-FE0F",construction_worker:"1F477-200D-2642-FE0F",princess:"1F478",japanese_ogre:"1F479",japanese_goblin:"1F47A",ghost:"1F47B",angel:"1F47C",alien:"1F47D",space_invader:"1F47E",imp:"1F47F",skull:"1F480","woman-tipping-hand":"1F481-200D-2640-FE0F","man-tipping-hand":"1F481-200D-2642-FE0F",information_desk_person:"1F481-200D-2640-FE0F","female-guard":"1F482-200D-2640-FE0F","male-guard":"1F482-200D-2642-FE0F",guardsman:"1F482-200D-2642-FE0F",dancer:"1F483",lipstick:"1F484",nail_care:"1F485","woman-getting-massage":"1F486-200D-2640-FE0F","man-getting-massage":"1F486-200D-2642-FE0F",massage:"1F486-200D-2640-FE0F","woman-getting-haircut":"1F487-200D-2640-FE0F","man-getting-haircut":"1F487-200D-2642-FE0F",haircut:"1F487-200D-2640-FE0F",barber:"1F488",syringe:"1F489",pill:"1F48A",kiss:"1F48B",love_letter:"1F48C",ring:"1F48D",gem:"1F48E",couplekiss:"1F48F",bouquet:"1F490",couple_with_heart:"1F491",wedding:"1F492",heartbeat:"1F493",broken_heart:"1F494",two_hearts:"1F495",sparkling_heart:"1F496",heartpulse:"1F497",cupid:"1F498",blue_heart:"1F499",green_heart:"1F49A",yellow_heart:"1F49B",purple_heart:"1F49C",gift_heart:"1F49D",revolving_hearts:"1F49E",heart_decoration:"1F49F",diamond_shape_with_a_dot_inside:"1F4A0",bulb:"1F4A1",anger:"1F4A2",bomb:"1F4A3",zzz:"1F4A4",boom:"1F4A5",sweat_drops:"1F4A6",droplet:"1F4A7",dash:"1F4A8",hankey:"1F4A9",muscle:"1F4AA",dizzy:"1F4AB",speech_balloon:"1F4AC",thought_balloon:"1F4AD",white_flower:"1F4AE",100:"1F4AF",moneybag:"1F4B0",currency_exchange:"1F4B1",heavy_dollar_sign:"1F4B2",credit_card:"1F4B3",yen:"1F4B4",dollar:"1F4B5",euro:"1F4B6",pound:"1F4B7",money_with_wings:"1F4B8",chart:"1F4B9",seat:"1F4BA",computer:"1F4BB",briefcase:"1F4BC",minidisc:"1F4BD",floppy_disk:"1F4BE",cd:"1F4BF",dvd:"1F4C0",file_folder:"1F4C1",open_file_folder:"1F4C2",page_with_curl:"1F4C3",page_facing_up:"1F4C4",date:"1F4C5",calendar:"1F4C6",card_index:"1F4C7",chart_with_upwards_trend:"1F4C8",chart_with_downwards_trend:"1F4C9",bar_chart:"1F4CA",clipboard:"1F4CB",pushpin:"1F4CC",round_pushpin:"1F4CD",paperclip:"1F4CE",straight_ruler:"1F4CF",triangular_ruler:"1F4D0",bookmark_tabs:"1F4D1",ledger:"1F4D2",notebook:"1F4D3",notebook_with_decorative_cover:"1F4D4",closed_book:"1F4D5",book:"1F4D6",green_book:"1F4D7",blue_book:"1F4D8",orange_book:"1F4D9",books:"1F4DA",name_badge:"1F4DB",scroll:"1F4DC",memo:"1F4DD",telephone_receiver:"1F4DE",pager:"1F4DF",fax:"1F4E0",satellite_antenna:"1F4E1",loudspeaker:"1F4E2",mega:"1F4E3",outbox_tray:"1F4E4",inbox_tray:"1F4E5",package:"1F4E6","e-mail":"1F4E7",incoming_envelope:"1F4E8",envelope_with_arrow:"1F4E9",mailbox_closed:"1F4EA",mailbox:"1F4EB",mailbox_with_mail:"1F4EC",mailbox_with_no_mail:"1F4ED",postbox:"1F4EE",postal_horn:"1F4EF",newspaper:"1F4F0",iphone:"1F4F1",calling:"1F4F2",vibration_mode:"1F4F3",mobile_phone_off:"1F4F4",no_mobile_phones:"1F4F5",signal_strength:"1F4F6",camera:"1F4F7",camera_with_flash:"1F4F8",video_camera:"1F4F9",tv:"1F4FA",radio:"1F4FB",vhs:"1F4FC",film_projector:"1F4FD-FE0F",prayer_beads:"1F4FF",twisted_rightwards_arrows:"1F500",repeat:"1F501",repeat_one:"1F502",arrows_clockwise:"1F503",arrows_counterclockwise:"1F504",low_brightness:"1F505",high_brightness:"1F506",mute:"1F507",speaker:"1F508",sound:"1F509",loud_sound:"1F50A",battery:"1F50B",electric_plug:"1F50C",mag:"1F50D",mag_right:"1F50E",lock_with_ink_pen:"1F50F",closed_lock_with_key:"1F510",key:"1F511",lock:"1F512",unlock:"1F513",bell:"1F514",no_bell:"1F515",bookmark:"1F516",link:"1F517",radio_button:"1F518",back:"1F519",end:"1F51A",on:"1F51B",soon:"1F51C",top:"1F51D",underage:"1F51E",keycap_ten:"1F51F",capital_abcd:"1F520",abcd:"1F521",1234:"1F522",symbols:"1F523",abc:"1F524",fire:"1F525",flashlight:"1F526",wrench:"1F527",hammer:"1F528",nut_and_bolt:"1F529",hocho:"1F52A",gun:"1F52B",microscope:"1F52C",telescope:"1F52D",crystal_ball:"1F52E",six_pointed_star:"1F52F",beginner:"1F530",trident:"1F531",black_square_button:"1F532",white_square_button:"1F533",red_circle:"1F534",large_blue_circle:"1F535",large_orange_diamond:"1F536",large_blue_diamond:"1F537",small_orange_diamond:"1F538",small_blue_diamond:"1F539",small_red_triangle:"1F53A",small_red_triangle_down:"1F53B",arrow_up_small:"1F53C",arrow_down_small:"1F53D",om_symbol:"1F549-FE0F",dove_of_peace:"1F54A-FE0F",kaaba:"1F54B",mosque:"1F54C",synagogue:"1F54D",menorah_with_nine_branches:"1F54E",clock1:"1F550",clock2:"1F551",clock3:"1F552",clock4:"1F553",clock5:"1F554",clock6:"1F555",clock7:"1F556",clock8:"1F557",clock9:"1F558",clock10:"1F559",clock11:"1F55A",clock12:"1F55B",clock130:"1F55C",clock230:"1F55D",clock330:"1F55E",clock430:"1F55F",clock530:"1F560",clock630:"1F561",clock730:"1F562",clock830:"1F563",clock930:"1F564",clock1030:"1F565",clock1130:"1F566",clock1230:"1F567",candle:"1F56F-FE0F",mantelpiece_clock:"1F570-FE0F",hole:"1F573-FE0F",man_in_business_suit_levitating:"1F574-FE0F","female-detective":"1F575-FE0F-200D-2640-FE0F","male-detective":"1F575-FE0F-200D-2642-FE0F",sleuth_or_spy:"1F575-FE0F-200D-2642-FE0F",dark_sunglasses:"1F576-FE0F",spider:"1F577-FE0F",spider_web:"1F578-FE0F",joystick:"1F579-FE0F",man_dancing:"1F57A",linked_paperclips:"1F587-FE0F",lower_left_ballpoint_pen:"1F58A-FE0F",lower_left_fountain_pen:"1F58B-FE0F",lower_left_paintbrush:"1F58C-FE0F",lower_left_crayon:"1F58D-FE0F",raised_hand_with_fingers_splayed:"1F590-FE0F",middle_finger:"1F595","spock-hand":"1F596",black_heart:"1F5A4",desktop_computer:"1F5A5-FE0F",printer:"1F5A8-FE0F",three_button_mouse:"1F5B1-FE0F",trackball:"1F5B2-FE0F",frame_with_picture:"1F5BC-FE0F",card_index_dividers:"1F5C2-FE0F",card_file_box:"1F5C3-FE0F",file_cabinet:"1F5C4-FE0F",wastebasket:"1F5D1-FE0F",spiral_note_pad:"1F5D2-FE0F",spiral_calendar_pad:"1F5D3-FE0F",compression:"1F5DC-FE0F",old_key:"1F5DD-FE0F",rolled_up_newspaper:"1F5DE-FE0F",dagger_knife:"1F5E1-FE0F",speaking_head_in_silhouette:"1F5E3-FE0F",left_speech_bubble:"1F5E8-FE0F",right_anger_bubble:"1F5EF-FE0F",ballot_box_with_ballot:"1F5F3-FE0F",world_map:"1F5FA-FE0F",mount_fuji:"1F5FB",tokyo_tower:"1F5FC",statue_of_liberty:"1F5FD",japan:"1F5FE",moyai:"1F5FF",grinning:"1F600",grin:"1F601",joy:"1F602",smiley:"1F603",smile:"1F604",sweat_smile:"1F605",laughing:"1F606",innocent:"1F607",smiling_imp:"1F608",wink:"1F609",blush:"1F60A",yum:"1F60B",relieved:"1F60C",heart_eyes:"1F60D",sunglasses:"1F60E",smirk:"1F60F",neutral_face:"1F610",expressionless:"1F611",unamused:"1F612",sweat:"1F613",pensive:"1F614",confused:"1F615",confounded:"1F616",kissing:"1F617",kissing_heart:"1F618",kissing_smiling_eyes:"1F619",kissing_closed_eyes:"1F61A",stuck_out_tongue:"1F61B",stuck_out_tongue_winking_eye:"1F61C",stuck_out_tongue_closed_eyes:"1F61D",disappointed:"1F61E",worried:"1F61F",angry:"1F620",rage:"1F621",cry:"1F622",persevere:"1F623",triumph:"1F624",disappointed_relieved:"1F625",frowning:"1F626",anguished:"1F627",fearful:"1F628",weary:"1F629",sleepy:"1F62A",tired_face:"1F62B",grimacing:"1F62C",sob:"1F62D",face_exhaling:"1F62E-200D-1F4A8",open_mouth:"1F62E",hushed:"1F62F",cold_sweat:"1F630",scream:"1F631",astonished:"1F632",flushed:"1F633",sleeping:"1F634",face_with_spiral_eyes:"1F635-200D-1F4AB",dizzy_face:"1F635",face_in_clouds:"1F636-200D-1F32B-FE0F",no_mouth:"1F636",mask:"1F637",smile_cat:"1F638",joy_cat:"1F639",smiley_cat:"1F63A",heart_eyes_cat:"1F63B",smirk_cat:"1F63C",kissing_cat:"1F63D",pouting_cat:"1F63E",crying_cat_face:"1F63F",scream_cat:"1F640",slightly_frowning_face:"1F641",slightly_smiling_face:"1F642",upside_down_face:"1F643",face_with_rolling_eyes:"1F644","woman-gesturing-no":"1F645-200D-2640-FE0F","man-gesturing-no":"1F645-200D-2642-FE0F",no_good:"1F645-200D-2640-FE0F","woman-gesturing-ok":"1F646-200D-2640-FE0F","man-gesturing-ok":"1F646-200D-2642-FE0F",ok_woman:"1F646-200D-2640-FE0F","woman-bowing":"1F647-200D-2640-FE0F","man-bowing":"1F647-200D-2642-FE0F",bow:"1F647",see_no_evil:"1F648",hear_no_evil:"1F649",speak_no_evil:"1F64A","woman-raising-hand":"1F64B-200D-2640-FE0F","man-raising-hand":"1F64B-200D-2642-FE0F",raising_hand:"1F64B-200D-2640-FE0F",raised_hands:"1F64C","woman-frowning":"1F64D-200D-2640-FE0F","man-frowning":"1F64D-200D-2642-FE0F",person_frowning:"1F64D-200D-2640-FE0F","woman-pouting":"1F64E-200D-2640-FE0F","man-pouting":"1F64E-200D-2642-FE0F",person_with_pouting_face:"1F64E-200D-2640-FE0F",pray:"1F64F",rocket:"1F680",helicopter:"1F681",steam_locomotive:"1F682",railway_car:"1F683",bullettrain_side:"1F684",bullettrain_front:"1F685",train2:"1F686",metro:"1F687",light_rail:"1F688",station:"1F689",tram:"1F68A",train:"1F68B",bus:"1F68C",oncoming_bus:"1F68D",trolleybus:"1F68E",busstop:"1F68F",minibus:"1F690",ambulance:"1F691",fire_engine:"1F692",police_car:"1F693",oncoming_police_car:"1F694",taxi:"1F695",oncoming_taxi:"1F696",car:"1F697",oncoming_automobile:"1F698",blue_car:"1F699",truck:"1F69A",articulated_lorry:"1F69B",tractor:"1F69C",monorail:"1F69D",mountain_railway:"1F69E",suspension_railway:"1F69F",mountain_cableway:"1F6A0",aerial_tramway:"1F6A1",ship:"1F6A2","woman-rowing-boat":"1F6A3-200D-2640-FE0F","man-rowing-boat":"1F6A3-200D-2642-FE0F",rowboat:"1F6A3-200D-2642-FE0F",speedboat:"1F6A4",traffic_light:"1F6A5",vertical_traffic_light:"1F6A6",construction:"1F6A7",rotating_light:"1F6A8",triangular_flag_on_post:"1F6A9",door:"1F6AA",no_entry_sign:"1F6AB",smoking:"1F6AC",no_smoking:"1F6AD",put_litter_in_its_place:"1F6AE",do_not_litter:"1F6AF",potable_water:"1F6B0","non-potable_water":"1F6B1",bike:"1F6B2",no_bicycles:"1F6B3","woman-biking":"1F6B4-200D-2640-FE0F","man-biking":"1F6B4-200D-2642-FE0F",bicyclist:"1F6B4-200D-2642-FE0F","woman-mountain-biking":"1F6B5-200D-2640-FE0F","man-mountain-biking":"1F6B5-200D-2642-FE0F",mountain_bicyclist:"1F6B5-200D-2642-FE0F","woman-walking":"1F6B6-200D-2640-FE0F","man-walking":"1F6B6-200D-2642-FE0F",walking:"1F6B6-200D-2642-FE0F",no_pedestrians:"1F6B7",children_crossing:"1F6B8",mens:"1F6B9",womens:"1F6BA",restroom:"1F6BB",baby_symbol:"1F6BC",toilet:"1F6BD",wc:"1F6BE",shower:"1F6BF",bath:"1F6C0",bathtub:"1F6C1",passport_control:"1F6C2",customs:"1F6C3",baggage_claim:"1F6C4",left_luggage:"1F6C5",couch_and_lamp:"1F6CB-FE0F",sleeping_accommodation:"1F6CC",shopping_bags:"1F6CD-FE0F",bellhop_bell:"1F6CE-FE0F",bed:"1F6CF-FE0F",place_of_worship:"1F6D0",octagonal_sign:"1F6D1",shopping_trolley:"1F6D2",hindu_temple:"1F6D5",hut:"1F6D6",elevator:"1F6D7",playground_slide:"1F6DD",wheel:"1F6DE",ring_buoy:"1F6DF",hammer_and_wrench:"1F6E0-FE0F",shield:"1F6E1-FE0F",oil_drum:"1F6E2-FE0F",motorway:"1F6E3-FE0F",railway_track:"1F6E4-FE0F",motor_boat:"1F6E5-FE0F",small_airplane:"1F6E9-FE0F",airplane_departure:"1F6EB",airplane_arriving:"1F6EC",satellite:"1F6F0-FE0F",passenger_ship:"1F6F3-FE0F",scooter:"1F6F4",motor_scooter:"1F6F5",canoe:"1F6F6",sled:"1F6F7",flying_saucer:"1F6F8",skateboard:"1F6F9",auto_rickshaw:"1F6FA",pickup_truck:"1F6FB",roller_skate:"1F6FC",large_orange_circle:"1F7E0",large_yellow_circle:"1F7E1",large_green_circle:"1F7E2",large_purple_circle:"1F7E3",large_brown_circle:"1F7E4",large_red_square:"1F7E5",large_blue_square:"1F7E6",large_orange_square:"1F7E7",large_yellow_square:"1F7E8",large_green_square:"1F7E9",large_purple_square:"1F7EA",large_brown_square:"1F7EB",heavy_equals_sign:"1F7F0",pinched_fingers:"1F90C",white_heart:"1F90D",brown_heart:"1F90E",pinching_hand:"1F90F",zipper_mouth_face:"1F910",money_mouth_face:"1F911",face_with_thermometer:"1F912",nerd_face:"1F913",thinking_face:"1F914",face_with_head_bandage:"1F915",robot_face:"1F916",hugging_face:"1F917",the_horns:"1F918",call_me_hand:"1F919",raised_back_of_hand:"1F91A","left-facing_fist":"1F91B","right-facing_fist":"1F91C",handshake:"1F91D",crossed_fingers:"1F91E",i_love_you_hand_sign:"1F91F",face_with_cowboy_hat:"1F920",clown_face:"1F921",nauseated_face:"1F922",rolling_on_the_floor_laughing:"1F923",drooling_face:"1F924",lying_face:"1F925","woman-facepalming":"1F926-200D-2640-FE0F","man-facepalming":"1F926-200D-2642-FE0F",face_palm:"1F926",sneezing_face:"1F927",face_with_raised_eyebrow:"1F928","star-struck":"1F929",zany_face:"1F92A",shushing_face:"1F92B",face_with_symbols_on_mouth:"1F92C",face_with_hand_over_mouth:"1F92D",face_vomiting:"1F92E",exploding_head:"1F92F",pregnant_woman:"1F930","breast-feeding":"1F931",palms_up_together:"1F932",selfie:"1F933",prince:"1F934",woman_in_tuxedo:"1F935-200D-2640-FE0F",man_in_tuxedo:"1F935-200D-2642-FE0F",person_in_tuxedo:"1F935",mrs_claus:"1F936","woman-shrugging":"1F937-200D-2640-FE0F","man-shrugging":"1F937-200D-2642-FE0F",shrug:"1F937","woman-cartwheeling":"1F938-200D-2640-FE0F","man-cartwheeling":"1F938-200D-2642-FE0F",person_doing_cartwheel:"1F938","woman-juggling":"1F939-200D-2640-FE0F","man-juggling":"1F939-200D-2642-FE0F",juggling:"1F939",fencer:"1F93A","woman-wrestling":"1F93C-200D-2640-FE0F","man-wrestling":"1F93C-200D-2642-FE0F",wrestlers:"1F93C","woman-playing-water-polo":"1F93D-200D-2640-FE0F","man-playing-water-polo":"1F93D-200D-2642-FE0F",water_polo:"1F93D","woman-playing-handball":"1F93E-200D-2640-FE0F","man-playing-handball":"1F93E-200D-2642-FE0F",handball:"1F93E",diving_mask:"1F93F",wilted_flower:"1F940",drum_with_drumsticks:"1F941",clinking_glasses:"1F942",tumbler_glass:"1F943",spoon:"1F944",goal_net:"1F945",first_place_medal:"1F947",second_place_medal:"1F948",third_place_medal:"1F949",boxing_glove:"1F94A",martial_arts_uniform:"1F94B",curling_stone:"1F94C",lacrosse:"1F94D",softball:"1F94E",flying_disc:"1F94F",croissant:"1F950",avocado:"1F951",cucumber:"1F952",bacon:"1F953",potato:"1F954",carrot:"1F955",baguette_bread:"1F956",green_salad:"1F957",shallow_pan_of_food:"1F958",stuffed_flatbread:"1F959",egg:"1F95A",glass_of_milk:"1F95B",peanuts:"1F95C",kiwifruit:"1F95D",pancakes:"1F95E",dumpling:"1F95F",fortune_cookie:"1F960",takeout_box:"1F961",chopsticks:"1F962",bowl_with_spoon:"1F963",cup_with_straw:"1F964",coconut:"1F965",broccoli:"1F966",pie:"1F967",pretzel:"1F968",cut_of_meat:"1F969",sandwich:"1F96A",canned_food:"1F96B",leafy_green:"1F96C",mango:"1F96D",moon_cake:"1F96E",bagel:"1F96F",smiling_face_with_3_hearts:"1F970",yawning_face:"1F971",smiling_face_with_tear:"1F972",partying_face:"1F973",woozy_face:"1F974",hot_face:"1F975",cold_face:"1F976",ninja:"1F977",disguised_face:"1F978",face_holding_back_tears:"1F979",pleading_face:"1F97A",sari:"1F97B",lab_coat:"1F97C",goggles:"1F97D",hiking_boot:"1F97E",womans_flat_shoe:"1F97F",crab:"1F980",lion_face:"1F981",scorpion:"1F982",turkey:"1F983",unicorn_face:"1F984",eagle:"1F985",duck:"1F986",bat:"1F987",shark:"1F988",owl:"1F989",fox_face:"1F98A",butterfly:"1F98B",deer:"1F98C",gorilla:"1F98D",lizard:"1F98E",rhinoceros:"1F98F",shrimp:"1F990",squid:"1F991",giraffe_face:"1F992",zebra_face:"1F993",hedgehog:"1F994",sauropod:"1F995","t-rex":"1F996",cricket:"1F997",kangaroo:"1F998",llama:"1F999",peacock:"1F99A",hippopotamus:"1F99B",parrot:"1F99C",raccoon:"1F99D",lobster:"1F99E",mosquito:"1F99F",microbe:"1F9A0",badger:"1F9A1",swan:"1F9A2",mammoth:"1F9A3",dodo:"1F9A4",sloth:"1F9A5",otter:"1F9A6",orangutan:"1F9A7",skunk:"1F9A8",flamingo:"1F9A9",oyster:"1F9AA",beaver:"1F9AB",bison:"1F9AC",seal:"1F9AD",guide_dog:"1F9AE",probing_cane:"1F9AF",bone:"1F9B4",leg:"1F9B5",foot:"1F9B6",tooth:"1F9B7",female_superhero:"1F9B8-200D-2640-FE0F",male_superhero:"1F9B8-200D-2642-FE0F",superhero:"1F9B8",female_supervillain:"1F9B9-200D-2640-FE0F",male_supervillain:"1F9B9-200D-2642-FE0F",supervillain:"1F9B9",safety_vest:"1F9BA",ear_with_hearing_aid:"1F9BB",motorized_wheelchair:"1F9BC",manual_wheelchair:"1F9BD",mechanical_arm:"1F9BE",mechanical_leg:"1F9BF",cheese_wedge:"1F9C0",cupcake:"1F9C1",salt:"1F9C2",beverage_box:"1F9C3",garlic:"1F9C4",onion:"1F9C5",falafel:"1F9C6",waffle:"1F9C7",butter:"1F9C8",mate_drink:"1F9C9",ice_cube:"1F9CA",bubble_tea:"1F9CB",troll:"1F9CC",woman_standing:"1F9CD-200D-2640-FE0F",man_standing:"1F9CD-200D-2642-FE0F",standing_person:"1F9CD",woman_kneeling:"1F9CE-200D-2640-FE0F",man_kneeling:"1F9CE-200D-2642-FE0F",kneeling_person:"1F9CE",deaf_woman:"1F9CF-200D-2640-FE0F",deaf_man:"1F9CF-200D-2642-FE0F",deaf_person:"1F9CF",face_with_monocle:"1F9D0",farmer:"1F9D1-200D-1F33E",cook:"1F9D1-200D-1F373",person_feeding_baby:"1F9D1-200D-1F37C",mx_claus:"1F9D1-200D-1F384",student:"1F9D1-200D-1F393",singer:"1F9D1-200D-1F3A4",artist:"1F9D1-200D-1F3A8",teacher:"1F9D1-200D-1F3EB",factory_worker:"1F9D1-200D-1F3ED",technologist:"1F9D1-200D-1F4BB",office_worker:"1F9D1-200D-1F4BC",mechanic:"1F9D1-200D-1F527",scientist:"1F9D1-200D-1F52C",astronaut:"1F9D1-200D-1F680",firefighter:"1F9D1-200D-1F692",people_holding_hands:"1F9D1-200D-1F91D-200D-1F9D1",person_with_probing_cane:"1F9D1-200D-1F9AF",red_haired_person:"1F9D1-200D-1F9B0",curly_haired_person:"1F9D1-200D-1F9B1",bald_person:"1F9D1-200D-1F9B2",white_haired_person:"1F9D1-200D-1F9B3",person_in_motorized_wheelchair:"1F9D1-200D-1F9BC",person_in_manual_wheelchair:"1F9D1-200D-1F9BD",health_worker:"1F9D1-200D-2695-FE0F",judge:"1F9D1-200D-2696-FE0F",pilot:"1F9D1-200D-2708-FE0F",adult:"1F9D1",child:"1F9D2",older_adult:"1F9D3",woman_with_beard:"1F9D4-200D-2640-FE0F",man_with_beard:"1F9D4-200D-2642-FE0F",bearded_person:"1F9D4",person_with_headscarf:"1F9D5",woman_in_steamy_room:"1F9D6-200D-2640-FE0F",man_in_steamy_room:"1F9D6-200D-2642-FE0F",person_in_steamy_room:"1F9D6-200D-2642-FE0F",woman_climbing:"1F9D7-200D-2640-FE0F",man_climbing:"1F9D7-200D-2642-FE0F",person_climbing:"1F9D7-200D-2640-FE0F",woman_in_lotus_position:"1F9D8-200D-2640-FE0F",man_in_lotus_position:"1F9D8-200D-2642-FE0F",person_in_lotus_position:"1F9D8-200D-2640-FE0F",female_mage:"1F9D9-200D-2640-FE0F",male_mage:"1F9D9-200D-2642-FE0F",mage:"1F9D9-200D-2640-FE0F",female_fairy:"1F9DA-200D-2640-FE0F",male_fairy:"1F9DA-200D-2642-FE0F",fairy:"1F9DA-200D-2640-FE0F",female_vampire:"1F9DB-200D-2640-FE0F",male_vampire:"1F9DB-200D-2642-FE0F",vampire:"1F9DB-200D-2640-FE0F",mermaid:"1F9DC-200D-2640-FE0F",merman:"1F9DC-200D-2642-FE0F",merperson:"1F9DC-200D-2642-FE0F",female_elf:"1F9DD-200D-2640-FE0F",male_elf:"1F9DD-200D-2642-FE0F",elf:"1F9DD-200D-2642-FE0F",female_genie:"1F9DE-200D-2640-FE0F",male_genie:"1F9DE-200D-2642-FE0F",genie:"1F9DE-200D-2642-FE0F",female_zombie:"1F9DF-200D-2640-FE0F",male_zombie:"1F9DF-200D-2642-FE0F",zombie:"1F9DF-200D-2642-FE0F",brain:"1F9E0",orange_heart:"1F9E1",billed_cap:"1F9E2",scarf:"1F9E3",gloves:"1F9E4",coat:"1F9E5",socks:"1F9E6",red_envelope:"1F9E7",firecracker:"1F9E8",jigsaw:"1F9E9",test_tube:"1F9EA",petri_dish:"1F9EB",dna:"1F9EC",compass:"1F9ED",abacus:"1F9EE",fire_extinguisher:"1F9EF",toolbox:"1F9F0",bricks:"1F9F1",magnet:"1F9F2",luggage:"1F9F3",lotion_bottle:"1F9F4",thread:"1F9F5",yarn:"1F9F6",safety_pin:"1F9F7",teddy_bear:"1F9F8",broom:"1F9F9",basket:"1F9FA",roll_of_paper:"1F9FB",soap:"1F9FC",sponge:"1F9FD",receipt:"1F9FE",nazar_amulet:"1F9FF",ballet_shoes:"1FA70","one-piece_swimsuit":"1FA71",briefs:"1FA72",shorts:"1FA73",thong_sandal:"1FA74",drop_of_blood:"1FA78",adhesive_bandage:"1FA79",stethoscope:"1FA7A","x-ray":"1FA7B",crutch:"1FA7C","yo-yo":"1FA80",kite:"1FA81",parachute:"1FA82",boomerang:"1FA83",magic_wand:"1FA84",pinata:"1FA85",nesting_dolls:"1FA86",ringed_planet:"1FA90",chair:"1FA91",razor:"1FA92",axe:"1FA93",diya_lamp:"1FA94",banjo:"1FA95",military_helmet:"1FA96",accordion:"1FA97",long_drum:"1FA98",coin:"1FA99",carpentry_saw:"1FA9A",screwdriver:"1FA9B",ladder:"1FA9C",hook:"1FA9D",mirror:"1FA9E",window:"1FA9F",plunger:"1FAA0",sewing_needle:"1FAA1",knot:"1FAA2",bucket:"1FAA3",mouse_trap:"1FAA4",toothbrush:"1FAA5",headstone:"1FAA6",placard:"1FAA7",rock:"1FAA8",mirror_ball:"1FAA9",identification_card:"1FAAA",low_battery:"1FAAB",hamsa:"1FAAC",fly:"1FAB0",worm:"1FAB1",beetle:"1FAB2",cockroach:"1FAB3",potted_plant:"1FAB4",wood:"1FAB5",feather:"1FAB6",lotus:"1FAB7",coral:"1FAB8",empty_nest:"1FAB9",nest_with_eggs:"1FABA",anatomical_heart:"1FAC0",lungs:"1FAC1",people_hugging:"1FAC2",pregnant_man:"1FAC3",pregnant_person:"1FAC4",person_with_crown:"1FAC5",blueberries:"1FAD0",bell_pepper:"1FAD1",olive:"1FAD2",flatbread:"1FAD3",tamale:"1FAD4",fondue:"1FAD5",teapot:"1FAD6",pouring_liquid:"1FAD7",beans:"1FAD8",jar:"1FAD9",melting_face:"1FAE0",saluting_face:"1FAE1",face_with_open_eyes_and_hand_over_mouth:"1FAE2",face_with_peeking_eye:"1FAE3",face_with_diagonal_mouth:"1FAE4",dotted_line_face:"1FAE5",biting_lip:"1FAE6",bubbles:"1FAE7",hand_with_index_finger_and_thumb_crossed:"1FAF0",rightwards_hand:"1FAF1",leftwards_hand:"1FAF2",palm_down_hand:"1FAF3",palm_up_hand:"1FAF4",index_pointing_at_the_viewer:"1FAF5",heart_hands:"1FAF6",bangbang:"203C-FE0F",interrobang:"2049-FE0F",tm:"2122-FE0F",information_source:"2139-FE0F",left_right_arrow:"2194-FE0F",arrow_up_down:"2195-FE0F",arrow_upper_left:"2196-FE0F",arrow_upper_right:"2197-FE0F",arrow_lower_right:"2198-FE0F",arrow_lower_left:"2199-FE0F",leftwards_arrow_with_hook:"21A9-FE0F",arrow_right_hook:"21AA-FE0F",watch:"231A",hourglass:"231B",keyboard:"2328-FE0F",eject:"23CF-FE0F",fast_forward:"23E9",rewind:"23EA",arrow_double_up:"23EB",arrow_double_down:"23EC",black_right_pointing_double_triangle_with_vertical_bar:"23ED-FE0F",black_left_pointing_double_triangle_with_vertical_bar:"23EE-FE0F",black_right_pointing_triangle_with_double_vertical_bar:"23EF-FE0F",alarm_clock:"23F0",stopwatch:"23F1-FE0F",timer_clock:"23F2-FE0F",hourglass_flowing_sand:"23F3",double_vertical_bar:"23F8-FE0F",black_square_for_stop:"23F9-FE0F",black_circle_for_record:"23FA-FE0F",m:"24C2-FE0F",black_small_square:"25AA-FE0F",white_small_square:"25AB-FE0F",arrow_forward:"25B6-FE0F",arrow_backward:"25C0-FE0F",white_medium_square:"25FB-FE0F",black_medium_square:"25FC-FE0F",white_medium_small_square:"25FD",black_medium_small_square:"25FE",sunny:"2600-FE0F",cloud:"2601-FE0F",umbrella:"2602-FE0F",snowman:"2603-FE0F",comet:"2604-FE0F",phone:"260E-FE0F",ballot_box_with_check:"2611-FE0F",umbrella_with_rain_drops:"2614",coffee:"2615",shamrock:"2618-FE0F",point_up:"261D-FE0F",skull_and_crossbones:"2620-FE0F",radioactive_sign:"2622-FE0F",biohazard_sign:"2623-FE0F",orthodox_cross:"2626-FE0F",star_and_crescent:"262A-FE0F",peace_symbol:"262E-FE0F",yin_yang:"262F-FE0F",wheel_of_dharma:"2638-FE0F",white_frowning_face:"2639-FE0F",relaxed:"263A-FE0F",female_sign:"2640-FE0F",male_sign:"2642-FE0F",aries:"2648",taurus:"2649",gemini:"264A",cancer:"264B",leo:"264C",virgo:"264D",libra:"264E",scorpius:"264F",sagittarius:"2650",capricorn:"2651",aquarius:"2652",pisces:"2653",chess_pawn:"265F-FE0F",spades:"2660-FE0F",clubs:"2663-FE0F",hearts:"2665-FE0F",diamonds:"2666-FE0F",hotsprings:"2668-FE0F",recycle:"267B-FE0F",infinity:"267E-FE0F",wheelchair:"267F",hammer_and_pick:"2692-FE0F",anchor:"2693",crossed_swords:"2694-FE0F",medical_symbol:"2695-FE0F",scales:"2696-FE0F",alembic:"2697-FE0F",gear:"2699-FE0F",atom_symbol:"269B-FE0F",fleur_de_lis:"269C-FE0F",warning:"26A0-FE0F",zap:"26A1",transgender_symbol:"26A7-FE0F",white_circle:"26AA",black_circle:"26AB",coffin:"26B0-FE0F",funeral_urn:"26B1-FE0F",soccer:"26BD",baseball:"26BE",snowman_without_snow:"26C4",partly_sunny:"26C5",thunder_cloud_and_rain:"26C8-FE0F",ophiuchus:"26CE",pick:"26CF-FE0F",helmet_with_white_cross:"26D1-FE0F",chains:"26D3-FE0F",no_entry:"26D4",shinto_shrine:"26E9-FE0F",church:"26EA",mountain:"26F0-FE0F",umbrella_on_ground:"26F1-FE0F",fountain:"26F2",golf:"26F3",ferry:"26F4-FE0F",boat:"26F5",skier:"26F7-FE0F",ice_skate:"26F8-FE0F","woman-bouncing-ball":"26F9-FE0F-200D-2640-FE0F","man-bouncing-ball":"26F9-FE0F-200D-2642-FE0F",person_with_ball:"26F9-FE0F-200D-2642-FE0F",tent:"26FA",fuelpump:"26FD",scissors:"2702-FE0F",white_check_mark:"2705",airplane:"2708-FE0F",email:"2709-FE0F",fist:"270A",hand:"270B",v:"270C-FE0F",writing_hand:"270D-FE0F",pencil2:"270F-FE0F",black_nib:"2712-FE0F",heavy_check_mark:"2714-FE0F",heavy_multiplication_x:"2716-FE0F",latin_cross:"271D-FE0F",star_of_david:"2721-FE0F",sparkles:"2728",eight_spoked_asterisk:"2733-FE0F",eight_pointed_black_star:"2734-FE0F",snowflake:"2744-FE0F",sparkle:"2747-FE0F",x:"274C",negative_squared_cross_mark:"274E",question:"2753",grey_question:"2754",grey_exclamation:"2755",exclamation:"2757",heavy_heart_exclamation_mark_ornament:"2763-FE0F",heart_on_fire:"2764-FE0F-200D-1F525",mending_heart:"2764-FE0F-200D-1FA79",heart:"2764-FE0F",heavy_plus_sign:"2795",heavy_minus_sign:"2796",heavy_division_sign:"2797",arrow_right:"27A1-FE0F",curly_loop:"27B0",loop:"27BF",arrow_heading_up:"2934-FE0F",arrow_heading_down:"2935-FE0F",arrow_left:"2B05-FE0F",arrow_up:"2B06-FE0F",arrow_down:"2B07-FE0F",black_large_square:"2B1B",white_large_square:"2B1C",star:"2B50",o:"2B55",wavy_dash:"3030-FE0F",part_alternation_mark:"303D-FE0F",congratulations:"3297-FE0F",secret:"3299-FE0F"}})); define("core/emoji/picker",["exports","core/localstorage","core/emoji/data","core/utils","core/str","core/templates"],(function(_exports,_localstorage,EmojiData,_utils,_str,_templates){var obj; /** * Emoji picker. * * @module core/emoji/picker * @copyright 2019 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_localstorage=(obj=_localstorage)&&obj.__esModule?obj:{default:obj},EmojiData=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(EmojiData);const ROW_TYPE_EMOJI=0,ROW_TYPE_HEADER=1,SELECTORS_CATEGORY_SELECTOR='[data-action="show-category"]',SELECTORS_EMOJIS_CONTAINER='[data-region="emojis-container"]',SELECTORS_EMOJI_PREVIEW='[data-region="emoji-preview"]',SELECTORS_EMOJI_SHORT_NAME='[data-region="emoji-short-name"]',SELECTORS_ROW_CONTAINER='[data-region="row-container"]',SELECTORS_SEARCH_INPUT='[data-region="search-input"]',SELECTORS_SEARCH_RESULTS_CONTAINER='[data-region="search-results-container"]',createRowDataForCategory=(categoryName,categoryDisplayName,emojis,totalRowCount)=>{const rowData=[];rowData.push({index:totalRowCount+rowData.length,type:ROW_TYPE_HEADER,data:{name:categoryName,displayName:categoryDisplayName}});for(let i=0;i<emojis.length;i+=7){const rowEmojis=emojis.slice(i,i+7);rowData.push({index:totalRowCount+rowData.length,type:ROW_TYPE_EMOJI,data:rowEmojis})}return rowData},addIndexesToRowData=rowData=>rowData.map(((data,index)=>({...data,index:index}))),getCategoryScrollPositionsFromRowData=rowData=>rowData.reduce(((carry,row,index)=>(row.type===ROW_TYPE_HEADER&&(carry[row.data.name]=40*index),carry)),{}),isEmojiElement=element=>null!==element.getAttribute("data-short-names"),findCategorySelectorFromElement=element=>element?"show-category"===element.getAttribute("data-action")?element:findCategorySelectorFromElement(element.parentElement):null,getCategorySelectorByCategoryName=(root,name)=>root.querySelector('[data-category="'.concat(name,'"]')),getCategoryByScrollPosition=(root,position,categoryScrollPositions)=>{let positions=[];position<0&&(position=0);for(const categoryName in categoryScrollPositions){const categoryPosition=categoryScrollPositions[categoryName];positions.push([categoryPosition,categoryName])}positions.sort(((_ref,_ref2)=>{let[a]=_ref,[b]=_ref2;return a<b?-1:a>b?1:0}));const{categoryName:categoryName,previousPosition:previousPosition,nextPosition:nextPosition}=positions.reduce(((carry,candidate)=>{const[categoryPosition,categoryName]=candidate;return categoryPosition<=position?(carry.categoryName=categoryName,carry.previousPosition=carry.currentPosition,carry.currentPosition=position):null===carry.nextPosition&&(carry.nextPosition=categoryPosition),carry}),{categoryName:null,currentPosition:null,previousPosition:null,nextPosition:null});return[getCategorySelectorByCategoryName(root,categoryName),previousPosition,nextPosition]},getRecentEmojis=()=>{const storedData=_localstorage.default.get("moodle-recent-emojis");return storedData?JSON.parse(storedData):[]},addRecentEmoji=(rowData,recentEmojiRowCount,newEmoji)=>{const categoryName=rowData[0].data.name,categoryDisplayName=rowData[0].data.displayName,recentEmojis=getRecentEmojis();let newRecentEmojis=[newEmoji,...recentEmojis.filter((emoji=>emoji.unified!=newEmoji.unified))];newRecentEmojis=newRecentEmojis.slice(0,21);const newRecentEmojiRowData=createRowDataForCategory(categoryName,categoryDisplayName,newRecentEmojis);return(recentEmojis=>{_localstorage.default.set("moodle-recent-emojis",JSON.stringify(recentEmojis))})(newRecentEmojis),[addIndexesToRowData(newRecentEmojiRowData.concat(rowData.slice(recentEmojiRowCount))),newRecentEmojiRowData.length]},getRowsToRender=(scrollPosition,visibleRowCount,rowData)=>{const minVisibleRow=scrollPosition>40?Math.floor(scrollPosition/40):0,start=minVisibleRow>=5?minVisibleRow-5:minVisibleRow,end=minVisibleRow+visibleRowCount+5;return rowData.slice(start,end)},createRowElement=async rowData=>{let row=null;return row=rowData.type===ROW_TYPE_HEADER?await(async(rowIndex,name)=>{const context={index:rowIndex,text:name},html=await(0,_templates.render)("core/emoji/header_row",context),temp=document.createElement("div");return temp.innerHTML=html,temp.firstChild})(rowData.index,rowData.data.displayName):await(async(rowIndex,emojis)=>{const context={index:rowIndex,emojis:emojis.map((emojiData=>{const charCodes=emojiData.unified.split("-").map((code=>"0x".concat(code))),emojiText=String.fromCodePoint.apply(null,charCodes);return{shortnames:":".concat(emojiData.shortnames.join(": :"),":"),unified:emojiData.unified,text:emojiText,spacer:!1}})),spacers:Array(7-emojis.length).fill(!0)},html=await(0,_templates.render)("core/emoji/emoji_row",context),temp=document.createElement("div");return temp.innerHTML=html,temp.firstChild})(rowData.index,rowData.data),row.style.position="absolute",row.style.left=0,row.style.right=0,row.style.top="".concat(40*rowData.index,"px"),row},doRowsMatch=(a,b)=>{if(a.index!==b.index)return!1;if(a.type!==b.type)return!1;if(typeof a.data!=typeof b.data)return!1;if(a.type===ROW_TYPE_HEADER)return a.data.name===b.data.name;if(a.data.length!==b.data.length)return!1;for(let i=0;i<a.data.length;i++)if(a.data[i].unified!=b.data[i].unified)return!1;return!0},generateRenderRowsAtPositionFunction=rowContainer=>{let currentRows=[],nextRows=[],rowCount=0,isRendering=!1;const renderNextRows=async()=>{if(!nextRows.length)return;if(isRendering)return;isRendering=!0;const nextRowsToRender=nextRows.slice();nextRows=[],await(async(rowContainer,currentRows,nextRows)=>{const toAdd=nextRows.filter((nextRow=>!currentRows.some((currentRow=>doRowsMatch(currentRow,nextRow)))));let toKeep=currentRows.filter((currentRow=>nextRows.some((nextRow=>doRowsMatch(currentRow,nextRow)))));const toRemoveElements=currentRows.filter((currentRow=>!nextRows.some((nextRow=>doRowsMatch(currentRow,nextRow))))).map((rowData=>rowContainer.querySelectorAll('[data-row="'.concat(rowData.index,'"]'))));(await Promise.all(toAdd.map((rowData=>createRowElement(rowData))))).forEach(((row,index)=>{const rowData=toAdd[index];let nextRowIndex=null;for(let i=0;i<toKeep.length;i++)if(toKeep[i].index>rowData.index){nextRowIndex=i;break}if(null!==nextRowIndex){const nextRowData=toKeep[nextRowIndex],nextRowNode=rowContainer.querySelector('[data-row="'.concat(nextRowData.index,'"]'));rowContainer.insertBefore(row,nextRowNode),toKeep.splice(nextRowIndex,0,toKeep)}else toKeep.push(rowData),rowContainer.appendChild(row)})),toRemoveElements.forEach((rows=>{for(let i=0;i<rows.length;i++){const row=rows[i];rowContainer.removeChild(row)}}))})(rowContainer,currentRows,nextRowsToRender),currentRows=nextRowsToRender,isRendering=!1,renderNextRows()};return function(scrollPosition,rowData){let rowLimit=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10;nextRows=getRowsToRender(scrollPosition,rowLimit,rowData),renderNextRows(),rowCount!==rowData.length&&(rowContainer.style.height="".concat(40*rowData.length,"px")),rowCount=rowData.length}},clearSearch=(emojiContainer,searchResultsContainer,searchInput)=>{searchResultsContainer.classList.add("hidden"),emojiContainer.classList.remove("hidden"),searchInput.value=""},getHandleMouseEnter=(emojiPreview,emojiShortName)=>e=>{const target=e.target;isEmojiElement(target)&&(emojiShortName.textContent=target.getAttribute("data-short-names"),emojiPreview.textContent=target.textContent)},getHandleMouseLeave=(emojiPreview,emojiShortName)=>e=>{const target=e.target;isEmojiElement(target)&&(emojiShortName.textContent="",emojiPreview.textContent="")},getHandleScroll=(root,currentVisibleRowScrollPosition,emojiContainer,initialCategoryScrollPositions,renderAtPosition)=>{let[currentCategoryElement,previousCategoryPosition,nextCategoryPosition]=getCategoryByScrollPosition(root,emojiContainer.scrollTop,initialCategoryScrollPositions);return(categoryScrollPositions,rowData)=>{const newScrollPosition=emojiContainer.scrollTop,updateRenderRows=newScrollPosition<currentVisibleRowScrollPosition-40||newScrollPosition>currentVisibleRowScrollPosition+40;(newScrollPosition>=nextCategoryPosition||newScrollPosition<previousCategoryPosition)&&([currentCategoryElement,previousCategoryPosition,nextCategoryPosition]=getCategoryByScrollPosition(root,newScrollPosition,categoryScrollPositions),((root,element)=>{const allCategorySelectors=root.querySelectorAll(SELECTORS_CATEGORY_SELECTOR);for(let i=0;i<allCategorySelectors.length;i++)allCategorySelectors[i].classList.remove("selected");element.classList.add("selected")})(root,currentCategoryElement)),updateRenderRows&&requestAnimationFrame((()=>{renderAtPosition(newScrollPosition,rowData),currentVisibleRowScrollPosition=newScrollPosition}))}},registerEventListeners=(root,emojiContainer,renderAtPosition,currentVisibleRowScrollPosition,selectCallback,categoryScrollPositions,rowData,recentEmojiRowCount)=>{const searchInput=root.querySelector(SELECTORS_SEARCH_INPUT),searchResultsContainer=root.querySelector(SELECTORS_SEARCH_RESULTS_CONTAINER),emojiPreview=root.querySelector(SELECTORS_EMOJI_PREVIEW),emojiShortName=root.querySelector(SELECTORS_EMOJI_SHORT_NAME),clickHandler=((recentEmojiRowCount,emojiContainer,searchResultsContainer,searchInput,selectCallback,renderAtPosition)=>(e,rowData,categoryScrollPositions)=>{const target=e.target;let newRowData=rowData,newCategoryScrollPositions=categoryScrollPositions;if(clearSearch(emojiContainer,searchResultsContainer,searchInput),isEmojiElement(target)){const emojiData={unified:target.getAttribute("data-unified"),shortnames:target.getAttribute("data-short-names").replace(/:/g,"").split(" ")},currentScrollTop=emojiContainer.scrollTop,isRecentEmojiRowVisible=null!==emojiContainer.querySelector('[data-row="'.concat(recentEmojiRowCount-1,'"]'));return[newRowData,recentEmojiRowCount]=addRecentEmoji(rowData,recentEmojiRowCount,emojiData),newCategoryScrollPositions=getCategoryScrollPositionsFromRowData(newRowData),isRecentEmojiRowVisible&&renderAtPosition(currentScrollTop,newRowData),selectCallback(target.textContent),[newRowData,newCategoryScrollPositions]}const categorySelector=findCategorySelectorFromElement(target);if(categorySelector){const position=categoryScrollPositions[categorySelector.getAttribute("data-category")];emojiContainer.scrollTop=position}return[newRowData,newCategoryScrollPositions]})(recentEmojiRowCount,emojiContainer,searchResultsContainer,searchInput,selectCallback,renderAtPosition),scrollHandler=getHandleScroll(root,currentVisibleRowScrollPosition,emojiContainer,categoryScrollPositions,renderAtPosition),searchHandler=((searchInput,searchResultsContainer,emojiContainer)=>{const rowContainer=searchResultsContainer.querySelector(SELECTORS_ROW_CONTAINER),renderSearchResultsAtPosition=generateRenderRowsAtPositionFunction(rowContainer);return searchResultsContainer.appendChild(rowContainer),async()=>{const searchTerm=searchInput.value.toLowerCase();if(searchTerm){((emojiContainer,searchResultsContainer)=>{searchResultsContainer.classList.remove("hidden"),emojiContainer.classList.add("hidden")})(emojiContainer,searchResultsContainer);const matchingEmojis=Object.keys(EmojiData.byShortName).reduce(((carry,shortName)=>(shortName.includes(searchTerm)&&carry.push({shortnames:[shortName],unified:EmojiData.byShortName[shortName]}),carry)),[]),searchResultsString=await(0,_str.get_string)("searchresults","core"),rowData=createRowDataForCategory(searchResultsString,searchResultsString,matchingEmojis,0);renderSearchResultsAtPosition(0,rowData,rowData.length)}else clearSearch(emojiContainer,searchResultsContainer,searchInput)}})(searchInput,searchResultsContainer,emojiContainer);root.addEventListener("focus",getHandleMouseEnter(emojiPreview,emojiShortName),!0),root.addEventListener("blur",getHandleMouseLeave(emojiPreview,emojiShortName),!0),root.addEventListener("mouseenter",getHandleMouseEnter(emojiPreview,emojiShortName),!0),root.addEventListener("mouseleave",getHandleMouseLeave(emojiPreview,emojiShortName),!0),root.addEventListener("click",(e=>{[rowData,categoryScrollPositions]=clickHandler(e,rowData,categoryScrollPositions)})),emojiContainer.addEventListener("scroll",(0,_utils.throttle)((()=>scrollHandler(categoryScrollPositions,rowData)),50)),searchInput.addEventListener("input",(0,_utils.debounce)(searchHandler,200))};return _exports.default=(root,selectCallback)=>{const emojiContainer=root.querySelector(SELECTORS_EMOJIS_CONTAINER),rowContainer=emojiContainer.querySelector(SELECTORS_ROW_CONTAINER),allData=[{name:"Recent",emojis:getRecentEmojis()},...EmojiData.byCategory];let rowData=[],recentEmojiRowCount=0;allData.forEach((category=>{const categoryDisplayName=getCategorySelectorByCategoryName(root,category.name).title,categoryRowData=createRowDataForCategory(category.name,categoryDisplayName,category.emojis,rowData.length);"Recent"===category.name&&(recentEmojiRowCount=categoryRowData.length),rowData=rowData.concat(categoryRowData)})),rowData=addIndexesToRowData(rowData);const categoryScrollPositions=getCategoryScrollPositionsFromRowData(rowData),renderAtPosition=generateRenderRowsAtPositionFunction(rowContainer);renderAtPosition(0,rowData),registerEventListeners(root,emojiContainer,renderAtPosition,0,selectCallback,categoryScrollPositions,rowData,recentEmojiRowCount)},_exports.default})); define("core/event",["exports","core_editor/events","core_filters/events","core_form/events","jquery","core/yui"],(function(_exports,_events,_events2,_events3,_jquery,_yui){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Global registry of core events that can be triggered/listened for. * * @module core/event * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.0 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_yui=_interopRequireDefault(_yui);const getRenamedLegacyFunction=(oldFunctionName,newModule,newFunctionName,newFunctionRef)=>function(){return window.console.warn("The core/event::".concat(oldFunctionName,"() function has been moved to ").concat(newModule,"::").concat(newFunctionName,". ")+"Please update your code to use the new module."),newFunctionRef(...arguments)};var _default={Events:{FORM_FIELD_VALIDATION:"core_form-field-validation"},getLegacyEvents:()=>{const result=_jquery.default.Deferred();return window.console.warn("The getLegacyEvents function has been deprecated. Please update your code to use native events."),_yui.default.use("event","moodle-core-event",(function(){result.resolve(window.M.core.event)})),result.promise()},notifyEditorContentRestored:getRenamedLegacyFunction("notifyEditorContentRestored","core_editor/events","notifyEditorContentRestored",_events.notifyEditorContentRestored),notifyFilterContentUpdated:getRenamedLegacyFunction("notifyFilterContentUpdated","core_filters/events","notifyFilterContentUpdated",_events2.notifyFilterContentUpdated),notifyFormSubmitAjax:getRenamedLegacyFunction("notifyFormSubmitAjax","core_form/events","notifyFormSubmittedByJavascript",_events3.notifyFormSubmittedByJavascript)};return _exports.default=_default,_exports.default})); define("core/event_dispatcher",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.dispatchEvent=void 0;_exports.dispatchEvent=function(eventName){let detail=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},container=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document,{bubbles:bubbles=!0,cancelable:cancelable=!1,composed:composed=!1}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const customEvent=new CustomEvent(eventName,{bubbles:bubbles,cancelable:cancelable,composed:composed,detail:detail});return container.dispatchEvent(customEvent),customEvent}})); /** * Course selector adaptor for auto-complete form element. * * @module core/form-cohort-selector * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("core/form-cohort-selector",["core/ajax","jquery"],(function(ajax,$){return{processResults:function(selector,data){var results=[],i=0,excludelist=String($(selector).data("exclude")).split(",");for(i=0;i<data.cohorts.length;i++)-1===excludelist.indexOf(String(data.cohorts[i].id))&&results.push({value:data.cohorts[i].id,label:data.cohorts[i].name});return results},transport:function(selector,query,success,failure){var promises;void 0===query&&(query="");var calls=[{methodname:"core_cohort_search_cohorts",args:{query:query,includes:"parents",limitfrom:0,limitnum:100,context:{contextid:$(selector).data("contextid")}}}];promises=ajax.call(calls),$.when.apply($.when,promises).done((function(data){success(data)})).fail(failure)}}})); /** * Course selector adaptor for auto-complete form element. * * @module core/form-course-selector * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("core/form-course-selector",["core/ajax","jquery"],(function(ajax,$){return{processResults:function(selector,data){var results=[],i=0,excludelist=String($(selector).data("exclude")).split(",");for(i=0;i<data.courses.length;i++)-1===excludelist.indexOf(String(data.courses[i].id))&&results.push({value:data.courses[i].id,label:data.courses[i].displayname});return results},transport:function(selector,query,success,failure){var el=$(selector),requiredcapabilities=el.data("requiredcapabilities");requiredcapabilities=""!==requiredcapabilities.trim()?requiredcapabilities.split(","):[];var promises,limittoenrolled=el.data("limittoenrolled"),includefrontpage=el.data("includefrontpage"),onlywithcompletion=el.data("onlywithcompletion");void 0===query&&(query="");var calls=[{methodname:"core_course_search_courses",args:{criterianame:"search",criteriavalue:query,page:0,perpage:100,requiredcapabilities:requiredcapabilities,limittoenrolled:limittoenrolled,onlywithcompletion:onlywithcompletion}}];includefrontpage&&calls.push({methodname:"core_course_get_courses",args:{options:{ids:[includefrontpage]}}}),promises=ajax.call(calls),$.when.apply($.when,promises).done((function(data,site){if(site&&1==site.length){var frontpage=site.pop();(""===query||frontpage.fullname.toUpperCase().indexOf(query.toUpperCase())>-1||frontpage.shortname.toUpperCase().indexOf(query.toUpperCase())>-1)&&data.courses.splice(0,0,frontpage)}success(data)})).fail(failure)}}})); /** * A way to call HTML fragments to be inserted as required via JavaScript. * * @module core/fragment * @copyright 2016 Adrian Greeve <adrian@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("core/fragment",["jquery","core/ajax"],(function($,ajax){var processCollectedJavascript=function(js){var jsNodes=$(js),allScript="";return jsNodes.each((function(index,scriptNode){var tagName=(scriptNode=$(scriptNode)).prop("tagName");if(tagName&&"script"==tagName.toLowerCase())if(scriptNode.attr("src")){var exists=!1;$("script").each((function(index,s){return $(s).attr("src")==scriptNode.attr("src")&&(exists=!0),!exists})),exists||(allScript+=" { ",allScript+=' node = document.createElement("script"); ',allScript+=' node.type = "text/javascript"; ',allScript+=' node.src = decodeURI("'+encodeURI(scriptNode.attr("src"))+'"); ',allScript+=' document.getElementsByTagName("head")[0].appendChild(node); ',allScript+=" } ")}else allScript+=" "+scriptNode.text()})),allScript};return{loadFragment:function(component,callback,contextid,params){var promise=$.Deferred();return function(component,callback,contextid,params){var formattedparams=[];for(var index in params)formattedparams.push({name:index,value:params[index]});return ajax.call([{methodname:"core_get_fragment",args:{component:component,callback:callback,contextid:contextid,args:formattedparams}}])[0]}(component,callback,contextid,params).then((function(data){promise.resolve(data.html,processCollectedJavascript(data.javascript))})).fail((function(ex){promise.reject(ex)})),promise.promise()},processCollectedJavascript:function(js){return processCollectedJavascript(js)}}})); 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}})); /** * AJAX helper for the inline editing a value. * * This script is automatically included from template core/inplace_editable * It registers a click-listener on [data-inplaceeditablelink] link (the "inplace edit" icon), * then replaces the displayed value with an input field. On "Enter" it sends a request * to web service core_update_inplace_editable, which invokes the specified callback. * Any exception thrown by the web service (or callback) is displayed as an error popup. * * @module core/inplace_editable * @copyright 2016 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("core/inplace_editable",["jquery","core/ajax","core/templates","core/notification","core/str","core/config","core/url","core/form-autocomplete","core/pending","core/local/inplace_editable/events"],(function($,ajax,templates,notification,str,cfg,url,autocomplete,Pending,Events){const updateValue=function(mainelement,value,silent){var pendingId=[mainelement.attr("data-itemid"),mainelement.attr("data-component"),mainelement.attr("data-itemtype")].join("-"),pendingPromise=new Pending(pendingId);addSpinner(mainelement),ajax.call([{methodname:"core_update_inplace_editable",args:{itemid:mainelement.attr("data-itemid"),component:mainelement.attr("data-component"),itemtype:mainelement.attr("data-itemtype"),value:value}}])[0].then((function(data){return templates.render("core/inplace_editable",data).then((function(html,js){var oldvalue=mainelement.attr("data-value"),newelement=$(html);templates.replaceNode(mainelement,newelement,js),silent||newelement.find("[data-inplaceeditablelink]").focus(),Events.notifyElementUpdated(newelement.get(0),data,oldvalue)}))})).then((function(){return pendingPromise.resolve()})).fail((function(ex){var element;(element=mainelement).removeClass("updating"),element.find("img.spinner").hide(),M.util.js_complete(pendingId),Events.notifyElementUpdateFailed(mainelement.get(0),ex,value).defaultPrevented||notification.exception(ex)}))},addSpinner=function(element){element.addClass("updating");var spinner=element.find("img.spinner");spinner.length?spinner.show():(spinner=$("<img/>").attr("src",url.imageUrl("i/loading_small")).addClass("spinner").addClass("smallicon"),element.append(spinner))};return $("body").on("click keypress","[data-inplaceeditable] [data-inplaceeditablelink]",(function(e){if("keypress"!==e.type||13===e.keyCode){var editingEnabledPromise=new Pending("autocomplete-start-editing");e.stopImmediatePropagation(),e.preventDefault();var mainelement=$(this).closest("[data-inplaceeditable]"),turnEditingOff=function(el){el.find("input").off(),el.find("select").off(),el.html(el.attr("data-oldcontent")),el.removeAttr("data-oldcontent"),el.removeClass("inplaceeditingon"),el.find("[data-inplaceeditablelink]").focus(),el.parents('[data-inplace-in-draggable="true"]').attr("draggable",!0).attr("data-inplace-in-draggable",!1)},uniqueId=function(prefix,idlength){var i,uniqid=prefix;for(i=0;i<idlength;i++)uniqid+=String(Math.floor(10*Math.random()));return 0===$("#"+uniqid).length?uniqid:uniqueId(prefix,idlength)};$('[data-inplace-in-draggable="true"]').attr("draggable",!0).attr("data-inplace-in-draggable",!1),$("span.inplaceeditable.inplaceeditingon").each((function(){turnEditingOff($(this))})),function(el){el.addClass("inplaceeditingon"),el.attr("data-oldcontent",el.html());var type=el.attr("data-type"),options=el.attr("data-options");el.parents('[draggable="true"]').attr("data-inplace-in-draggable",!0).attr("draggable",!1),"toggle"===type?function(el,newvalue){turnEditingOff(el),updateValue(el,newvalue)}(el,options):"select"===type?function(el,options){var i,inputelement=$("<select></select>").attr("id",uniqueId("id_inplacevalue_",20)).addClass("custom-select"),lbl=$('<label class="accesshide">'+mainelement.attr("data-editlabel")+"</label>").attr("for",inputelement.attr("id"));for(i in options)inputelement.append($("<option>").attr("value",options[i].key).html(options[i].value));inputelement.val(el.attr("data-value")),el.html("").append(lbl).append(inputelement),inputelement.focus(),inputelement.select(),inputelement.on("keyup change focusout",(function(e){if(!cfg.behatsiterunning||"focusout"!==e.type){if("change"===e.type){var val=inputelement.val();turnEditingOff(el),updateValue(el,val)}("keyup"===e.type&&27===e.keyCode||"focusout"===e.type)&&turnEditingOff(el)}}))}(el,$.parseJSON(options)):"autocomplete"===type?function(el,args){var i,inputelement=$("<select></select>").attr("id",uniqueId("id_inplacevalue_",20)).addClass("form-autocomplete-original-select").addClass("custom-select"),lbl=$('<label class="accesshide">'+mainelement.attr("data-editlabel")+"</label>").attr("for",inputelement.attr("id")),options=args.options,attributes=args.attributes,saveelement=$('<a href="#"></a>'),cancelelement=$('<a href="#"></a>');for(i in options)inputelement.append($("<option>").attr("value",options[i].key).html(options[i].value));attributes.multiple&&inputelement.attr("multiple","true"),inputelement.val(JSON.parse(el.attr("data-value"))),str.get_string("savechanges","core").then((function(s){return templates.renderPix("e/save","core",s)})).then((function(html){saveelement.append(html)})).fail(notification.exception),str.get_string("cancel","core").then((function(s){return templates.renderPix("e/cancel","core",s)})).then((function(html){cancelelement.append(html)})).fail(notification.exception),el.html("").append(lbl).append(inputelement).append(saveelement).append(cancelelement),inputelement.focus(),inputelement.select(),autocomplete.enhance(inputelement,attributes.tags,attributes.ajax,attributes.placeholder,attributes.caseSensitive,attributes.showSuggestions,attributes.noSelectionString).then((function(){el.find("[role=combobox]").focus()})).fail(notification.exception),inputelement.on("keyup",(function(e){("keyup"===e.type&&27===e.keyCode||"focusout"===e.type)&&turnEditingOff(el)})),saveelement.on("click",(function(e){var val=JSON.stringify(inputelement.val());inputelement.empty(),turnEditingOff(el),updateValue(el,val),e.preventDefault()})),cancelelement.on("click",(function(e){inputelement.empty(),turnEditingOff(el),e.preventDefault()}))}(el,$.parseJSON(options)):function(el){str.get_string("edittitleinstructions").done((function(s){var instr=$('<span class="editinstructions">'+s+"</span>").attr("id",uniqueId("id_editinstructions_",20)),inputelement=$('<input type="text"/>').attr("id",uniqueId("id_inplacevalue_",20)).attr("value",el.attr("data-value")).attr("aria-describedby",instr.attr("id")).addClass("ignoredirty").addClass("form-control"),lbl=$('<label class="accesshide">'+mainelement.attr("data-editlabel")+"</label>").attr("for",inputelement.attr("id"));el.html("").append(instr).append(lbl).append(inputelement),inputelement.focus(),inputelement.select(),inputelement.on("keyup keypress focusout",(function(e){if(!cfg.behatsiterunning||"focusout"!==e.type){if("keypress"===e.type&&13===e.keyCode){var val=inputelement.val();turnEditingOff(el),updateValue(el,val)}("keyup"===e.type&&27===e.keyCode||"focusout"===e.type)&&turnEditingOff(el)}}))}))}(el)}(mainelement),editingEnabledPromise.resolve()}})),{getInplaceEditable:function(parent){const element=parent.querySelector("[data-inplaceeditable]");if(element)return{element:element,getValue:function(){return this.element.dataset.value},setValue:function(newvalue){updateValue($(this.element),newvalue,!0)},getItemId:function(){return this.element.dataset.itemid}}}}})); /** * A list of human readable names for the keycodes. * * @module core/key_codes * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("core/key_codes",(function(){return{tab:9,enter:13,shift:16,ctrl:17,alt:18,escape:27,space:32,end:35,home:36,arrowLeft:37,arrowUp:38,arrowRight:39,arrowDown:40,8:56,asterix:106,pageUp:33,pageDown:34}})); 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 <andrew@nicols.co.uk> * @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/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/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 <andrew@nicols.co.uk> * @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/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 <paulh@moodle.com> * @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/modal/alert",["exports","core/modal"],(function(_exports,_modal){var obj; /** * Alert modal. * * @module core/modal_alert * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @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/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 <ferran@moodle.com> * @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/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 <ferran@moodle.com> * @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/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 <ferran@moodle.com> * @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 <ferran@moodle.com> * @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 <ferran@moodle.com> * @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/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 <ferran@moodle.com> * @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/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 <ferran@moodle.com> * @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/statemanager",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;_exports.default= /** * 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 <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ 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)}))}))}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}}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/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 <davidmc@moodle.com> * @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]}})); /** * Simple API for set/get to localstorage, with cacherev expiration. * * @module core/localstorage * @class localstorage * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/localstorage",["core/config","core/storagewrapper"],(function(config,StorageWrapper){var storage=new StorageWrapper(window.localStorage);return{get:function(key){return storage.get(key)},set:function(key,value){return storage.set(key,value)}}})); /** * This is an empty module, that is required before all other modules. * Because every module is returned from a request for any other module, this * forces the loading of all modules with a single request. * * @module core/log * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/log",["core/loglevel"],(function(log){var originalFactory=log.methodFactory;return log.methodFactory=function(methodName,logLevel){var rawMethod=originalFactory(methodName,logLevel);return function(message,source){rawMethod(source?source+": "+message:message)}},log.setConfig=function(config){void 0!==config.level&&log.setLevel(config.level)},log})); var root,definition;root=window,definition=function(){var noop=function(){},isIE="undefined"!=typeof window&&void 0!==window.navigator&&/Trident\/|MSIE /.test(window.navigator.userAgent),logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if("function"==typeof method.bind)return method.bind(obj);try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}function traceForIE(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function realMethod(methodName){return"debug"===methodName&&(methodName="log"),"undefined"!=typeof console&&("trace"===methodName&&isIE?traceForIE:void 0!==console[methodName]?bindMethod(console,methodName):void 0!==console.log?bindMethod(console,"log"):noop)}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){"undefined"!=typeof console&&(replaceLoggingMethods.call(this,level,loggerName),this[methodName].apply(this,arguments))}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var currentLevel,self=this;defaultLevel=null==defaultLevel?"WARN":defaultLevel;var storageKey="loglevel";function getPersistedLevel(){var storedLevel;if("undefined"!=typeof window&&storageKey){try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(void 0===storedLevel)try{var cookie=window.document.cookie,location=cookie.indexOf(encodeURIComponent(storageKey)+"=");-1!==location&&(storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1])}catch(ignore){}return void 0===self.levels[storedLevel]&&(storedLevel=void 0),storedLevel}}"string"==typeof name?storageKey+=":"+name:"symbol"==typeof name&&(storageKey=void 0),self.name=name,self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},self.methodFactory=factory||defaultMethodFactory,self.getLevel=function(){return currentLevel},self.setLevel=function(level,persist){if("string"==typeof level&&void 0!==self.levels[level.toUpperCase()]&&(level=self.levels[level.toUpperCase()]),!("number"==typeof level&&level>=0&&level<=self.levels.SILENT))throw"log.setLevel() called with invalid level: "+level;if(currentLevel=level,!1!==persist&&function(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if("undefined"!=typeof window&&storageKey){try{return void(window.localStorage[storageKey]=levelName)}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}}(level),replaceLoggingMethods.call(self,level,name),"undefined"==typeof console&&level<self.levels.SILENT)return"No console available for logging"},self.setDefaultLevel=function(level){defaultLevel=level,getPersistedLevel()||self.setLevel(level,!1)},self.resetLevel=function(){self.setLevel(defaultLevel,!1),function(){if("undefined"!=typeof window&&storageKey){try{return void window.localStorage.removeItem(storageKey)}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(ignore){}}}()},self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)},self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();null==initialLevel&&(initialLevel=defaultLevel),self.setLevel(initialLevel,!1)}var defaultLogger=new Logger,_loggersByName={};defaultLogger.getLogger=function(name){if("symbol"!=typeof name&&"string"!=typeof name||""===name)throw new TypeError("You must supply a name when creating a logger.");var logger=_loggersByName[name];return logger||(logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)),logger};var _log="undefined"!=typeof window?window.log:void 0;return defaultLogger.noConflict=function(){return"undefined"!=typeof window&&window.log===defaultLogger&&(window.log=_log),defaultLogger},defaultLogger.getLoggers=function(){return _loggersByName},defaultLogger.default=defaultLogger,defaultLogger},"function"==typeof define&&define.amd?define("core/loglevel",definition):"object"==typeof module&&module.exports?module.exports=definition():root.log=definition(); 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 <bas@moodle.com> * @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.offsetHeight<maxHeight&&"true"!==item.dataset.forceintomoremenu){const lastNode=moreDropdown.removeChild(item);moveOutOfMoreDropdown(menu,lastNode)}})),0===Array.from(moreDropdown.children).length&&moreButton.classList.add(Selectors_classes.hidden)),menu.offsetHeight>maxHeight&&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/mustache",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var objectToString=Object.prototype.toString,isArray=Array.isArray||function(object){return"[object Array]"===objectToString.call(object)};function isFunction(object){return"function"==typeof object}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return null!=obj&&"object"==typeof obj&&propName in obj}var regExpTest=RegExp.prototype.test;var nonSpaceRe=/\S/;function isWhitespace(string){return!function(re,string){return regExpTest.call(re,string)}(nonSpaceRe,string)}var entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!|\$|</;function Scanner(string){this.string=string,this.tail=string,this.pos=0}function Context(view,parentContext){this.view=view,this.blocks={},this.cache={".":this.view},this.parent=parentContext}function Writer(){this.templateCache={_cache:{},set:function(key,value){this._cache[key]=value},get:function(key){return this._cache[key]},clear:function(){this._cache={}}}}Scanner.prototype.eos=function(){return""===this.tail},Scanner.prototype.scan=function(re){var match=this.tail.match(re);if(!match||0!==match.index)return"";var string=match[0];return this.tail=this.tail.substring(string.length),this.pos+=string.length,string},Scanner.prototype.scanUntil=function(re){var match,index=this.tail.search(re);switch(index){case-1:match=this.tail,this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index),this.tail=this.tail.substring(index)}return this.pos+=match.length,match},Context.prototype.push=function(view){return new Context(view,this)},Context.prototype.setBlockVar=function(name,value){return this.blocks[name]=value,value},Context.prototype.clearBlockVars=function(){this.blocks={}},Context.prototype.getBlockVar=function(name){var value,blocks=this.blocks;return blocks.hasOwnProperty(name)?value=blocks[name]:this.parent&&(value=this.parent.getBlockVar(name)),value},Context.prototype.parseNameAndArgs=function(name){var arg,argbuffer,parts=name.split(" "),inString=!1,first=!0,i=0,finalArgs=[];for(i=0;i<parts.length;i++)arg=parts[i],argbuffer="",inString?-1!==arg.replace("\\\\","").search(/^"$|[^\\]"$/)?(finalArgs[finalArgs.length]=argbuffer+" "+arg.substr(0,arg.length-1),argbuffer="",inString=!1):argbuffer+=" "+arg:-1===arg.search(/^"/)||first?(-1!==arg.search(/^\d+(\.\d*)?$/)?finalArgs[finalArgs.length]=parseFloat(arg):finalArgs[finalArgs.length]="true"===arg?1:"false"===arg?0:first?arg:this.lookup(arg),first=!1):-1!==arg.replace("\\\\","").search(/^".*[^\\]"$/)?finalArgs[finalArgs.length]=arg.substr(1,arg.length-2):(inString=!0,argbuffer=arg.substr(1));return finalArgs},Context.prototype.lookup=function(name){var value,primitive,propName,cache=this.cache,lambdaArgs=this.parseNameAndArgs(name);if(name=lambdaArgs.shift(),cache.hasOwnProperty(name))value=cache[name];else{for(var intermediateValue,names,index,context=this,lookupHit=!1;context;){if(name.indexOf(".")>0)for(intermediateValue=context.view,names=name.split("."),index=0;null!=intermediateValue&&index<names.length;)index===names.length-1&&(lookupHit=hasProperty(intermediateValue,names[index])||(primitive=intermediateValue,propName=names[index],null!=primitive&&"object"!=typeof primitive&&primitive.hasOwnProperty&&primitive.hasOwnProperty(propName))),intermediateValue=intermediateValue[names[index++]];else intermediateValue=context.view[name],lookupHit=hasProperty(context.view,name);if(lookupHit){value=intermediateValue;break}context=context.parent}cache[name]=value}return isFunction(value)&&(value=value.call(this.view,lambdaArgs)),value},Writer.prototype.clearCache=function(){void 0!==this.templateCache&&this.templateCache.clear()},Writer.prototype.parse=function(template,tags){var cache=this.templateCache,cacheKey=template+":"+(tags||mustache.tags).join(":"),isCacheEnabled=void 0!==cache,tokens=isCacheEnabled?cache.get(cacheKey):void 0;return null==tokens&&(tokens=function(template,tags){if(!template)return[];var openingTagRe,closingTagRe,closingCurlyRe,lineHasNonSpace=!1,sections=[],tokens=[],spaces=[],hasTag=!1,nonSpace=!1,indentation="",tagIndex=0;function stripSpace(){if(hasTag&&!nonSpace)for(;spaces.length;)delete tokens[spaces.pop()];else spaces=[];hasTag=!1,nonSpace=!1}function compileTags(tagsToCompile){if("string"==typeof tagsToCompile&&(tagsToCompile=tagsToCompile.split(spaceRe,2)),!isArray(tagsToCompile)||2!==tagsToCompile.length)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*"),closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1])),closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);for(var start,type,value,chr,token,openSection,tagName,scanner=new Scanner(template);!scanner.eos();){if(start=scanner.pos,value=scanner.scanUntil(openingTagRe))for(var i=0,valueLength=value.length;i<valueLength;++i)isWhitespace(chr=value.charAt(i))?(spaces.push(tokens.length),indentation+=chr):(nonSpace=!0,lineHasNonSpace=!0,indentation+=" "),tokens.push(["text",chr,start,start+1]),start+=1,"\n"===chr&&(stripSpace(),indentation="",tagIndex=0,lineHasNonSpace=!1);if(!scanner.scan(openingTagRe))break;if(hasTag=!0,type=scanner.scan(tagRe)||"name",scanner.scan(whiteRe),"="===type?(value=scanner.scanUntil(equalsRe),scanner.scan(equalsRe),scanner.scanUntil(closingTagRe)):"{"===type?(value=scanner.scanUntil(closingCurlyRe),scanner.scan(curlyRe),scanner.scanUntil(closingTagRe),type="&"):value=scanner.scanUntil(closingTagRe),!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);if(token=">"==type?[type,value,start,scanner.pos,indentation,tagIndex,lineHasNonSpace]:[type,value,start,scanner.pos],tagIndex++,tokens.push(token),"#"===type||"^"===type||"$"===type||"<"===type)sections.push(token);else if("/"===type){if(!(openSection=sections.pop()))throw new Error('Unopened section "'+value+'" at '+start);if((tagName=openSection[1].split(" ",1)[0])!==value.split(" ",1)[0])throw new Error('Unclosed section "'+tagName+'" at '+start)}else"name"===type||"{"===type||"&"===type?nonSpace=!0:"="===type&&compileTags(value)}if(stripSpace(),openSection=sections.pop())throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return function(tokens){for(var token,nestedTokens=[],collector=nestedTokens,sections=[],i=0,numTokens=tokens.length;i<numTokens;++i)switch((token=tokens[i])[0]){case"$":case"<":case"#":case"^":collector.push(token),sections.push(token),collector=token[4]=[];break;case"/":sections.pop()[5]=token[2],collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}return nestedTokens}(function(tokens){for(var token,lastToken,squashedTokens=[],i=0,numTokens=tokens.length;i<numTokens;++i)(token=tokens[i])&&("text"===token[0]&&lastToken&&"text"===lastToken[0]?(lastToken[1]+=token[1],lastToken[3]=token[3]):(squashedTokens.push(token),lastToken=token));return squashedTokens}(tokens))}(template,tags),isCacheEnabled&&cache.set(cacheKey,tokens)),tokens},Writer.prototype.render=function(template,view,partials,config){var tags=this.getConfigTags(config),tokens=this.parse(template,tags),context=view instanceof Context?view:new Context(view,void 0);return this.renderTokens(tokens,context,partials,template,config)},Writer.prototype.renderTokens=function(tokens,context,partials,originalTemplate,config){for(var token,symbol,value,buffer="",i=0,numTokens=tokens.length;i<numTokens;++i)value=void 0,"#"===(symbol=(token=tokens[i])[0])?value=this.renderSection(token,context,partials,originalTemplate,config):"^"===symbol?value=this.renderInverted(token,context,partials,originalTemplate,config):">"===symbol?value=this.renderPartial(token,context,partials,config):"<"===symbol?value=this.renderBlock(token,context,partials,originalTemplate,config):"$"===symbol?value=this.renderBlockVariable(token,context,partials,originalTemplate,config):"&"===symbol?value=this.unescapedValue(token,context):"name"===symbol?value=this.escapedValue(token,context,config):"text"===symbol&&(value=this.rawValue(token)),void 0!==value&&(buffer+=value);return buffer},Writer.prototype.renderSection=function(token,context,partials,originalTemplate,config){var self=this,buffer="",lambdaArgs=context.parseNameAndArgs(token[1]),name=lambdaArgs.shift(),value=context.lookup(name);if(value){if(isArray(value))for(var j=0,valueLength=value.length;j<valueLength;++j)buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate,config);else if("object"==typeof value||"string"==typeof value||"number"==typeof value)buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate,config);else if(isFunction(value)){if("string"!=typeof originalTemplate)throw new Error("Cannot use higher-order sections without the original template");null!=(value=value.call(context.view,originalTemplate.slice(token[3],token[5]),(function(template){return self.render(template,context,partials,config)}),lambdaArgs))&&(buffer+=value)}else buffer+=this.renderTokens(token[4],context,partials,originalTemplate,config);return buffer}},Writer.prototype.renderInverted=function(token,context,partials,originalTemplate,config){var value=context.lookup(token[1]);if(!value||isArray(value)&&0===value.length)return this.renderTokens(token[4],context,partials,originalTemplate,config)},Writer.prototype.indentPartial=function(partial,indentation,lineHasNonSpace){for(var filteredIndentation=indentation.replace(/[^ \t]/g,""),partialByNl=partial.split("\n"),i=0;i<partialByNl.length;i++)partialByNl[i].length&&(i>0||!lineHasNonSpace)&&(partialByNl[i]=filteredIndentation+partialByNl[i]);return partialByNl.join("\n")},Writer.prototype.renderPartial=function(token,context,partials,config){if(partials){var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(null!=value){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;0==tagIndex&&indentation&&(indentedValue=this.indentPartial(value,indentation,lineHasNonSpace));var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}}},Writer.prototype.renderBlock=function(token,context,partials,originalTemplate,config){if(partials){var value=isFunction(partials)?partials(token[1]):partials[token[1]];null!=value&&context.clearBlockVars(),this.renderTokens(token[4],context,partials,originalTemplate,config);var result=this.renderTokens(this.parse(value),context,partials,value,config);return context.clearBlockVars(),result}},Writer.prototype.renderBlockVariable=function(token,context,partials,originalTemplate,config){var value=token[1],exists=context.getBlockVar(value);return exists?this.renderTokens(this.parse(exists),context,partials,exists,config):(context.setBlockVar(value,originalTemplate.slice(token[3],token[5])),this.renderTokens(token[4],context,partials,originalTemplate,config))},Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(null!=value)return value},Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(null!=value)return"number"==typeof value&&escape===mustache.escape?String(value):escape(value)},Writer.prototype.rawValue=function(token){return token[1]},Writer.prototype.getConfigTags=function(config){return isArray(config)?config:config&&"object"==typeof config?config.tags:void 0},Writer.prototype.getConfigEscape=function(config){return config&&"object"==typeof config&&!isArray(config)?config.escape:void 0};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()},mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)},mustache.render=function(template,view,partials,config){if("string"!=typeof template)throw new TypeError('Invalid template! Template should be a "string" but "'+((isArray(obj=template)?"array":typeof obj)+'" was given as the first argument for mustache#render(template, view, partials)'));var obj;return defaultWriter.render(template,view,partials,config)},mustache.escape=function(string){return String(string).replace(/[&<>"'`=\/]/g,(function(s){return entityMap[s]}))},mustache.Scanner=Scanner,mustache.Context=Context,mustache.Writer=Writer;var _default=mustache;return _exports.default=_default,_exports.default})); /** * 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()))}}})); /** * Provide global helper code to enhance page elements. * * @module core/page_global * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/page_global",["jquery","core/custom_interaction_events","core/str","core/network"],(function($,CustomEvents,Str,Network){return{init:function(){var body;body=$("body"),CustomEvents.define(body,[CustomEvents.events.activate]),body.on(CustomEvents.events.activate,"[data-show-active-item]",(function(e){var option=$(e.target).closest(".dropdown-item"),menuContainer=option.closest("[data-show-active-item]");if(option.hasClass("dropdown-item")&&!option.hasClass("active")){var dropdownItems=menuContainer.find(".dropdown-item");dropdownItems.removeClass("active"),dropdownItems.removeAttr("aria-current"),menuContainer.attr("data-skip-active-class")||option.addClass("active"),option.attr("aria-current",!0);var activeOptionText=option.text(),dropdownToggle=menuContainer.parent().find('[data-toggle="dropdown"]'),dropdownToggleText=dropdownToggle.find("[data-active-item-text]");dropdownToggleText.length?dropdownToggleText.html(activeOptionText):dropdownToggle.html(activeOptionText);var activeItemAriaLabelComponent=menuContainer.attr("data-active-item-button-aria-label-components");if(activeItemAriaLabelComponent){var strParams=activeItemAriaLabelComponent.split(",");strParams.push(activeOptionText),Str.get_string(strParams[0].trim(),strParams[1].trim(),strParams[2].trim()).then((function(string){return dropdownToggle.attr("aria-label",string),string})).catch((function(){return!1}))}}})),Network.init()}}})); /** * Javascript to load and render a paged content section. * * @module core/paged_content * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content",["jquery","core/paged_content_pages","core/paged_content_paging_bar","core/paged_content_paging_bar_limit_selector","core/paged_content_paging_dropdown"],(function($,Pages,PagingBar,PagingBarLimitSelector,Dropdown){return{init:function(root,renderPagesContentCallback,namespaceOverride){var pagesContainer=(root=$(root)).find(Pages.rootSelector),pagingBarContainer=root.find(PagingBar.rootSelector),dropdownContainer=root.find(Dropdown.rootSelector),pagingBarLimitSelectorContainer=root.find(PagingBarLimitSelector.rootSelector),id=root.attr("id");namespaceOverride&&(id=namespaceOverride),Pages.init(pagesContainer,id,renderPagesContentCallback),pagingBarContainer.length&&PagingBar.init(pagingBarContainer,id),pagingBarLimitSelectorContainer.length&&PagingBarLimitSelector.init(pagingBarLimitSelectorContainer,id),dropdownContainer.length&&Dropdown.init(dropdownContainer,id)},rootSelector:'[data-region="paged-content-container"]'}})); /** * Events for the paged content element. * * @module core/paged_content_events * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_events",[],(function(){return{SHOW_PAGES:"core-paged-content-show-pages",PAGES_SHOWN:"core-paged-content-pages-shown",ALL_ITEMS_LOADED:"core-paged-content-all-items-loaded",SET_ITEMS_PER_PAGE_LIMIT:"core-paged-content-set-items-per-page-limit"}})); /** * Javascript for showing/hiding pages of content. * * @module core/paged_content_pages * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_pages",["jquery","core/templates","core/notification","core/pubsub","core/paged_content_events","core/pending"],(function($,Templates,Notification,PubSub,PagedContentEvents,Pending){var SELECTORS_PAGE_REGION='[data-region="paged-content-page"]',TEMPLATES_PAGING_CONTENT_ITEM="core/paged_content_page",TEMPLATES_LOADING="core/overlay_loading",findPage=function(root,pageNumber){return root.find('[data-page="'+pageNumber+'"]')},showPages=function(root,pagesData,id,renderPagesContentCallback){var pendingPromise=new Pending("core/paged_content_pages:showPages"),existingPages=[],newPageData=[],newPagesPromise=$.Deferred();if(pagesData.forEach((function(pageData){var pageNumber=pageData.pageNumber,existingPage=findPage(root,pageNumber);existingPage.length?existingPages.push(existingPage):newPageData.push(pageData)})),newPageData.length&&"function"==typeof renderPagesContentCallback){var renderPagePromises=renderPagesContentCallback(newPageData,{allItemsLoaded:function(lastPageNumber){PubSub.publish(id+PagedContentEvents.ALL_ITEMS_LOADED,lastPageNumber)}}).map((function(promise,index){return function(root,pagePromise,pageNumber){var deferred=$.Deferred();return pagePromise.then((function(html,pageJS){pageJS=pageJS||"",Templates.render(TEMPLATES_PAGING_CONTENT_ITEM,{page:pageNumber,content:html}).then((function(html){Templates.appendNodeContents(root,html,pageJS);var page=findPage(root,pageNumber);deferred.resolve(page)})).fail((function(exception){deferred.reject(exception)})).fail(Notification.exception)})).fail((function(exception){deferred.reject(exception)})).fail(Notification.exception),deferred.promise()}(root,promise,newPageData[index].pageNumber)}));$.when.apply($,renderPagePromises).then((function(){var newPages=Array.prototype.slice.call(arguments);newPagesPromise.resolve(newPages)})).fail((function(exception){newPagesPromise.reject(exception)})).fail(Notification.exception)}else newPagesPromise.resolve([]);var loadingPromise=function(root){var deferred=$.Deferred();root.attr("aria-busy",!0);var pendingPromise=new Pending("core/paged_content_pages:startLoading");return Templates.render(TEMPLATES_LOADING,{visible:!0}).then((function(html){var loadingSpinner=$(html),timerId=setTimeout((function(){root.css("position","relative"),loadingSpinner.appendTo(root)}),300);deferred.always((function(){clearTimeout(timerId),loadingSpinner.remove(),root.css("position",""),root.removeAttr("aria-busy"),pendingPromise.resolve()}))})).fail(Notification.exception),deferred}(root);newPagesPromise.then((function(newPages){var pagesToShow=existingPages.concat(newPages);root.find(SELECTORS_PAGE_REGION).addClass("hidden"),pagesToShow.forEach((function(page){page.removeClass("hidden")}))})).then((function(){PubSub.publish(id+PagedContentEvents.PAGES_SHOWN,pagesData)})).fail(Notification.exception).always((function(){loadingPromise.resolve(),pendingPromise.resolve()})).catch()};return{init:function(root,id,renderPagesContentCallback){root=$(root),PubSub.subscribe(id+PagedContentEvents.SHOW_PAGES,(function(pagesData){showPages(root,pagesData,id,renderPagesContentCallback)})),PubSub.subscribe(id+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT,(function(){root.empty()}))},rootSelector:'[data-region="page-container"]'}})); /** * Javascript for dynamically changing the page limits. * * @module core/paged_content_paging_bar_limit_selector * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @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"]'}})); /** * Javascript to manage the paging dropdown control. * * @module core/paged_content_paging_dropdown * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @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))<pageNumber}))},getLimit=function(item){return parseInt(item.attr("data-item-count"),10)},getOffset=function(root,item){if(null!=item.attr("data-offset"))return parseInt(item.attr("data-offset"),10);var offset=0;return getPreviousItems(root,item).each((function(index,prevItem){prevItem=$(prevItem),offset+=getLimit(prevItem)})),item.attr("data-offset",offset),offset},getActiveItem=function(root){return root.find(SELECTORS_ACTIVE_DROPDOWN_ITEM)},setActiveItem=function(root,item,id){var eventPayload=function(root,items){return items.map((function(index,item){return item=$(item),{pageNumber:getPageNumber(item),limit:getLimit(item),offset:getOffset(root,item)}})).get()}(root,getPreviousItems(root,item).add(item)),toggle=root.find(SELECTORS_DROPDOWN_TOGGLE),caret=toggle.find(SELECTORS_CARET);getActiveItem(root).removeClass("active"),item.addClass("active"),toggle.html(item.text()),toggle.append(caret),PubSub.publish(id+PagedContentEvents.SHOW_PAGES,eventPayload)};return{init:function(root,id){root=$(root),function(items){items.each((function(index,item){(item=$(item)).attr("data-page-number",index+1)}))}(getAllItems(root));var activeItem=getActiveItem(root);activeItem.length&&setActiveItem(root,activeItem,id),CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_DROPDOWN_ITEM,(function(e,data){var item=$(e.target).closest(SELECTORS_DROPDOWN_ITEM);setActiveItem(root,item,id),data.originalEvent.preventDefault()}))},rootSelector:'[data-region="paging-dropdown-container"]'}})); /** * @copyright 2015 Martin Mastny <mastnym@vscht.cz> * @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)}}})); /** * Controls the popover region element. * * See template: core/popover_region * * @module core/popover_region_controller * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("core/popover_region_controller",["jquery","core/str","core/custom_interaction_events"],(function($,str,customEvents){var SELECTORS_CONTENT=".popover-region-content",SELECTORS_CONTENT_CONTAINER=".popover-region-content-container",SELECTORS_MENU_CONTAINER=".popover-region-container",SELECTORS_MENU_TOGGLE=".popover-region-toggle",SELECTORS_CAN_RECEIVE_FOCUS='input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',PopoverRegionController=function(element){this.root=$(element),this.content=this.root.find(SELECTORS_CONTENT),this.contentContainer=this.root.find(SELECTORS_CONTENT_CONTAINER),this.menuContainer=this.root.find(SELECTORS_MENU_CONTAINER),this.menuToggle=this.root.find(SELECTORS_MENU_TOGGLE),this.isLoading=!1,this.promises={closeHandlers:$.Deferred(),navigationHandlers:$.Deferred()},this.registerBaseEventListeners()};return PopoverRegionController.prototype.events=function(){return{menuOpened:"popoverregion:menuopened",menuClosed:"popoverregion:menuclosed",startLoading:"popoverregion:startLoading",stopLoading:"popoverregion:stopLoading"}},PopoverRegionController.prototype.getContentContainer=function(){return this.contentContainer},PopoverRegionController.prototype.getContent=function(){return this.content},PopoverRegionController.prototype.isMenuOpen=function(){return!this.root.hasClass("collapsed")},PopoverRegionController.prototype.toggleMenu=function(){this.isMenuOpen()?this.closeMenu():this.openMenu()},PopoverRegionController.prototype.closeMenu=function(){this.isMenuOpen()&&(this.root.addClass("collapsed"),this.menuContainer.attr("aria-expanded","false"),this.menuContainer.attr("aria-hidden","true"),this.updateButtonAriaLabel(),this.updateFocusItemTabIndex(),this.root.trigger(this.events().menuClosed))},PopoverRegionController.prototype.openMenu=function(){this.isMenuOpen()||(this.root.removeClass("collapsed"),this.menuContainer.attr("aria-expanded","true"),this.menuContainer.attr("aria-hidden","false"),this.updateButtonAriaLabel(),this.updateFocusItemTabIndex(),this.promises.closeHandlers.resolve(),this.promises.navigationHandlers.resolve(),this.root.trigger(this.events().menuOpened))},PopoverRegionController.prototype.updateButtonAriaLabel=function(){this.isMenuOpen()?str.get_string("hidepopoverwindow").done(function(string){this.menuToggle.attr("aria-label",string)}.bind(this)):str.get_string("showpopoverwindow").done(function(string){this.menuToggle.attr("aria-label",string)}.bind(this))},PopoverRegionController.prototype.startLoading=function(){this.isLoading=!0,this.getContentContainer().addClass("loading"),this.getContentContainer().attr("aria-busy","true"),this.root.trigger(this.events().startLoading)},PopoverRegionController.prototype.stopLoading=function(){this.isLoading=!1,this.getContentContainer().removeClass("loading"),this.getContentContainer().attr("aria-busy","false"),this.root.trigger(this.events().stopLoading)},PopoverRegionController.prototype.focusMenuToggle=function(){this.menuToggle.focus()},PopoverRegionController.prototype.contentItemHasFocus=function(){return this.getContentItemWithFocus().length>0},PopoverRegionController.prototype.getContentItemWithFocus=function(){var currentFocus=$(document.activeElement),items=this.getContent().children(),currentItem=items.filter(currentFocus);return currentItem.length||(currentItem=items.has(currentFocus)),currentItem},PopoverRegionController.prototype.focusContentItem=function(item){item.is(SELECTORS_CAN_RECEIVE_FOCUS)?item.focus():item.find(SELECTORS_CAN_RECEIVE_FOCUS).first().focus()},PopoverRegionController.prototype.focusFirstContentItem=function(){this.focusContentItem(this.getContent().children().first())},PopoverRegionController.prototype.focusLastContentItem=function(){this.focusContentItem(this.getContent().children().last())},PopoverRegionController.prototype.focusNextContentItem=function(){var currentItem=this.getContentItemWithFocus();currentItem.length&¤tItem.next()&&this.focusContentItem(currentItem.next())},PopoverRegionController.prototype.focusPreviousContentItem=function(){var currentItem=this.getContentItemWithFocus();currentItem.length&¤tItem.prev()&&this.focusContentItem(currentItem.prev())},PopoverRegionController.prototype.registerBaseEventListeners=function(){customEvents.define(this.root,[customEvents.events.activate,customEvents.events.escape]),this.root.on(customEvents.events.activate,SELECTORS_MENU_TOGGLE,function(){this.toggleMenu()}.bind(this)),this.promises.closeHandlers.done(function(){this.root.on(customEvents.events.escape,function(){this.closeMenu(),this.focusMenuToggle()}.bind(this)),$("html").click(function(e){var target=$(e.target);this.root.is(target)||this.root.has(target).length||this.closeMenu()}.bind(this)),customEvents.define(this.getContentContainer(),[customEvents.events.scrollBottom])}.bind(this))},PopoverRegionController.prototype.registerListNavigationEventListeners=function(){customEvents.define(this.root,[customEvents.events.down]),this.root.on(customEvents.events.down,function(e,data){this.isMenuOpen()?this.contentItemHasFocus()?this.focusNextContentItem():this.focusFirstContentItem():(this.openMenu(),this.focusFirstContentItem()),data.originalEvent.preventDefault()}.bind(this)),this.promises.navigationHandlers.done(function(){customEvents.define(this.root,[customEvents.events.up,customEvents.events.home,customEvents.events.end]),this.root.on(customEvents.events.up,function(e,data){this.focusPreviousContentItem(),data.originalEvent.preventDefault()}.bind(this)),this.root.on(customEvents.events.home,function(e,data){this.focusFirstContentItem(),data.originalEvent.preventDefault()}.bind(this)),this.root.on(customEvents.events.end,function(e,data){this.focusLastContentItem(),data.originalEvent.preventDefault()}.bind(this))}.bind(this))},PopoverRegionController.prototype.updateFocusItemTabIndex=function(){this.isMenuOpen()?this.menuContainer.find(SELECTORS_CAN_RECEIVE_FOCUS).removeAttr("tabindex"):this.menuContainer.find(SELECTORS_CAN_RECEIVE_FOCUS).attr("tabindex","-1")},PopoverRegionController})); /**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.12.6 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define("core/popper",factory):global.Popper=factory()}(window,(function(){for(var isBrowser="undefined"!=typeof window&&void 0!==window.document,longerTimeoutBrowsers=["Edge","Trident","Firefox"],timeoutDuration=0,i=0;i<longerTimeoutBrowsers.length;i+=1)if(isBrowser&&navigator.userAgent.indexOf(longerTimeoutBrowsers[i])>=0){timeoutDuration=1;break}var debounce=isBrowser&&window.Promise?function(fn){var called=!1;return function(){called||(called=!0,Promise.resolve().then((function(){called=!1,fn()})))}}:function(fn){var scheduled=!1;return function(){scheduled||(scheduled=!0,setTimeout((function(){scheduled=!1,fn()}),timeoutDuration))}};function isFunction(functionToCheck){return functionToCheck&&"[object Function]"==={}.toString.call(functionToCheck)}function getStyleComputedProperty(element,property){if(1!==element.nodeType)return[];var css=window.getComputedStyle(element,null);return property?css[property]:css}function getParentNode(element){return"HTML"===element.nodeName?element:element.parentNode||element.host}function getScrollParent(element){if(!element)return window.document.body;switch(element.nodeName){case"HTML":case"BODY":return element.ownerDocument.body;case"#document":return element.body}var _getStyleComputedProp=getStyleComputedProperty(element),overflow=_getStyleComputedProp.overflow,overflowX=_getStyleComputedProp.overflowX,overflowY=_getStyleComputedProp.overflowY;return/(auto|scroll)/.test(overflow+overflowY+overflowX)?element:getScrollParent(getParentNode(element))}function getOffsetParent(element){var offsetParent=element&&element.offsetParent,nodeName=offsetParent&&offsetParent.nodeName;return nodeName&&"BODY"!==nodeName&&"HTML"!==nodeName?-1!==["TD","TABLE"].indexOf(offsetParent.nodeName)&&"static"===getStyleComputedProperty(offsetParent,"position")?getOffsetParent(offsetParent):offsetParent:element?element.ownerDocument.documentElement:window.document.documentElement}function getRoot(node){return null!==node.parentNode?getRoot(node.parentNode):node}function findCommonOffsetParent(element1,element2){if(!(element1&&element1.nodeType&&element2&&element2.nodeType))return window.document.documentElement;var order=element1.compareDocumentPosition(element2)&Node.DOCUMENT_POSITION_FOLLOWING,start=order?element1:element2,end=order?element2:element1,range=document.createRange();range.setStart(start,0),range.setEnd(end,0);var element,nodeName,commonAncestorContainer=range.commonAncestorContainer;if(element1!==commonAncestorContainer&&element2!==commonAncestorContainer||start.contains(end))return"BODY"===(nodeName=(element=commonAncestorContainer).nodeName)||"HTML"!==nodeName&&getOffsetParent(element.firstElementChild)!==element?getOffsetParent(commonAncestorContainer):commonAncestorContainer;var element1root=getRoot(element1);return element1root.host?findCommonOffsetParent(element1root.host,element2):findCommonOffsetParent(element1,getRoot(element2).host)}function getScroll(element){var side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"top",upperSide="top"===side?"scrollTop":"scrollLeft",nodeName=element.nodeName;if("BODY"===nodeName||"HTML"===nodeName){var html=element.ownerDocument.documentElement,scrollingElement=element.ownerDocument.scrollingElement||html;return scrollingElement[upperSide]}return element[upperSide]}function getBordersSize(styles,axis){var sideA="x"===axis?"Left":"Top",sideB="Left"===sideA?"Right":"Bottom";return+styles["border"+sideA+"Width"].split("px")[0]+ +styles["border"+sideB+"Width"].split("px")[0]}var isIE10=void 0,isIE10$1=function(){return void 0===isIE10&&(isIE10=-1!==navigator.appVersion.indexOf("MSIE 10")),isIE10};function getSize(axis,body,html,computedStyle){return Math.max(body["offset"+axis],body["scroll"+axis],html["client"+axis],html["offset"+axis],html["scroll"+axis],isIE10$1()?html["offset"+axis]+computedStyle["margin"+("Height"===axis?"Top":"Left")]+computedStyle["margin"+("Height"===axis?"Bottom":"Right")]:0)}function getWindowSizes(){var body=window.document.body,html=window.document.documentElement,computedStyle=isIE10$1()&&window.getComputedStyle(html);return{height:getSize("Height",body,html,computedStyle),width:getSize("Width",body,html,computedStyle)}}var classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")},createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),defineProperty=function(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj},_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};function getClientRect(offsets){return _extends({},offsets,{right:offsets.left+offsets.width,bottom:offsets.top+offsets.height})}function getBoundingClientRect(element){var rect={};if(isIE10$1())try{rect=element.getBoundingClientRect();var scrollTop=getScroll(element,"top"),scrollLeft=getScroll(element,"left");rect.top+=scrollTop,rect.left+=scrollLeft,rect.bottom+=scrollTop,rect.right+=scrollLeft}catch(err){}else rect=element.getBoundingClientRect();var result={left:rect.left,top:rect.top,width:rect.right-rect.left,height:rect.bottom-rect.top},sizes="HTML"===element.nodeName?getWindowSizes():{},width=sizes.width||element.clientWidth||result.right-result.left,height=sizes.height||element.clientHeight||result.bottom-result.top,horizScrollbar=element.offsetWidth-width,vertScrollbar=element.offsetHeight-height;if(horizScrollbar||vertScrollbar){var styles=getStyleComputedProperty(element);horizScrollbar-=getBordersSize(styles,"x"),vertScrollbar-=getBordersSize(styles,"y"),result.width-=horizScrollbar,result.height-=vertScrollbar}return getClientRect(result)}function getOffsetRectRelativeToArbitraryNode(children,parent){var isIE10=isIE10$1(),isHTML="HTML"===parent.nodeName,childrenRect=getBoundingClientRect(children),parentRect=getBoundingClientRect(parent),scrollParent=getScrollParent(children),styles=getStyleComputedProperty(parent),borderTopWidth=+styles.borderTopWidth.split("px")[0],borderLeftWidth=+styles.borderLeftWidth.split("px")[0],offsets=getClientRect({top:childrenRect.top-parentRect.top-borderTopWidth,left:childrenRect.left-parentRect.left-borderLeftWidth,width:childrenRect.width,height:childrenRect.height});if(offsets.marginTop=0,offsets.marginLeft=0,!isIE10&&isHTML){var marginTop=+styles.marginTop.split("px")[0],marginLeft=+styles.marginLeft.split("px")[0];offsets.top-=borderTopWidth-marginTop,offsets.bottom-=borderTopWidth-marginTop,offsets.left-=borderLeftWidth-marginLeft,offsets.right-=borderLeftWidth-marginLeft,offsets.marginTop=marginTop,offsets.marginLeft=marginLeft}return(isIE10?parent.contains(scrollParent):parent===scrollParent&&"BODY"!==scrollParent.nodeName)&&(offsets=function(rect,element){var subtract=arguments.length>2&&void 0!==arguments[2]&&arguments[2],scrollTop=getScroll(element,"top"),scrollLeft=getScroll(element,"left"),modifier=subtract?-1:1;return rect.top+=scrollTop*modifier,rect.bottom+=scrollTop*modifier,rect.left+=scrollLeft*modifier,rect.right+=scrollLeft*modifier,rect}(offsets,parent)),offsets}function isFixed(element){var nodeName=element.nodeName;return"BODY"!==nodeName&&"HTML"!==nodeName&&("fixed"===getStyleComputedProperty(element,"position")||isFixed(getParentNode(element)))}function getBoundaries(popper,reference,padding,boundariesElement){var boundaries={top:0,left:0},offsetParent=findCommonOffsetParent(popper,reference);if("viewport"===boundariesElement)boundaries=function(element){var html=element.ownerDocument.documentElement,relativeOffset=getOffsetRectRelativeToArbitraryNode(element,html),width=Math.max(html.clientWidth,window.innerWidth||0),height=Math.max(html.clientHeight,window.innerHeight||0),scrollTop=getScroll(html),scrollLeft=getScroll(html,"left");return getClientRect({top:scrollTop-relativeOffset.top+relativeOffset.marginTop,left:scrollLeft-relativeOffset.left+relativeOffset.marginLeft,width:width,height:height})}(offsetParent);else{var boundariesNode=void 0;"scrollParent"===boundariesElement?"BODY"===(boundariesNode=getScrollParent(getParentNode(popper))).nodeName&&(boundariesNode=popper.ownerDocument.documentElement):boundariesNode="window"===boundariesElement?popper.ownerDocument.documentElement:boundariesElement;var offsets=getOffsetRectRelativeToArbitraryNode(boundariesNode,offsetParent);if("HTML"!==boundariesNode.nodeName||isFixed(offsetParent))boundaries=offsets;else{var _getWindowSizes=getWindowSizes(),height=_getWindowSizes.height,width=_getWindowSizes.width;boundaries.top+=offsets.top-offsets.marginTop,boundaries.bottom=height+offsets.top,boundaries.left+=offsets.left-offsets.marginLeft,boundaries.right=width+offsets.left}}return boundaries.left+=padding,boundaries.top+=padding,boundaries.right-=padding,boundaries.bottom-=padding,boundaries}function getArea(_ref){return _ref.width*_ref.height}function computeAutoPlacement(placement,refRect,popper,reference,boundariesElement){var padding=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;if(-1===placement.indexOf("auto"))return placement;var boundaries=getBoundaries(popper,reference,padding,boundariesElement),rects={top:{width:boundaries.width,height:refRect.top-boundaries.top},right:{width:boundaries.right-refRect.right,height:boundaries.height},bottom:{width:boundaries.width,height:boundaries.bottom-refRect.bottom},left:{width:refRect.left-boundaries.left,height:boundaries.height}},sortedAreas=Object.keys(rects).map((function(key){return _extends({key:key},rects[key],{area:getArea(rects[key])})})).sort((function(a,b){return b.area-a.area})),filteredAreas=sortedAreas.filter((function(_ref2){var width=_ref2.width,height=_ref2.height;return width>=popper.clientWidth&&height>=popper.clientHeight})),computedPlacement=filteredAreas.length>0?filteredAreas[0].key:sortedAreas[0].key,variation=placement.split("-")[1];return computedPlacement+(variation?"-"+variation:"")}function getReferenceOffsets(state,popper,reference){return getOffsetRectRelativeToArbitraryNode(reference,findCommonOffsetParent(popper,reference))}function getOuterSizes(element){var styles=window.getComputedStyle(element),x=parseFloat(styles.marginTop)+parseFloat(styles.marginBottom),y=parseFloat(styles.marginLeft)+parseFloat(styles.marginRight);return{width:element.offsetWidth+y,height:element.offsetHeight+x}}function getOppositePlacement(placement){var hash={left:"right",right:"left",bottom:"top",top:"bottom"};return placement.replace(/left|right|bottom|top/g,(function(matched){return hash[matched]}))}function getPopperOffsets(popper,referenceOffsets,placement){placement=placement.split("-")[0];var popperRect=getOuterSizes(popper),popperOffsets={width:popperRect.width,height:popperRect.height},isHoriz=-1!==["right","left"].indexOf(placement),mainSide=isHoriz?"top":"left",secondarySide=isHoriz?"left":"top",measurement=isHoriz?"height":"width",secondaryMeasurement=isHoriz?"width":"height";return popperOffsets[mainSide]=referenceOffsets[mainSide]+referenceOffsets[measurement]/2-popperRect[measurement]/2,popperOffsets[secondarySide]=placement===secondarySide?referenceOffsets[secondarySide]-popperRect[secondaryMeasurement]:referenceOffsets[getOppositePlacement(secondarySide)],popperOffsets}function find(arr,check){return Array.prototype.find?arr.find(check):arr.filter(check)[0]}function runModifiers(modifiers,data,ends){return(void 0===ends?modifiers:modifiers.slice(0,function(arr,prop,value){if(Array.prototype.findIndex)return arr.findIndex((function(cur){return cur[prop]===value}));var match=find(arr,(function(obj){return obj[prop]===value}));return arr.indexOf(match)}(modifiers,"name",ends))).forEach((function(modifier){modifier.function&&console.warn("`modifier.function` is deprecated, use `modifier.fn`!");var fn=modifier.function||modifier.fn;modifier.enabled&&isFunction(fn)&&(data.offsets.popper=getClientRect(data.offsets.popper),data.offsets.reference=getClientRect(data.offsets.reference),data=fn(data,modifier))})),data}function update(){if(!this.state.isDestroyed){var data={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}};data.offsets.reference=getReferenceOffsets(this.state,this.popper,this.reference),data.placement=computeAutoPlacement(this.options.placement,data.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),data.originalPlacement=data.placement,data.offsets.popper=getPopperOffsets(this.popper,data.offsets.reference,data.placement),data.offsets.popper.position="absolute",data=runModifiers(this.modifiers,data),this.state.isCreated?this.options.onUpdate(data):(this.state.isCreated=!0,this.options.onCreate(data))}}function isModifierEnabled(modifiers,modifierName){return modifiers.some((function(_ref){var name=_ref.name;return _ref.enabled&&name===modifierName}))}function getSupportedPropertyName(property){for(var prefixes=[!1,"ms","Webkit","Moz","O"],upperProp=property.charAt(0).toUpperCase()+property.slice(1),i=0;i<prefixes.length-1;i++){var prefix=prefixes[i],toCheck=prefix?""+prefix+upperProp:property;if(void 0!==window.document.body.style[toCheck])return toCheck}return null}function destroy(){return this.state.isDestroyed=!0,isModifierEnabled(this.modifiers,"applyStyle")&&(this.popper.removeAttribute("x-placement"),this.popper.style.left="",this.popper.style.position="",this.popper.style.top="",this.popper.style[getSupportedPropertyName("transform")]=""),this.disableEventListeners(),this.options.removeOnDestroy&&this.popper.parentNode.removeChild(this.popper),this}function getWindow(element){var ownerDocument=element.ownerDocument;return ownerDocument?ownerDocument.defaultView:window}function attachToScrollParents(scrollParent,event,callback,scrollParents){var isBody="BODY"===scrollParent.nodeName,target=isBody?scrollParent.ownerDocument.defaultView:scrollParent;target.addEventListener(event,callback,{passive:!0}),isBody||attachToScrollParents(getScrollParent(target.parentNode),event,callback,scrollParents),scrollParents.push(target)}function setupEventListeners(reference,options,state,updateBound){state.updateBound=updateBound,getWindow(reference).addEventListener("resize",state.updateBound,{passive:!0});var scrollElement=getScrollParent(reference);return attachToScrollParents(scrollElement,"scroll",state.updateBound,state.scrollParents),state.scrollElement=scrollElement,state.eventsEnabled=!0,state}function enableEventListeners(){this.state.eventsEnabled||(this.state=setupEventListeners(this.reference,this.options,this.state,this.scheduleUpdate))}function disableEventListeners(){var reference,state;this.state.eventsEnabled&&(window.cancelAnimationFrame(this.scheduleUpdate),this.state=(reference=this.reference,state=this.state,getWindow(reference).removeEventListener("resize",state.updateBound),state.scrollParents.forEach((function(target){target.removeEventListener("scroll",state.updateBound)})),state.updateBound=null,state.scrollParents=[],state.scrollElement=null,state.eventsEnabled=!1,state))}function isNumeric(n){return""!==n&&!isNaN(parseFloat(n))&&isFinite(n)}function setStyles(element,styles){Object.keys(styles).forEach((function(prop){var unit="";-1!==["width","height","top","right","bottom","left"].indexOf(prop)&&isNumeric(styles[prop])&&(unit="px"),element.style[prop]=styles[prop]+unit}))}function isModifierRequired(modifiers,requestingName,requestedName){var requesting=find(modifiers,(function(_ref){return _ref.name===requestingName})),isRequired=!!requesting&&modifiers.some((function(modifier){return modifier.name===requestedName&&modifier.enabled&&modifier.order<requesting.order}));if(!isRequired){var _requesting="`"+requestingName+"`",requested="`"+requestedName+"`";console.warn(requested+" modifier is required by "+_requesting+" modifier in order to work, be sure to include it before "+_requesting+"!")}return isRequired}var placements=["auto-start","auto","auto-end","top-start","top","top-end","right-start","right","right-end","bottom-end","bottom","bottom-start","left-end","left","left-start"],validPlacements=placements.slice(3);function clockwise(placement){var counter=arguments.length>1&&void 0!==arguments[1]&&arguments[1],index=validPlacements.indexOf(placement),arr=validPlacements.slice(index+1).concat(validPlacements.slice(0,index));return counter?arr.reverse():arr}var BEHAVIORS_FLIP="flip",BEHAVIORS_CLOCKWISE="clockwise",BEHAVIORS_COUNTERCLOCKWISE="counterclockwise";function parseOffset(offset,popperOffsets,referenceOffsets,basePlacement){var offsets=[0,0],useHeight=-1!==["right","left"].indexOf(basePlacement),fragments=offset.split(/(\+|\-)/).map((function(frag){return frag.trim()})),divider=fragments.indexOf(find(fragments,(function(frag){return-1!==frag.search(/,|\s/)})));fragments[divider]&&-1===fragments[divider].indexOf(",")&&console.warn("Offsets separated by white space(s) are deprecated, use a comma (,) instead.");var splitRegex=/\s*,\s*|\s+/,ops=-1!==divider?[fragments.slice(0,divider).concat([fragments[divider].split(splitRegex)[0]]),[fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider+1))]:[fragments];return ops=ops.map((function(op,index){var measurement=(1===index?!useHeight:useHeight)?"height":"width",mergeWithPrevious=!1;return op.reduce((function(a,b){return""===a[a.length-1]&&-1!==["+","-"].indexOf(b)?(a[a.length-1]=b,mergeWithPrevious=!0,a):mergeWithPrevious?(a[a.length-1]+=b,mergeWithPrevious=!1,a):a.concat(b)}),[]).map((function(str){return function(str,measurement,popperOffsets,referenceOffsets){var split=str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/),value=+split[1],unit=split[2];if(!value)return str;if(0===unit.indexOf("%")){return getClientRect("%p"===unit?popperOffsets:referenceOffsets)[measurement]/100*value}if("vh"===unit||"vw"===unit)return("vh"===unit?Math.max(document.documentElement.clientHeight,window.innerHeight||0):Math.max(document.documentElement.clientWidth,window.innerWidth||0))/100*value;return value}(str,measurement,popperOffsets,referenceOffsets)}))})),ops.forEach((function(op,index){op.forEach((function(frag,index2){isNumeric(frag)&&(offsets[index]+=frag*("-"===op[index2-1]?-1:1))}))})),offsets}var modifiers={shift:{order:100,enabled:!0,fn:function(data){var placement=data.placement,basePlacement=placement.split("-")[0],shiftvariation=placement.split("-")[1];if(shiftvariation){var _data$offsets=data.offsets,reference=_data$offsets.reference,popper=_data$offsets.popper,isVertical=-1!==["bottom","top"].indexOf(basePlacement),side=isVertical?"left":"top",measurement=isVertical?"width":"height",shiftOffsets={start:defineProperty({},side,reference[side]),end:defineProperty({},side,reference[side]+reference[measurement]-popper[measurement])};data.offsets.popper=_extends({},popper,shiftOffsets[shiftvariation])}return data}},offset:{order:200,enabled:!0,fn:function(data,_ref){var offset=_ref.offset,placement=data.placement,_data$offsets=data.offsets,popper=_data$offsets.popper,reference=_data$offsets.reference,basePlacement=placement.split("-")[0],offsets=void 0;return offsets=isNumeric(+offset)?[+offset,0]:parseOffset(offset,popper,reference,basePlacement),"left"===basePlacement?(popper.top+=offsets[0],popper.left-=offsets[1]):"right"===basePlacement?(popper.top+=offsets[0],popper.left+=offsets[1]):"top"===basePlacement?(popper.left+=offsets[0],popper.top-=offsets[1]):"bottom"===basePlacement&&(popper.left+=offsets[0],popper.top+=offsets[1]),data.popper=popper,data},offset:0},preventOverflow:{order:300,enabled:!0,fn:function(data,options){var boundariesElement=options.boundariesElement||getOffsetParent(data.instance.popper);data.instance.reference===boundariesElement&&(boundariesElement=getOffsetParent(boundariesElement));var boundaries=getBoundaries(data.instance.popper,data.instance.reference,options.padding,boundariesElement);options.boundaries=boundaries;var order=options.priority,popper=data.offsets.popper,check={primary:function(placement){var value=popper[placement];return popper[placement]<boundaries[placement]&&!options.escapeWithReference&&(value=Math.max(popper[placement],boundaries[placement])),defineProperty({},placement,value)},secondary:function(placement){var mainSide="right"===placement?"left":"top",value=popper[mainSide];return popper[placement]>boundaries[placement]&&!options.escapeWithReference&&(value=Math.min(popper[mainSide],boundaries[placement]-("right"===placement?popper.width:popper.height))),defineProperty({},mainSide,value)}};return order.forEach((function(placement){var side=-1!==["left","top"].indexOf(placement)?"primary":"secondary";popper=_extends({},popper,check[side](placement))})),data.offsets.popper=popper,data},priority:["left","right","top","bottom"],padding:5,boundariesElement:"scrollParent"},keepTogether:{order:400,enabled:!0,fn:function(data){var _data$offsets=data.offsets,popper=_data$offsets.popper,reference=_data$offsets.reference,placement=data.placement.split("-")[0],floor=Math.floor,isVertical=-1!==["top","bottom"].indexOf(placement),side=isVertical?"right":"bottom",opSide=isVertical?"left":"top",measurement=isVertical?"width":"height";return popper[side]<floor(reference[opSide])&&(data.offsets.popper[opSide]=floor(reference[opSide])-popper[measurement]),popper[opSide]>floor(reference[side])&&(data.offsets.popper[opSide]=floor(reference[side])),data}},arrow:{order:500,enabled:!0,fn:function(data,options){if(!isModifierRequired(data.instance.modifiers,"arrow","keepTogether"))return data;var arrowElement=options.element;if("string"==typeof arrowElement){if(!(arrowElement=data.instance.popper.querySelector(arrowElement)))return data}else if(!data.instance.popper.contains(arrowElement))return console.warn("WARNING: `arrow.element` must be child of its popper element!"),data;var placement=data.placement.split("-")[0],_data$offsets=data.offsets,popper=_data$offsets.popper,reference=_data$offsets.reference,isVertical=-1!==["left","right"].indexOf(placement),len=isVertical?"height":"width",sideCapitalized=isVertical?"Top":"Left",side=sideCapitalized.toLowerCase(),altSide=isVertical?"left":"top",opSide=isVertical?"bottom":"right",arrowElementSize=getOuterSizes(arrowElement)[len];reference[opSide]-arrowElementSize<popper[side]&&(data.offsets.popper[side]-=popper[side]-(reference[opSide]-arrowElementSize)),reference[side]+arrowElementSize>popper[opSide]&&(data.offsets.popper[side]+=reference[side]+arrowElementSize-popper[opSide]);var center=reference[side]+reference[len]/2-arrowElementSize/2,popperMarginSide=getStyleComputedProperty(data.instance.popper,"margin"+sideCapitalized).replace("px",""),sideValue=center-getClientRect(data.offsets.popper)[side]-popperMarginSide;return sideValue=Math.max(Math.min(popper[len]-arrowElementSize,sideValue),0),data.arrowElement=arrowElement,data.offsets.arrow={},data.offsets.arrow[side]=Math.round(sideValue),data.offsets.arrow[altSide]="",data},element:"[x-arrow]"},flip:{order:600,enabled:!0,fn:function(data,options){if(isModifierEnabled(data.instance.modifiers,"inner"))return data;if(data.flipped&&data.placement===data.originalPlacement)return data;var boundaries=getBoundaries(data.instance.popper,data.instance.reference,options.padding,options.boundariesElement),placement=data.placement.split("-")[0],placementOpposite=getOppositePlacement(placement),variation=data.placement.split("-")[1]||"",flipOrder=[];switch(options.behavior){case BEHAVIORS_FLIP:flipOrder=[placement,placementOpposite];break;case BEHAVIORS_CLOCKWISE:flipOrder=clockwise(placement);break;case BEHAVIORS_COUNTERCLOCKWISE:flipOrder=clockwise(placement,!0);break;default:flipOrder=options.behavior}return flipOrder.forEach((function(step,index){if(placement!==step||flipOrder.length===index+1)return data;placement=data.placement.split("-")[0],placementOpposite=getOppositePlacement(placement);var popperOffsets=data.offsets.popper,refOffsets=data.offsets.reference,floor=Math.floor,overlapsRef="left"===placement&&floor(popperOffsets.right)>floor(refOffsets.left)||"right"===placement&&floor(popperOffsets.left)<floor(refOffsets.right)||"top"===placement&&floor(popperOffsets.bottom)>floor(refOffsets.top)||"bottom"===placement&&floor(popperOffsets.top)<floor(refOffsets.bottom),overflowsLeft=floor(popperOffsets.left)<floor(boundaries.left),overflowsRight=floor(popperOffsets.right)>floor(boundaries.right),overflowsTop=floor(popperOffsets.top)<floor(boundaries.top),overflowsBottom=floor(popperOffsets.bottom)>floor(boundaries.bottom),overflowsBoundaries="left"===placement&&overflowsLeft||"right"===placement&&overflowsRight||"top"===placement&&overflowsTop||"bottom"===placement&&overflowsBottom,isVertical=-1!==["top","bottom"].indexOf(placement),flippedVariation=!!options.flipVariations&&(isVertical&&"start"===variation&&overflowsLeft||isVertical&&"end"===variation&&overflowsRight||!isVertical&&"start"===variation&&overflowsTop||!isVertical&&"end"===variation&&overflowsBottom);(overlapsRef||overflowsBoundaries||flippedVariation)&&(data.flipped=!0,(overlapsRef||overflowsBoundaries)&&(placement=flipOrder[index+1]),flippedVariation&&(variation=function(variation){return"end"===variation?"start":"start"===variation?"end":variation}(variation)),data.placement=placement+(variation?"-"+variation:""),data.offsets.popper=_extends({},data.offsets.popper,getPopperOffsets(data.instance.popper,data.offsets.reference,data.placement)),data=runModifiers(data.instance.modifiers,data,"flip"))})),data},behavior:"flip",padding:5,boundariesElement:"viewport"},inner:{order:700,enabled:!1,fn:function(data){var placement=data.placement,basePlacement=placement.split("-")[0],_data$offsets=data.offsets,popper=_data$offsets.popper,reference=_data$offsets.reference,isHoriz=-1!==["left","right"].indexOf(basePlacement),subtractLength=-1===["top","left"].indexOf(basePlacement);return popper[isHoriz?"left":"top"]=reference[basePlacement]-(subtractLength?popper[isHoriz?"width":"height"]:0),data.placement=getOppositePlacement(placement),data.offsets.popper=getClientRect(popper),data}},hide:{order:800,enabled:!0,fn:function(data){if(!isModifierRequired(data.instance.modifiers,"hide","preventOverflow"))return data;var refRect=data.offsets.reference,bound=find(data.instance.modifiers,(function(modifier){return"preventOverflow"===modifier.name})).boundaries;if(refRect.bottom<bound.top||refRect.left>bound.right||refRect.top>bound.bottom||refRect.right<bound.left){if(!0===data.hide)return data;data.hide=!0,data.attributes["x-out-of-boundaries"]=""}else{if(!1===data.hide)return data;data.hide=!1,data.attributes["x-out-of-boundaries"]=!1}return data}},computeStyle:{order:850,enabled:!0,fn:function(data,options){var x=options.x,y=options.y,popper=data.offsets.popper,legacyGpuAccelerationOption=find(data.instance.modifiers,(function(modifier){return"applyStyle"===modifier.name})).gpuAcceleration;void 0!==legacyGpuAccelerationOption&&console.warn("WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!");var gpuAcceleration=void 0!==legacyGpuAccelerationOption?legacyGpuAccelerationOption:options.gpuAcceleration,offsetParentRect=getBoundingClientRect(getOffsetParent(data.instance.popper)),styles={position:popper.position},offsets={left:Math.floor(popper.left),top:Math.floor(popper.top),bottom:Math.floor(popper.bottom),right:Math.floor(popper.right)},sideA="bottom"===x?"top":"bottom",sideB="right"===y?"left":"right",prefixedProperty=getSupportedPropertyName("transform"),left=void 0,top=void 0;if(top="bottom"===sideA?-offsetParentRect.height+offsets.bottom:offsets.top,left="right"===sideB?-offsetParentRect.width+offsets.right:offsets.left,gpuAcceleration&&prefixedProperty)styles[prefixedProperty]="translate3d("+left+"px, "+top+"px, 0)",styles[sideA]=0,styles[sideB]=0,styles.willChange="transform";else{var invertTop="bottom"===sideA?-1:1,invertLeft="right"===sideB?-1:1;styles[sideA]=top*invertTop,styles[sideB]=left*invertLeft,styles.willChange=sideA+", "+sideB}var attributes={"x-placement":data.placement};return data.attributes=_extends({},attributes,data.attributes),data.styles=_extends({},styles,data.styles),data.arrowStyles=_extends({},data.offsets.arrow,data.arrowStyles),data},gpuAcceleration:!0,x:"bottom",y:"right"},applyStyle:{order:900,enabled:!0,fn:function(data){var element,attributes;return setStyles(data.instance.popper,data.styles),element=data.instance.popper,attributes=data.attributes,Object.keys(attributes).forEach((function(prop){!1!==attributes[prop]?element.setAttribute(prop,attributes[prop]):element.removeAttribute(prop)})),data.arrowElement&&Object.keys(data.arrowStyles).length&&setStyles(data.arrowElement,data.arrowStyles),data},onLoad:function(reference,popper,options,modifierOptions,state){var referenceOffsets=getReferenceOffsets(0,popper,reference),placement=computeAutoPlacement(options.placement,referenceOffsets,popper,reference,options.modifiers.flip.boundariesElement,options.modifiers.flip.padding);return popper.setAttribute("x-placement",placement),setStyles(popper,{position:"absolute"}),options},gpuAcceleration:void 0}},Defaults={placement:"bottom",eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:modifiers},Popper=function(){function Popper(reference,popper){var _this=this,options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};classCallCheck(this,Popper),this.scheduleUpdate=function(){return requestAnimationFrame(_this.update)},this.update=debounce(this.update.bind(this)),this.options=_extends({},Popper.Defaults,options),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=reference&&reference.jquery?reference[0]:reference,this.popper=popper&&popper.jquery?popper[0]:popper,this.options.modifiers={},Object.keys(_extends({},Popper.Defaults.modifiers,options.modifiers)).forEach((function(name){_this.options.modifiers[name]=_extends({},Popper.Defaults.modifiers[name]||{},options.modifiers?options.modifiers[name]:{})})),this.modifiers=Object.keys(this.options.modifiers).map((function(name){return _extends({name:name},_this.options.modifiers[name])})).sort((function(a,b){return a.order-b.order})),this.modifiers.forEach((function(modifierOptions){modifierOptions.enabled&&isFunction(modifierOptions.onLoad)&&modifierOptions.onLoad(_this.reference,_this.popper,_this.options,modifierOptions,_this.state)})),this.update();var eventsEnabled=this.options.eventsEnabled;eventsEnabled&&this.enableEventListeners(),this.state.eventsEnabled=eventsEnabled}return createClass(Popper,[{key:"update",value:function(){return update.call(this)}},{key:"destroy",value:function(){return destroy.call(this)}},{key:"enableEventListeners",value:function(){return enableEventListeners.call(this)}},{key:"disableEventListeners",value:function(){return disableEventListeners.call(this)}}]),Popper}();return Popper.Utils=("undefined"!=typeof window?window:global).PopperUtils,Popper.placements=placements,Popper.Defaults=Defaults,Popper})); define("core/prefetch",["exports","core/config"],(function(_exports,_config){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_config=(obj=_config)&&obj.__esModule?obj:{default:obj};var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};let prefetchTimer,initialPrefetchComplete=!1,templateList=[],stringList={};const fetchQueue=()=>{if(templateList){const templatesToLoad=templateList.slice();templateList=[],("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"])).then((Templates=>Templates.prefetchTemplates(templatesToLoad))).catch()}const mappedStringsToFetch=stringList;stringList={};const stringsToFetch=[];Object.keys(mappedStringsToFetch).forEach((component=>{stringsToFetch.push(...mappedStringsToFetch[component].map((key=>({component:component,key:key}))))})),stringsToFetch&&("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/str"],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/str")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/str"])).then((Str=>Str.get_strings(stringsToFetch))).catch()},processQueue=()=>{prefetchTimer||(initialPrefetchComplete?fetchQueue():prefetchTimer=setTimeout((()=>{initialPrefetchComplete=!0,prefetchTimer=null,("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require([_config.default.iconsystemmodule],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require(_config.default.iconsystemmodule)):Promise.resolve(_systemImportTransformerGlobalIdentifier[_config.default.iconsystemmodule])).then((IconSystem=>{const iconSystem=new IconSystem;return prefetchTemplate(iconSystem.getTemplateName()),iconSystem})).then((iconSystem=>{fetchQueue(),iconSystem.init()})).catch()}),500))},prefetchTemplates=templatesNames=>{templateList=templateList.concat(templatesNames),processQueue()},prefetchTemplate=templateName=>{prefetchTemplates([templateName])},prefetchStrings=(component,keys)=>{stringList[component]||(stringList[component]=[]),stringList[component]=stringList[component].concat(keys),processQueue()};prefetchTemplates([].concat(["core/loading"],["core/modal"],["core/modal_backdrop"])),prefetchStrings("core",["cancel","closebuttontitle","loading","savechanges"]),prefetchStrings("core_form",["showless","showmore"]);var _default={prefetchTemplate:prefetchTemplate,prefetchTemplates:prefetchTemplates,prefetchString:(component,key)=>{stringList[component]||(stringList[component]=[]),stringList[component].push(key),processQueue()},prefetchStrings:prefetchStrings};return _exports.default=_default,_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 <ryan@moodle.com> * @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<events[eventName].length;i++)if(events[eventName][i]===callback){events[eventName].splice(i,1);break}};_exports.publish=function(eventName,data){const pendingPromise=new _pending.default("Publishing "+eventName);events[eventName]&&events[eventName].forEach((function(callback){callback(data)})),pendingPromise.resolve()}})); 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 <ferran@moodle.com> * @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}})); /** * Simple API for set/get to sessionstorage, with cacherev expiration. * * Session storage will only persist for as long as the browser window * stays open. * * See: * https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage * * @module core/sessionstorage * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/sessionstorage",["core/config","core/storagewrapper"],(function(config,StorageWrapper){var storage=new StorageWrapper(window.sessionStorage);return{get:function(key){return storage.get(key)},set:function(key,value){return storage.set(key,value)}}})); /** * Show/hide admin settings based on other settings selected * * @copyright 2018 Davo Smith, Synergy Learning * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/showhidesettings",["jquery"],(function($){var dependencies;function isCheckboxHiddenElement($el){return $el.is("input[type=hidden]")&&$el.siblings('input[type=checkbox][name="'+$el.attr("name")+'"]').length}function isCheckedRelevant($el,value){return!isCheckboxHiddenElement($el)&&!function($el,value){return $el.is("input[type=radio]")&&$el.attr("value")!==value}($el,value)}function isUncheckedRadioButton($el){return $el.is("input[type=radio]")&&!$el.prop("checked")}function isUncheckedCheckbox($el){return $el.is("input[type=checkbox]")&&!$el.prop("checked")}function isMultiSelect($el){return $el.is("select")&&$el.prop("multiple")}function multiSelectMatches($el,values){var selected=$el.val()||[];if(!values.length)return!1;if(selected.length!==values.length)return!1;for(var i in selected)if(selected.hasOwnProperty(i)&&-1===values.indexOf(selected[i]))return!1;return!0}var depFns={notchecked:function($dependon,value){var hide=!1;return value=String(value),$dependon.each((function(idx,el){var $el=$(el);isCheckedRelevant($el,value)&&(hide=hide||!$el.prop("checked"))})),hide},checked:function($dependon,value){var hide=!1;return value=String(value),$dependon.each((function(idx,el){var $el=$(el);isCheckedRelevant($el,value)&&(hide=hide||$el.prop("checked"))})),hide},noitemselected:function($dependon){var hide=!1;return $dependon.each((function(idx,el){var $el=$(el);hide=hide||-1===$el.prop("selectedIndex")})),hide},eq:function($dependon,value){var hide=!1,hiddenVal=!1;return value=String(value),$dependon.each((function(idx,el){var $el=$(el);if(!isUncheckedRadioButton($el))if(isCheckboxHiddenElement($el))hiddenVal=$el.val()===value;else if(isUncheckedCheckbox($el))hide=hide||hiddenVal;else if(isMultiSelect($el)){var values=value.split("|");hide=multiSelectMatches($el,values)}else hide=hide||$el.val()===value})),hide},in:function($dependon,value){var hide=!1,hiddenVal=!1,values=value.split("|");return $dependon.each((function(idx,el){var $el=$(el);isUncheckedRadioButton($el)||(isCheckboxHiddenElement($el)?hiddenVal=values.indexOf($el.val())>-1:hide=isUncheckedCheckbox($el)?hide||hiddenVal:isMultiSelect($el)?multiSelectMatches($el,values):hide||values.indexOf($el.val())>-1)})),hide},defaultCondition:function($dependon,value){var hide=!1,hiddenVal=!1;return value=String(value),$dependon.each((function(idx,el){var $el=$(el);if(!isUncheckedRadioButton($el))if(isCheckboxHiddenElement($el))hiddenVal=$el.val()!==value;else if(isUncheckedCheckbox($el))hide=hide||hiddenVal;else if(isMultiSelect($el)){var values=value.split("|");hide=!multiSelectMatches($el,values)}else hide=hide||$el.val()!==value})),hide}};function getElementsByName(name){return $('[name="'+name+'"],[name^="'+name+'["]')}function updateDependencies(){var toHide={};$.each(dependencies,(function(dependonname){var dependon=getElementsByName(dependonname);$.each(dependencies[dependonname],(function(condition,values){$.each(values,(function(value,elements){var hide=function($dependon,condition,value){return"function"==typeof depFns[condition]?depFns[condition]($dependon,value):depFns.defaultCondition($dependon,value)}(dependon,condition,value);$.each(elements,(function(idx,elToHide){toHide.hasOwnProperty(elToHide)?toHide[elToHide]=toHide[elToHide]||hide:toHide[elToHide]=hide}))}))}))})),$.each(toHide,(function(elToHide,hide){getElementsByName(elToHide).each((function(idx,el){var $parent=$(el).closest(".form-item");$parent.length&&(hide?$parent.hide():$parent.show())}))}))}return{init:function(opts){dependencies=opts.dependencies,$.each(dependencies,(function(depname){var $el=getElementsByName(depname);$el.length&&$el.on("change",updateDependencies)})),updateDependencies(),$(".form-dependenton").hide()}}})); /** * A javascript module to handle list items drag and drop * * Example of usage: * * Create a list (for example `<ul>` or `<tbody>`) where each draggable element has a drag handle. * The best practice is to use the template core/drag_handle: * $OUTPUT->render_from_template('core/drag_handle', ['movetitle' => get_string('movecontent', 'moodle', ELEMENTNAME)]); * * Attach this JS module to this list: * * Space between define and ( critical in comment but not allowed in code in order to function * correctly with Moodle's requirejs.php * * More details: https://docs.moodle.org/dev/Sortable_list * * For the full list of possible parameters see var defaultParameters below. * * The following jQuery events are fired: * - SortableList.EVENTS.DRAGSTART : when user started dragging a list element * - SortableList.EVENTS.DRAG : when user dragged a list element to a new position * - SortableList.EVENTS.DROP : when user dropped a list element * - SortableList.EVENTS.DROPEND : when user finished dragging - either fired right after dropping or * if "Esc" was pressed during dragging * * @example * define (['jquery', 'core/sortable_list'], function($, SortableList) { * var list = new SortableList('ul.my-awesome-list'); // source list (usually <ul> or <tbody>) - selector or element * * // Listen to the events when element is dragged. * $('ul.my-awesome-list > *').on(SortableList.EVENTS.DROP, function(evt, info) { * console.log(info); * }); * * // Advanced usage. Overwrite methods getElementName, getDestinationName, moveDialogueTitle, for example: * list.getElementName = function(element) { * return $.Deferred().resolve(element.attr('data-name')); * } * }); * * @module core/sortable_list * @class core/sortable_list * @copyright 2018 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/sortable_list",["jquery","core/log","core/autoscroll","core/str","core/modal_factory","core/modal_events","core/notification"],(function($,log,autoScroll,str,ModalFactory,ModalEvents,Notification){var defaultParameters={targetListSelector:null,moveHandlerSelector:"[data-drag-type=move]",isHorizontal:!1,autoScroll:!0},CSS_keyboardDragClass="dragdrop-keyboard-drag",CSS_isDraggedClass="sortable-list-is-dragged",CSS_currentPositionClass="sortable-list-current-position",CSS_targetListClass="sortable-list-target",CSS_overElementClass="sortable-list-over-element",registerNotPassiveListeners=function(eventname){return{setup:function(x,ns,handle){return!!ns.includes("notPassive")&&(this.addEventListener(eventname,handle,{passive:!1}),!0)}}};(function(){var options,passivesupported=!1;try{options=Object.defineProperty({},"passive",{get:function(){passivesupported=!0}}),document.addEventListener("testpassiveeventoptions",options,options),document.removeEventListener("testpassiveeventoptions",options,options)}catch(err){passivesupported=!1}return passivesupported})&&($.event.special.touchstart=registerNotPassiveListeners("touchstart"),$.event.special.touchmove=registerNotPassiveListeners("touchmove"),$.event.special.touchend=registerNotPassiveListeners("touchend"));var SortableList=function(root,config){this.info=null,this.proxy=null,this.proxyDelta=null,this.dragCounter=0,this.lastEvent=null,this.config=$.extend({},defaultParameters,config||{}),this.config.listSelector=root,this.config.targetListSelector||(this.config.targetListSelector=root),"object"==typeof this.config.listSelector?$(this.config.listSelector).on("mousedown touchstart.notPassive",$.proxy(this.dragStartHandler,this)):$("body").on("mousedown touchstart.notPassive",this.config.listSelector,$.proxy(this.dragStartHandler,this)),null!==this.config.moveHandlerSelector&&$("body").on("click keypress",this.config.moveHandlerSelector,$.proxy(this.clickHandler,this))};return SortableList.EVENTS={DRAGSTART:"sortablelist-dragstart",DRAG:"sortablelist-drag",DROP:"sortablelist-drop",DRAGEND:"sortablelist-dragend"},SortableList.prototype.resetDraggedClasses=function(){var classes=[CSS_isDraggedClass,CSS_currentPositionClass,CSS_overElementClass,CSS_targetListClass];for(var i in classes)$("."+classes[i]).removeClass(classes[i]);this.proxy&&(this.proxy.remove(),this.proxy=$())},SortableList.prototype.calculatePositionOnPage=function(evt){if(evt.originalEvent&&evt.originalEvent.touches&&void 0!==evt.originalEvent.touches[0]){var touch=evt.originalEvent.touches[0];evt.pageX=touch.pageX,evt.pageY=touch.pageY}void 0===evt.pageX?(evt.pageX=this.lastEvent.pageX,evt.pageY=this.lastEvent.pageY):this.lastEvent=evt,void 0===evt.clientX&&(evt.clientX=Math.round(evt.pageX-$(window).scrollLeft()),evt.clientY=Math.round(evt.pageY-$(window).scrollTop()))},SortableList.prototype.dragStartHandler=function(evt){if(null!==this.info){if("click"===this.info.type||"touchend"===this.info.type)return;this.moveElement(this.info.sourceList,this.info.sourceNextElement),this.finishDragging()}if("mousedown"!==evt.type||1===evt.which){this.calculatePositionOnPage(evt);var movedElement=$(evt.target).closest($(evt.currentTarget).children());if(movedElement.length&&(null===this.config.moveHandlerSelector||$(evt.target).closest(this.config.moveHandlerSelector,movedElement).length)){evt.stopPropagation(),evt.preventDefault(),this.dragCounter++,this.info={element:movedElement,sourceNextElement:movedElement.next(),sourceList:movedElement.parent(),targetNextElement:movedElement.next(),targetList:movedElement.parent(),type:evt.type,dropped:!1,startX:evt.pageX,startY:evt.pageY,startTime:(new Date).getTime()},$(this.config.targetListSelector).addClass(CSS_targetListClass);var offset=movedElement.offset();movedElement.addClass(CSS_currentPositionClass),this.proxyDelta={x:offset.left-evt.pageX,y:offset.top-evt.pageY},this.proxy=$();var thisDragCounter=this.dragCounter;setTimeout($.proxy((function(){null!==this.info&&"click"!==this.info.type&&"keypress"!==this.info.type&&this.dragCounter===thisDragCounter&&this.createProxy()}),this),500),$(window).on("mousemove touchmove.notPassive mouseup touchend.notPassive",$.proxy(this.dragHandler,this)),$(window).on("keypress",$.proxy(this.dragcancelHandler,this)),this.config.autoScroll&&autoScroll.start((function(){$(window).trigger("mousemove")})),this.executeCallback(SortableList.EVENTS.DRAGSTART)}}},SortableList.prototype.createProxy=function(){this.proxy=this.info.element.clone(),this.info.sourceList.append(this.proxy),this.proxy.removeAttr("id").removeClass(CSS_currentPositionClass).addClass(CSS_isDraggedClass).css({position:"fixed"}),this.proxy.offset({top:this.proxyDelta.y+this.lastEvent.pageY,left:this.proxyDelta.x+this.lastEvent.pageX})},SortableList.prototype.clickHandler=function(evt){if(("keypress"!==evt.type||13===evt.originalEvent.keyCode||32===evt.originalEvent.keyCode)&&null===this.info){var clickedElement=$(evt.target).closest(this.config.moveHandlerSelector),sourceList=clickedElement.closest(this.config.listSelector),movedElement=clickedElement.closest(sourceList.children());movedElement.length&&(evt.preventDefault(),evt.stopPropagation(),this.dragCounter++,this.info={element:movedElement,sourceNextElement:movedElement.next(),sourceList:sourceList,targetNextElement:movedElement.next(),targetList:sourceList,dropped:!1,type:evt.type,startTime:(new Date).getTime()},this.executeCallback(SortableList.EVENTS.DRAGSTART),this.displayMoveDialogue(clickedElement))}},SortableList.prototype.getPositionInNode=function(pageX,pageY,element){if(!element.length)return null;var rect=element[0].getBoundingClientRect(),y=pageY-(rect.top+window.scrollY),x=pageX-(rect.left+window.scrollX);return x>=-0&&x<=rect.width+0&&y>=-0&&y<=rect.height+0?{x:x,y:y,xRatio:rect.width?x/rect.width:0,yRatio:rect.height?y/rect.height:0}:null},SortableList.prototype.isListHorizontal=function(element){var isHorizontal=this.config.isHorizontal;return!0===isHorizontal||!1===isHorizontal?isHorizontal:isHorizontal(element)},SortableList.prototype.dragHandler=function(evt){evt.preventDefault(),evt.stopPropagation(),this.calculatePositionOnPage(evt),this.proxy.offset({top:-1e3,left:-1e3});var element=$(document.elementFromPoint(evt.clientX,evt.clientY)),mainElement=this.info.element[0],isNotSelf=function(){return this!==mainElement},current=element.closest("."+CSS_targetListClass+" > :not(."+CSS_isDraggedClass+")").filter(isNotSelf),currentList=element.closest("."+CSS_targetListClass),proxy=this.proxy,isNotProxy=function(){return!proxy||!proxy.length||this!==proxy[0]};if($("."+CSS_overElementClass).removeClass(CSS_overElementClass),current.addClass(CSS_overElementClass),this.proxy.offset({top:this.proxyDelta.y+evt.pageY,left:this.proxyDelta.x+evt.pageX}),currentList.length&&!currentList.children().filter(isNotProxy).length)this.moveElement(currentList,$());else if(1===current.length&&!this.info.element.find(current[0]).length){var coordinates=this.getPositionInNode(evt.pageX,evt.pageY,current);if(coordinates){var parent=current.parent(),ratio=this.isListHorizontal(parent)?coordinates.xRatio:coordinates.yRatio,subList=current.find("."+CSS_targetListClass),subListEmpty=!subList.children().filter(isNotProxy).filter(isNotSelf).length;subList.length&&subListEmpty&&ratio>.2&&ratio<.8?this.moveElement(subList,$()):ratio>.5?this.moveElement(parent,current.next().filter(isNotProxy)):this.moveElement(parent,current)}}if("mouseup"===evt.type||"touchend"===evt.type){this.info.endX=evt.pageX,this.info.endY=evt.pageY,this.info.endTime=(new Date).getTime(),this.info.dropped=!0,this.info.positionChanged=this.hasPositionChanged(this.info);var oldinfo=this.info;this.executeCallback(SortableList.EVENTS.DROP),this.finishDragging(),"touchend"===evt.type&&null!==this.config.moveHandlerSelector&&oldinfo.endTime-oldinfo.startTime<500&&!oldinfo.positionChanged&&this.clickHandler(evt)}},SortableList.prototype.hasPositionChanged=function(info){return info.sourceList[0]!==info.targetList[0]||info.sourceNextElement.length!==info.targetNextElement.length||info.sourceNextElement.length&&info.sourceNextElement[0]!==info.targetNextElement[0]},SortableList.prototype.moveElement=function(parentElement,beforeElement){var dragEl=this.info.element;beforeElement.length&&beforeElement[0]===dragEl[0]||parentElement[0]===this.info.targetList[0]&&beforeElement.length===this.info.targetNextElement.length&&beforeElement[0]===this.info.targetNextElement[0]||(beforeElement.length?parentElement[0].insertBefore(dragEl[0],beforeElement[0]):this.proxy&&this.proxy.parent().length&&this.proxy.parent()[0]===parentElement[0]?parentElement[0].insertBefore(dragEl[0],this.proxy[0]):parentElement[0].appendChild(dragEl[0]),this.info.targetList=parentElement,this.info.targetNextElement=beforeElement,this.executeCallback(SortableList.EVENTS.DRAG))},SortableList.prototype.finishDragging=function(){this.resetDraggedClasses(),this.config.autoScroll&&autoScroll.stop(),$(window).off("mousemove touchmove.notPassive mouseup touchend.notPassive",$.proxy(this.dragHandler,this)),$(window).off("keypress",$.proxy(this.dragcancelHandler,this)),this.executeCallback(SortableList.EVENTS.DRAGEND),this.info=null},SortableList.prototype.executeCallback=function(eventName){this.info.element.trigger(eventName,this.info)},SortableList.prototype.dragcancelHandler=function(evt){"keypress"===evt.type&&27===evt.originalEvent.keyCode&&(this.moveElement(this.info.sourceList,this.info.sourceNextElement),this.finishDragging())},SortableList.prototype.getElementName=function(element){return $.Deferred().resolve(element.text())},SortableList.prototype.getDestinationName=function(parentElement,afterElement){return afterElement.length?this.getElementName(afterElement).then((function(name){return str.get_string("movecontentafter","moodle",name)})):str.get_string("movecontenttothetop","moodle")},SortableList.prototype.getMoveDialogueTitle=function(element,handler){return handler.attr("title")?$.Deferred().resolve(handler.attr("title")):this.getElementName(element).then((function(name){return str.get_string("movecontent","moodle",name)}))},SortableList.prototype.getDestinationsList=function(){var addedLists=[],targets=$(this.config.targetListSelector),destinations=$("<ul/>").addClass(CSS_keyboardDragClass),result=$.when().then((function(){return destinations})),createLink=$.proxy((function(parentElement,beforeElement,afterElement){beforeElement.is(this.info.element)||afterElement.is(this.info.element)||$.contains(this.info.element[0],parentElement[0])||(result=result.then($.proxy((function(){return this.getDestinationName(parentElement,afterElement)}),this)).then((function(txt){var li=$("<li/>").appendTo(destinations);return $('<a href="#"/>').attr("data-core_sortable_list-quickmove",1).appendTo(li).data("parent-element",parentElement).data("before-element",beforeElement).text(txt),destinations})))}),this),addList=function(){if(-1===$.inArray(this,addedLists)){addedLists.push(this);var list=$(this),children=list.children();children.each((function(){var element=$(this);createLink(list,element,element.prev()),element.find(targets).each(addList)})),createLink(list,$(),children.last())}};return targets.each(addList),result},SortableList.prototype.displayMoveDialogue=function(clickedElement){ModalFactory.create({type:ModalFactory.types.CANCEL,title:this.getMoveDialogueTitle(this.info.element,clickedElement),body:this.getDestinationsList()}).then($.proxy((function(modal){var quickMoveHandler=$.proxy((function(e){e.preventDefault(),e.stopPropagation(),this.moveElement($(e.currentTarget).data("parent-element"),$(e.currentTarget).data("before-element")),this.info.endTime=(new Date).getTime(),this.info.positionChanged=this.hasPositionChanged(this.info),this.info.dropped=!0,clickedElement.focus(),this.executeCallback(SortableList.EVENTS.DROP),modal.hide()}),this);return modal.getRoot().on("click","[data-core_sortable_list-quickmove]",quickMoveHandler),modal.getRoot().on(ModalEvents.hidden,$.proxy((function(){modal.getRoot().off("click","[data-core_sortable_list-quickmove]",quickMoveHandler),modal.destroy(),this.finishDragging()}),this)),modal.setLarge(),modal.show(),modal}),this)).catch(Notification.exception)},SortableList})); /** * 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 <ryan@moodle.com> * @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<len;i++)hash=(hash<<5)-hash+source.charCodeAt(i),hash|=0;return hash},Wrapper.prototype.get=function(key){return!!this.supported&&(key=this.prefixKey(key),this.storage.getItem(key))},Wrapper.prototype.set=function(key,value){if(!this.supported)return!1;key=this.prefixKey(key);try{this.storage.setItem(key,value)}catch(e){return!1}return!0},Wrapper})); /** * AJAX helper for the tag management page. * * @module core/tag * @copyright 2015 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.0 */ define("core/tag",["jquery","core/ajax","core/templates","core/notification","core/str","core/modal_factory","core/modal_events","core/pending"],(function($,ajax,templates,notification,str,ModalFactory,ModalEvents,Pending){return{initTagindexPage:function(){$("body").delegate(".tagarea[data-ta] a[data-quickload=1]","click",(function(e){var pendingPromise=new Pending("core/tag:initTagindexPage");e.preventDefault();var target=$(this),query=target[0].search.replace(/^\?/,""),tagarea=target.closest(".tagarea[data-ta]"),args=query.split("&").reduce((function(s,c){var t=c.split("=");return s[t[0]]=decodeURIComponent(t[1]),s}),{});ajax.call([{methodname:"core_tag_get_tagindex",args:{tagindex:args}}])[0].then((function(data){return templates.render("core_tag/index",data)})).then((function(html,js){templates.replaceNode(tagarea,html,js)})).always(pendingPromise.resolve).catch(notification.exception)}))},initManagePage:function(){$("body").on("updated","[data-inplaceeditable]",(function(e){var pendingPromise=new Pending("core/tag:initManagePage");if(str.get_strings([{key:"selecttag",component:"core_tag"},{key:"now",component:"core"}]).then((function(result){$('label[for="tagselect'+e.ajaxreturn.itemid+'"]').html(result[0]),$(e.target).closest("tr").find("td.col-timemodified").html(result[1])})).always(pendingPromise.resolve).catch(notification.exception),"tagflag"===e.ajaxreturn.itemtype){var row=$(e.target).closest("tr");"0"===e.ajaxreturn.value?row.removeClass("table-warning"):row.addClass("table-warning")}})),$(".tag-management-table").delegate("a.tagdelete","click",(function(e){var pendingPromise=new Pending("core/tag:tagdelete");e.preventDefault();var href=$(this).attr("href");str.get_strings([{key:"delete",component:"core"},{key:"confirmdeletetag",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(){window.location.href=href}))})).always(pendingPromise.resolve).catch(notification.exception)})),$("#tag-management-delete").click((function(e){var form=$(this).closest("form").get(0);if($(form).find("input[data-togglegroup='tags-manage'][data-toggle='slave']:checked").length){var pendingPromise=new Pending("core/tag:tag-management-delete"),tempElement=$("<input type='hidden'/>").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=$("<input type='hidden'/>").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();$("<input type='hidden'/>").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/toast",["exports","core/templates","core/notification","core/pending"],(function(_exports,_templates,_notification,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A system for displaying small snackbar notifications to users which disappear shortly after they are shown. * * @module core/toast * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.addToastRegion=_exports.add=void 0,_templates=_interopRequireDefault(_templates),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);const addToastRegion=async parent=>{const pendingPromise=new _pending.default("addToastRegion");try{const{html:html,js:js}=await _templates.default.renderForPromise("core/local/toast/wrapper",{});_templates.default.prependNodeContents(parent,html,js)}catch(e){_notification.default.exception(e)}pendingPromise.resolve()};_exports.addToastRegion=addToastRegion;_exports.add=async(message,configuration)=>{const pendingPromise=new _pending.default("addToastRegion");configuration={type:"info",closeButton:!1,autohide:!0,delay:4e3,...configuration};try{const targetNode=await getTargetNode(),{html:html,js:js}=await _templates.default.renderForPromise("core/local/toast/message",{message:await message,...configuration});_templates.default.prependNodeContents(targetNode,html,js)}catch(e){_notification.default.exception(e)}pendingPromise.resolve()};const getTargetNode=async()=>{const regions=document.querySelectorAll(".toast-wrapper");return regions.length?regions[regions.length-1]:(await addToastRegion(document.body),getTargetNode())}})); define("core/tooltip",["jquery","core/aria"],(function($,Aria){var Tooltip=function(selector){this._regionSelector=selector,$(this._regionSelector).each(function(index,element){var tooltipId=$(element).attr("aria-describedby");if(tooltipId){var tooltipele=document.getElementById(tooltipId);if(tooltipele)"tooltip"==$(tooltipele).attr("role")&&($(tooltipele).hide(),$(element).attr("tabindex","0")),$(element).on("focus",this._handleFocus.bind(this)),$(element).on("mouseover",this._handleMouseOver.bind(this)),$(element).on("mouseout",this._handleMouseOut.bind(this)),$(element).on("blur",this._handleBlur.bind(this)),$(element).on("keydown",this._handleKeyDown.bind(this))}}.bind(this))};return Tooltip.prototype._regionSelector=null,Tooltip.prototype._showTooltip=function(e){var triggerElement=$(e.target),tooltipId=triggerElement.attr("aria-describedby");if(tooltipId){var tooltipele=$(document.getElementById(tooltipId));if(tooltipele.show(),Aria.unhide(tooltipele),!tooltipele.is(".tooltip")){var inner=$('<div class="tooltip-inner"></div>');inner.append(tooltipele.contents()),tooltipele.append(inner),tooltipele.addClass("tooltip"),tooltipele.addClass("bottom"),tooltipele.append('<div class="tooltip-arrow"></div>')}var pos=triggerElement.offset();pos.top+=triggerElement.height()+10,$(tooltipele).offset(pos)}},Tooltip.prototype._hideTooltip=function(e){var tooltipId=$(e.target).attr("aria-describedby");if(tooltipId){var tooltipele=document.getElementById(tooltipId);$(tooltipele).hide(),Aria.hide(tooltipele)}},Tooltip.prototype._handleFocus=function(e){this._showTooltip(e)},Tooltip.prototype._handleKeyDown=function(e){27==e.which&&this._hideTooltip(e)},Tooltip.prototype._handleMouseOver=function(e){this._showTooltip(e)},Tooltip.prototype._handleMouseOut=function(e){$(e.target).is(":focus")||this._hideTooltip(e)},Tooltip.prototype._handleBlur=function(e){this._hideTooltip(e)},Tooltip})); /** * Implement an accessible aria tree widget, from a nested unordered list. * Based on http://oaa-accessibility.org/example/41/. * * @module core/tree * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/tree",["jquery"],(function($){var SELECTORS_ITEM="[role=treeitem]",SELECTORS_GROUP="[role=treeitem]:has([role=group]), [role=treeitem][aria-owns], [role=treeitem][data-requires-ajax=true]",SELECTORS_CLOSED_GROUP="[role=treeitem]:has([role=group])[aria-expanded=false], [role=treeitem][aria-owns][aria-expanded=false], [role=treeitem][data-requires-ajax=true][aria-expanded=false]",SELECTORS_FIRST_ITEM="[role=treeitem]:first",SELECTORS_VISIBLE_ITEM="[role=treeitem]:visible",SELECTORS_UNLOADED_AJAX_ITEM="[role=treeitem][data-requires-ajax=true][data-loaded=false][aria-expanded=true]",Tree=function(selector,selectCallback){this.treeRoot=$(selector),this.treeRoot.data("activeItem",null),this.selectCallback=selectCallback,this.keys={tab:9,enter:13,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,up:38,right:39,down:40,asterisk:106},this.initialiseNodes(this.treeRoot),this.setActiveItem(this.treeRoot.find(SELECTORS_FIRST_ITEM)),this.refreshVisibleItemsCache(),this.bindEventHandlers()};return Tree.prototype.registerEnterCallback=function(callback){this.enterCallback=callback},Tree.prototype.refreshVisibleItemsCache=function(){this.treeRoot.data("visibleItems",this.treeRoot.find(SELECTORS_VISIBLE_ITEM))},Tree.prototype.getVisibleItems=function(){return this.treeRoot.data("visibleItems")},Tree.prototype.setActiveItem=function(item){var currentActive=this.treeRoot.data("activeItem");item!==currentActive&&(currentActive&&(currentActive.attr("tabindex","-1"),currentActive.attr("aria-selected","false")),item.attr("tabindex","0"),item.attr("aria-selected","true"),this.treeRoot.data("activeItem",item),"function"==typeof this.selectCallback&&this.selectCallback(item))},Tree.prototype.isGroupItem=function(item){return item.is(SELECTORS_GROUP)},Tree.prototype.getGroupFromItem=function(item){var ariaowns=this.treeRoot.find("#"+item.attr("aria-owns")),plain=item.children("[role=group]");return ariaowns.length>plain.length?ariaowns:plain},Tree.prototype.isGroupCollapsed=function(item){return"false"===item.attr("aria-expanded")},Tree.prototype.isGroupCollapsible=function(item){return"false"!==item.attr("data-collapsible")},Tree.prototype.initialiseNodes=function(node){this.removeAllFromTabOrder(node),this.setAriaSelectedFalseOnItems(node);var thisTree=this;node.find(SELECTORS_UNLOADED_AJAX_ITEM).each((function(){var unloadedNode=$(this);thisTree.collapseGroup(unloadedNode),thisTree.expandGroup(unloadedNode)}))},Tree.prototype.removeAllFromTabOrder=function(node){node.find("*").attr("tabindex","-1"),this.getGroupFromItem($(node)).find("*").attr("tabindex","-1")},Tree.prototype.setAriaSelectedFalseOnItems=function(node){node.find(SELECTORS_ITEM).attr("aria-selected","false")},Tree.prototype.expandAllGroups=function(){var thisTree=this;this.treeRoot.find(SELECTORS_CLOSED_GROUP).each((function(){var groupNode=$(this);thisTree.expandGroup($(this)).done((function(){thisTree.expandAllChildGroups(groupNode)}))}))},Tree.prototype.expandAllChildGroups=function(item){var thisTree=this;this.getGroupFromItem(item).find(SELECTORS_CLOSED_GROUP).each((function(){var groupNode=$(this);thisTree.expandGroup($(this)).done((function(){thisTree.expandAllChildGroups(groupNode)}))}))},Tree.prototype.expandGroup=function(item){var promise=$.Deferred();if("false"!==item.attr("data-expandable")&&this.isGroupCollapsed(item))if("true"===item.attr("data-requires-ajax")&&"true"!==item.attr("data-loaded")){item.attr("data-loaded",!1);var moduleName=item.closest("[data-ajax-loader]").attr("data-ajax-loader"),thisTree=this;const p=item.find("p");p.addClass("loading"),require([moduleName],(function(loader){loader.load(item).done((function(){item.attr("data-loaded",!0),thisTree.initialiseNodes(item),thisTree.finishExpandingGroup(item),p.removeClass("loading"),promise.resolve()}))}))}else this.finishExpandingGroup(item),promise.resolve();else promise.resolve();return promise},Tree.prototype.finishExpandingGroup=function(item){this.getGroupFromItem(item).removeAttr("aria-hidden"),item.attr("aria-expanded","true"),this.refreshVisibleItemsCache()},Tree.prototype.collapseGroup=function(item){this.isGroupCollapsible(item)&&!this.isGroupCollapsed(item)&&(this.getGroupFromItem(item).attr("aria-hidden","true"),item.attr("aria-expanded","false"),this.refreshVisibleItemsCache())},Tree.prototype.toggleGroup=function(item){"true"===item.attr("aria-expanded")?this.collapseGroup(item):this.expandGroup(item)},Tree.prototype.handleKeyDown=function(e){var _this$getVisibleItems,item=$(e.target),currentIndex=null===(_this$getVisibleItems=this.getVisibleItems())||void 0===_this$getVisibleItems?void 0:_this$getVisibleItems.index(item);if(!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey&&e.keyCode!=this.keys.tab))switch(e.keyCode){case this.keys.home:return this.getVisibleItems().first().focus(),void e.preventDefault();case this.keys.end:return this.getVisibleItems().last().focus(),void e.preventDefault();case this.keys.enter:var links=item.children("a").length?item.children("a"):item.children().not(SELECTORS_GROUP).find("a");return links.length?links.first().data("overrides-tree-activation-key-handler")?links.first().triggerHandler(e):"function"==typeof this.enterCallback?this.enterCallback(item):window.location.href=links.first().attr("href"):this.isGroupItem(item)&&this.toggleGroup(item,!0),void e.preventDefault();case this.keys.space:if(this.isGroupItem(item))this.toggleGroup(item,!0);else if(item.children("a").length){var firstLink=item.children("a").first();firstLink.data("overrides-tree-activation-key-handler")&&firstLink.triggerHandler(e)}return void e.preventDefault();case this.keys.left:var focusParent=function(tree){tree.getVisibleItems().filter((function(){return tree.getGroupFromItem($(this)).has(item).length})).focus()};return this.isGroupItem(item)?this.isGroupCollapsed(item)?focusParent(this):this.collapseGroup(item):focusParent(this),void e.preventDefault();case this.keys.right:return this.isGroupItem(item)&&(this.isGroupCollapsed(item)?this.expandGroup(item):this.getGroupFromItem(item).find(SELECTORS_ITEM).first().focus()),void e.preventDefault();case this.keys.up:if(currentIndex>0)this.getVisibleItems().eq(currentIndex-1).focus();return void e.preventDefault();case this.keys.down:if(currentIndex<this.getVisibleItems().length-1)this.getVisibleItems().eq(currentIndex+1).focus();return void e.preventDefault();case this.keys.asterisk:return this.expandAllGroups(),void e.preventDefault()}},Tree.prototype.handleItemClick=function(event,item){item.focus(),this.isGroupItem(item)&&this.toggleGroup(item)},Tree.prototype.handleClick=function(event){if(!(event.altKey||event.ctrlKey||event.shiftKey||event.metaKey)){var item=$(event.target).closest('[role="treeitem"]');item.is(event.currentTarget)&&this.handleItemClick(event,item)}},Tree.prototype.handleFocus=function(e){this.setActiveItem($(e.target))},Tree.prototype.bindEventHandlers=function(){this.treeRoot.on({click:this.handleClick.bind(this),keydown:this.handleKeyDown.bind(this),focus:this.handleFocus.bind(this)},SELECTORS_ITEM)},Tree})); /** * 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 <ryan@moodle.com> * @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<text.length;i+=charLengthAt(text,i))count++;return count},getSliceLength=function(text,amount){if(!text.length)return 0;var length=0,count=0;do{length+=charLengthAt(text,length),count++}while(length<text.length&&count<amount);return length};return $.truncate=function(html,options){return $("<div></div>").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(!(textLength<o.length)){if(o.stripTags&&self.text(text),o.words&&excess>0){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}})); /** * URL utility functions. * * @module core/url * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/url",["jquery","core/config"],(function($,config){return{fileUrl:function(relativeScript,slashArg){var url=config.wwwroot+relativeScript;return"/"!=slashArg.charAt(0)&&(slashArg="/"+slashArg),config.slasharguments?url+=slashArg:url+="?file="+encodeURIComponent(slashArg),url},relativeUrl:function(relativePath,params,includeSessKey){if(0===relativePath.indexOf("http:")||0===relativePath.indexOf("https:")||relativePath.indexOf("://")>=0)throw new Error("relativeUrl function does not accept absolute urls");"/"!=relativePath.charAt(0)&&(relativePath="/"+relativePath),"admin"!==config.admin&&(relativePath=relativePath.replace(/^\/admin\//,"/"+config.admin+"/")),params=params||{},includeSessKey&&(params.sesskey=config.sesskey);var queryString="";return Object.keys(params).length&&(queryString=$.map(params,(function(value,param){return param+"="+value})).join("&")),""!==queryString?config.wwwroot+relativePath+"?"+queryString:config.wwwroot+relativePath},imageUrl:function(imagename,component){return M.util.image_url(imagename,component)}}})); /** * Fetch and render dates from timestamps. * * @module core/user_date * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/user_date",["jquery","core/ajax","core/sessionstorage","core/config"],(function($,Ajax,Storage,Config){var promisesCache={},getKey=function(request){return"core_user_date/"+$("html").attr("lang").replace(/-/g,"_")+"/"+Config.usertimezone+"/"+request.timestamp+"/"+request.format},loadDatesFromServer=function(dates){var args=dates.map((function(data){var fixDay=data.hasOwnProperty("fixday")?data.fixday:1,fixHour=data.hasOwnProperty("fixhour")?data.fixhour:1;return{timestamp:data.timestamp,format:data.format,type:data.type||null,fixday:fixDay,fixhour:fixHour}})),request={methodname:"core_get_user_dates",args:{contextid:Config.contextid,timestamps:args}};return Ajax.call([request],!0,!0)[0].then((function(results){results.dates.forEach((function(value,index){var date=dates[index];!function(key,value){Storage.set(key,value)}(getKey(date),value),date.deferred.resolve(value)}))})).catch((function(ex){dates.forEach((function(date){date.deferred.reject(ex)}))}))};return{get:function(requests){var ajaxRequests=[],promises=[];return requests.forEach((function(request){var key=getKey(request);if(function(key){return void 0!==promisesCache[key]}(key))promises.push(function(key){return promisesCache[key]}(key));else{var deferred=$.Deferred(),cached=function(key){return Storage.get(key)}(key);cached?deferred.resolve(cached):(request.deferred=deferred,ajaxRequests.push(request)),function(key,promise){promisesCache[key]=promise}(key,deferred.promise()),promises.push(deferred.promise())}})),ajaxRequests.length&&loadDatesFromServer(ajaxRequests),$.when.apply($,promises).then((function(){return 1===arguments.length?[arguments[0]]:Array.apply(null,arguments)}))},getUserMidnightForTimestamp:function(timestamp,todayMidnight){var future=timestamp>todayMidnight,diffSeconds=Math.abs(timestamp-todayMidnight),diffDaysInSeconds=86400*(future?Math.floor(diffSeconds/86400):Math.ceil(diffSeconds/86400));return future?todayMidnight+diffDaysInSeconds:todayMidnight-diffDaysInSeconds}}})); 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 <mihail@moodle.com> * @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})); /** * Expose the global YUI variable. Note: This is only for scripts that are writing AMD * wrappers for YUI functionality. This is not for plugins. * * @module core/yui * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/yui",(function(){return Y})); define("core/addblockmodal",["exports","core/modal_factory","core/templates","core/str","core/ajax"],(function(_exports,_modal_factory,_templates,_str,_ajax){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Show an add block modal instead of doing it on a separate page. * * @module core/addblockmodal * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modal_factory=_interopRequireDefault(_modal_factory),_templates=_interopRequireDefault(_templates),_ajax=_interopRequireDefault(_ajax);const SELECTORS_ADD_BLOCK='[data-key="addblock"]';let listenerEventsRegistered=!1;const registerListenerEvents=(pageType,pageLayout,addBlockUrl,subPage)=>{document.addEventListener("click",(e=>{const addBlock=e.target.closest(SELECTORS_ADD_BLOCK);if(addBlock){e.preventDefault();let addBlockModal=null,addBlockModalUrl=null!=addBlockUrl?addBlockUrl:addBlock.dataset.url;buildAddBlockModal().then((modal=>{addBlockModal=modal;const modalBody=renderBlocks(addBlockModalUrl,pageType,pageLayout,subPage);return modal.setBody(modalBody),modal.show(),modalBody})).catch((()=>{addBlockModal.destroy()}))}}))},buildAddBlockModal=()=>_modal_factory.default.create({type:_modal_factory.default.types.CANCEL,title:(0,_str.get_string)("addblock")}),renderBlocks=async(addBlockUrl,pageType,pageLayout,subPage)=>{const blocks=await getAddableBlocks(pageType,pageLayout,subPage);return _templates.default.render("core/add_block_body",{blocks:blocks,url:addBlockUrl})},getAddableBlocks=async(pageType,pageLayout,subPage)=>{const request={methodname:"core_block_fetch_addable_blocks",args:{pagecontextid:M.cfg.contextid,pagetype:pageType,pagelayout:pageLayout,subpage:subPage}};return _ajax.default.call([request])[0]};_exports.init=function(pageType,pageLayout){let addBlockUrl=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,subPage=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";listenerEventsRegistered||(registerListenerEvents(pageType,pageLayout,addBlockUrl,subPage),listenerEventsRegistered=!0)}})); /** * Expose the M.cfg global variable. * * @module core/config * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @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/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 <code>data-action="copytoclipboard"</code> attribute and set the * <code>data-clipboard-target</code> 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 <code>data-clipboard-success-message</code> 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 <caption>Markup for the trigger and target elements</caption> * <input type="text" id="textinputtocopy" class="form-control" value="Copy me!" readonly /> * <button id="copybutton" data-action="copytoclipboard" data-clipboard-target="#textinputtocopy" * data-clipboard-success-message="Success!" class="btn btn-secondary"> * Copy to clipboard * </button> */ 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/datafilter",["exports","core/datafilter/filtertypes/courseid","core/datafilter/filtertype","core/str","core/notification","core/pending","core/datafilter/selectors","core/templates","core/custom_interaction_events","jquery"],(function(_exports,_courseid,_filtertype,_str,_notification,_pending,_selectors,_templates,_custom_interaction_events,_jquery){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_courseid=_interopRequireDefault(_courseid),_filtertype=_interopRequireDefault(_filtertype),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_selectors=_interopRequireDefault(_selectors),_templates=_interopRequireDefault(_templates),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_jquery=_interopRequireDefault(_jquery);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}return _exports.default=class{constructor(filterSet,applyCallback){this.filterSet=filterSet,this.applyCallback=applyCallback,this.activeFilters={courseid:new _courseid.default("courseid",filterSet)}}init(){this.filterSet.querySelector(_selectors.default.filterset.region).addEventListener("click",(e=>{e.target.closest(_selectors.default.filterset.actions.addRow)&&(e.preventDefault(),this.addFilterRow()),e.target.closest(_selectors.default.filterset.actions.applyFilters)&&(e.preventDefault(),this.updateTableFromFilter()),e.target.closest(_selectors.default.filterset.actions.resetFilters)&&(e.preventDefault(),this.removeAllFilters())})),this.filterSet.querySelector(_selectors.default.filterset.regions.filterlist).addEventListener("click",(e=>{e.target.closest(_selectors.default.filter.actions.remove)&&(e.preventDefault(),this.removeOrReplaceFilterRow(e.target.closest(_selectors.default.filter.region),!0))}));let filterRegion=(0,_jquery.default)(this.getFilterRegion());_custom_interaction_events.default.define(filterRegion,[_custom_interaction_events.default.events.accessibleChange]),filterRegion.on(_custom_interaction_events.default.events.accessibleChange,(e=>{const typeField=e.target.closest(_selectors.default.filter.fields.type);if(typeField&&typeField.value){const filter=e.target.closest(_selectors.default.filter.region);this.addFilter(filter,typeField.value)}})),this.filterSet.querySelector(_selectors.default.filterset.fields.join).addEventListener("change",(e=>{this.filterSet.dataset.filterverb=e.target.value}))}getFilterRegion(){return this.filterSet.querySelector(_selectors.default.filterset.regions.filterlist)}addFilterRow(){const pendingPromise=new _pending.default("core/datafilter:addFilterRow"),rownum=1+this.getFilterRegion().querySelectorAll(_selectors.default.filter.region).length;return _templates.default.renderForPromise("core/datafilter/filter_row",{rownumber:rownum}).then((_ref=>{let{html:html,js:js}=_ref;return _templates.default.appendNodeContents(this.getFilterRegion(),html,js)})).then((filterRow=>{const typeList=this.filterSet.querySelector(_selectors.default.data.typeList);return filterRow.forEach((contentNode=>{const contentTypeList=contentNode.querySelector(_selectors.default.filter.fields.type);contentTypeList&&(contentTypeList.innerHTML=typeList.innerHTML)})),filterRow})).then((filterRow=>(this.updateFiltersOptions(),filterRow))).then((result=>(pendingPromise.resolve(),result))).catch(_notification.default.exception)}getFilterDataSource(filterType){return this.filterSet.querySelector(_selectors.default.filterset.regions.datasource).querySelector(_selectors.default.data.fields.byName(filterType))}async addFilter(filterRow,filterType,initialFilterValues){filterRow.dataset.filterType=filterType;const filterDataNode=this.getFilterDataSource(filterType);let Filter=_filtertype.default;filterDataNode.dataset.filterTypeClass&&(Filter=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require([filterDataNode.dataset.filterTypeClass],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require(filterDataNode.dataset.filterTypeClass)):Promise.resolve(_systemImportTransformerGlobalIdentifier[filterDataNode.dataset.filterTypeClass]))),this.activeFilters[filterType]=new Filter(filterType,this.filterSet,initialFilterValues);const typeField=filterRow.querySelector(_selectors.default.filter.fields.type);return typeField.value=filterType,typeField.disabled="disabled",this.updateFiltersOptions(),this.activeFilters[filterType]}getFilterObject(name){return this.activeFilters[name]}removeOrReplaceFilterRow(filterRow,refreshContent){1===this.getFilterRegion().querySelectorAll(_selectors.default.filter.region).length?this.replaceFilterRow(filterRow,refreshContent):this.removeFilterRow(filterRow,refreshContent)}async removeFilterRow(filterRow){let refreshContent=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const hasFilterValue=!!filterRow.querySelector(_selectors.default.filter.fields.type).value;this.removeFilterObject(filterRow.dataset.filterType),filterRow.remove(),this.updateFiltersOptions(),hasFilterValue&&refreshContent&&this.updateTableFromFilter();const filterLegends=await this.getAvailableFilterLegends();this.getFilterRegion().querySelectorAll(_selectors.default.filter.region).forEach(((filterRow,index)=>{filterRow.querySelector("legend").innerText=filterLegends[index]}))}replaceFilterRow(filterRow){let refreshContent=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],rowNum=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return this.removeFilterObject(filterRow.dataset.filterType),_templates.default.renderForPromise("core/datafilter/filter_row",{rownumber:rowNum}).then((_ref2=>{let{html:html,js:js}=_ref2;return _templates.default.replaceNode(filterRow,html,js)})).then((filterRow=>{const typeList=this.filterSet.querySelector(_selectors.default.data.typeList);return filterRow.forEach((contentNode=>{const contentTypeList=contentNode.querySelector(_selectors.default.filter.fields.type);contentTypeList&&(contentTypeList.innerHTML=typeList.innerHTML)})),filterRow})).then((filterRow=>(this.updateFiltersOptions(),filterRow))).then((filterRow=>refreshContent?this.updateTableFromFilter():filterRow)).catch(_notification.default.exception)}removeFilterObject(filterName){if(filterName){const filter=this.getFilterObject(filterName);filter&&(filter.tearDown(),delete this.activeFilters[filterName])}}removeAllFilters(){return this.getFilterRegion().querySelectorAll(_selectors.default.filter.region).forEach((filterRow=>this.removeOrReplaceFilterRow(filterRow,!1))),this.updateTableFromFilter()}removeEmptyFilters(){this.getFilterRegion().querySelectorAll(_selectors.default.filter.region).forEach((filterRow=>{filterRow.querySelector(_selectors.default.filter.fields.type).value||this.removeOrReplaceFilterRow(filterRow,!1)}))}updateFiltersOptions(){const filters=this.getFilterRegion().querySelectorAll(_selectors.default.filter.region);filters.forEach((filterRow=>{filterRow.querySelectorAll(_selectors.default.filter.fields.type+" option").forEach((option=>{option.value===filterRow.dataset.filterType?(option.classList.remove("hidden"),option.disabled=!1):this.activeFilters[option.value]?(option.classList.add("hidden"),option.disabled=!0):(option.classList.remove("hidden"),option.disabled=!1)}))}));const addRowButton=this.filterSet.querySelector(_selectors.default.filterset.actions.addRow);this.filterSet.querySelectorAll(_selectors.default.data.fields.all).length<=filters.length?addRowButton.setAttribute("disabled","disabled"):addRowButton.removeAttribute("disabled"),1===filters.length?(this.filterSet.querySelector(_selectors.default.filterset.regions.filtermatch).classList.add("hidden"),this.filterSet.querySelector(_selectors.default.filterset.fields.join).value=2,this.filterSet.dataset.filterverb=2):this.filterSet.querySelector(_selectors.default.filterset.regions.filtermatch).classList.remove("hidden")}updateTableFromFilter(){const pendingPromise=new _pending.default("core/datafilter:updateTableFromFilter"),filters={};Object.values(this.activeFilters).forEach((filter=>{filters[filter.filterValue.name]=filter.filterValue})),this.applyCallback&&this.applyCallback(filters,pendingPromise)}async getAvailableFilterLegends(){const maxFilters=document.querySelector(_selectors.default.data.typeListSelect).length-1;let requests=[];[...Array(maxFilters)].forEach(((_,rowIndex)=>{requests.push({key:"filterrowlegend",component:"core",param:rowIndex+1})}));return await(0,_str.get_strings)(requests).then((fetchedStrings=>fetchedStrings)).catch(_notification.default.exception)}},_exports.default})); define("core/dynamic_tabs",["exports","jquery","core/templates","core/loadingicon","core/notification","core/pending","core/str","core/local/repository/dynamic_tabs","core_form/changechecker"],(function(_exports,_jquery,_templates,_loadingicon,_notification,_pending,_str,_dynamic_tabs,_changechecker){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Dynamic Tabs UI element with AJAX loading of tabs content * * @module core/dynamic_tabs * @copyright 2021 David Matamoros <davidmc@moodle.com> based on code from Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_templates=_interopRequireDefault(_templates),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);const SELECTORS={dynamicTabs:".dynamictabs",activeTab:".dynamictabs .nav-link.active",allActiveTabs:'.dynamictabs .nav-link[data-toggle="tab"]:not(.disabled)',tabContent:".dynamictabs .tab-pane [data-tab-content]",tabToggle:'a[data-toggle="tab"]',tabPane:".dynamictabs .tab-pane",forTabName:tabName=>'.dynamictabs [data-tab-content="'.concat(tabName,'"]'),forTabId:tabName=>'.dynamictabs [data-toggle="tab"][href="#'.concat(tabName,'"]')};_exports.init=()=>{const tabToggle=(0,_jquery.default)(SELECTORS.tabToggle);if(tabToggle.on("click",(event=>{(0,_changechecker.isAnyWatchedFormDirty)()&&(event.preventDefault(),event.stopPropagation(),(0,_str.get_strings)([{key:"changesmade",component:"moodle"},{key:"changesmadereallygoaway",component:"moodle"},{key:"confirm",component:"moodle"}]).then((_ref=>{let[strChangesMade,strChangesMadeReally,strConfirm]=_ref;return _notification.default.confirm(strChangesMade,strChangesMadeReally,strConfirm,null,(()=>{(0,_changechecker.resetAllFormDirtyStates)(),(0,_jquery.default)(event.target).trigger(event.type)}))})).catch(_notification.default.exception))})),tabToggle.on("show.bs.tab",(function(){const previousTabName=getActiveTabName();if(previousTabName){document.querySelector(SELECTORS.forTabName(previousTabName)).textContent=""}})).on("shown.bs.tab",(function(){const tab=(0,_jquery.default)((0,_jquery.default)(this).attr("href"));1===tab.length&&loadTab(tab.attr("id"))})),!openTabFromHash()){const tabs=document.querySelector(SELECTORS.allActiveTabs);if(tabs)openTab(tabs.getAttribute("aria-controls"));else{const tabPane=document.querySelector(SELECTORS.tabPane);tabPane&&(tabPane.classList.add("active","show"),loadTab(tabPane.getAttribute("id")))}}};const getActiveTabName=()=>{const element=document.querySelector(SELECTORS.activeTab);return(null==element?void 0:element.getAttribute("aria-controls"))||null},loadTab=tabName=>{var _ref2,_tabName;tabName=null!==(_ref2=null!==(_tabName=tabName)&&void 0!==_tabName?_tabName:getActiveTabName())&&void 0!==_ref2?_ref2:(()=>{const element=document.querySelector(SELECTORS.tabContent);return(null==element?void 0:element.dataset.tabContent)||null})();const tab=document.querySelector(SELECTORS.forTabName(tabName));if(!tab)return;const pendingPromise=new _pending.default("core/dynamic_tabs:loadTab:"+tabName);(0,_loadingicon.addIconToContainer)(tab).then((()=>{let tabArgs={...tab.dataset};return delete tabArgs.tabClass,delete tabArgs.tabContent,(0,_dynamic_tabs.getContent)(tab.dataset.tabClass,JSON.stringify(tabArgs))})).then((response=>Promise.all([_jquery.default.parseHTML(response.javascript,null,!0).map((node=>node.innerHTML)).join("\n"),_templates.default.renderForPromise(response.template,JSON.parse(response.content))]))).then((_ref3=>{let[responseJs,{html:html,js:js}]=_ref3;return _templates.default.replaceNodeContents(tab,html,js+responseJs)})).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)},openTab=tabName=>{const tab=(tabName=>document.querySelector(SELECTORS.forTabId(tabName)))(tabName);return!!tab&&(loadTab(tabName),tab.classList.add("active"),(tabName=>document.getElementById(tabName))(tabName).classList.add("active","show"),!0)},openTabFromHash=()=>{const hash=document.location.hash;return!!hash.match(/^#\w+$/g)&&openTab(hash.replace(/^#/g,""))}})); /** * This is an empty module, that is required before all other modules. * Because every module is returned from a request for any other module, this * forces the loading of all modules with a single request. * * This function also sets up the listeners for ajax requests so we can tell * if any requests are still in progress. * * @module core/first * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */ define("core/first",["jquery"],(function($){$(document).bind("ajaxStart",(function(){M.util.js_pending("jq")})).bind("ajaxStop",(function(){M.util.js_complete("jq")}))})); /** * Autocomplete wrapper for select2 library. * * @module core/form-autocomplete * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.0 */ define("core/form-autocomplete",["jquery","core/log","core/str","core/templates","core/notification","core/loadingicon","core/aria","core_form/changechecker"],(function($,log,str,templates,notification,LoadingIcon,Aria,FormChangeChecker){var KEYS_DOWN=40,KEYS_ENTER=13,KEYS_SPACE=32,KEYS_ESCAPE=27,KEYS_COMMA=44,KEYS_UP=38,KEYS_LEFT=37,KEYS_RIGHT=39,uniqueId=Date.now(),activateSelection=function(index,state){var selectionElement=$(document.getElementById(state.selectionId)),length=selectionElement.children("[aria-selected=true]").length;for(index%=length;index<0;)index+=length;var element=$(selectionElement.children("[aria-selected=true]").get(index)),itemId=state.selectionId+"-"+index;return selectionElement.children().attr("data-active-selection",null).attr("id",""),element.attr("data-active-selection",!0).attr("id",itemId),selectionElement.attr("aria-activedescendant",itemId),selectionElement.attr("data-active-value",element.attr("data-value")),$.Deferred().resolve()},updateActiveSelectionFromState=function(state){var activeElement=function(state){var _selectionRegion$attr,selectionRegion=$(document.getElementById(state.selectionId)),activeId=selectionRegion.attr("aria-activedescendant");if(activeId){var activeElement=$(document.getElementById(activeId));if(activeElement.length)return activeElement}var activeValue=null===(_selectionRegion$attr=selectionRegion.attr("data-active-value"))||void 0===_selectionRegion$attr?void 0:_selectionRegion$attr.replace(/"/g,'\\"');return selectionRegion.find('[data-value="'+activeValue+'"]')}(state),activeValue=activeElement.attr("data-value"),selectionRegion=$(document.getElementById(state.selectionId));if(activeValue){var activeIndex=selectionRegion.find("[aria-selected=true]").index(activeElement);if(-1!==activeIndex)return void activateSelection(activeIndex,state)}activateSelection(0,state)},updateSelectionList=function(options,state,originalSelect){var pendingKey="form-autocomplete-updateSelectionList-"+state.inputId;M.util.js_pending(pendingKey);var items=[],newSelection=$(document.getElementById(state.selectionId));if(originalSelect.children("option").each((function(index,ele){var label;$(ele).prop("selected")&&(""!==(label=$(ele).data("html")?$(ele).data("html"):$(ele).html())&&items.push({label:label,value:$(ele).attr("value")}))})),!hasItemListChanged(state,items))return M.util.js_complete(pendingKey),Promise.resolve();state.items=items;var context=$.extend(options,state);return templates.render(options.templates.items,context).then((function(html,js){templates.replaceNodeContents(newSelection,html,js),updateActiveSelectionFromState(state)})).then((function(){return M.util.js_complete(pendingKey)})).catch(notification.exception)},hasItemListChanged=function(state,items){return state.items.length!==items.length||state.items.filter((item=>-1===items.indexOf(item))).length>0},notifyChange=function(originalSelect){FormChangeChecker.markFormChangedFromNode(originalSelect[0]),originalSelect[0].dispatchEvent(new Event("change"))},deselectItem=function(options,state,item,originalSelect){var selectedItemValue=$(item).attr("data-value");return originalSelect.prepend($("<option>")),originalSelect.children("option").each((function(index,ele){$(ele).attr("value")==selectedItemValue&&($(ele).prop("selected",!1),$(ele).attr("data-iscustom")&&$(ele).remove())})),updateSelectionList(options,state,originalSelect).then((function(){notifyChange(originalSelect)}))},activateItem=function(index,state){var inputElement=$(document.getElementById(state.inputId)),suggestionsElement=$(document.getElementById(state.suggestionsId)),length=suggestionsElement.children(":not([aria-hidden])").length;for(index%=length;index<0;)index+=length;var element=$(suggestionsElement.children(":not([aria-hidden])").get(index)),globalIndex=$(suggestionsElement.children("[role=option]")).index(element),itemId=state.suggestionsId+"-"+globalIndex;suggestionsElement.children().attr("aria-selected",!1).attr("id",""),element.attr("aria-selected",!0).attr("id",itemId),inputElement.attr("aria-activedescendant",itemId);var scrollPos=element.offset().top-suggestionsElement.offset().top+suggestionsElement.scrollTop()-suggestionsElement.height()/2;return suggestionsElement.animate({scrollTop:scrollPos},100).promise()},closeSuggestions=function(state){var inputElement=$(document.getElementById(state.inputId)),suggestionsElement=$(document.getElementById(state.suggestionsId));return"true"===inputElement.attr("aria-expanded")&&inputElement.attr("aria-expanded",!1),inputElement.attr("aria-activedescendant",state.selectionId),Aria.hide(suggestionsElement.get()),suggestionsElement.hide(),$.Deferred().resolve()},updateSuggestions=function(options,state,query,originalSelect){var pendingKey="form-autocomplete-updateSuggestions-"+state.inputId;M.util.js_pending(pendingKey);var inputElement=$(document.getElementById(state.inputId)),suggestionsElement=$(document.getElementById(state.suggestionsId)),matchingElements=!1,suggestions=[];originalSelect.children("option").each((function(index,option){!0!==$(option).prop("selected")&&(suggestions[suggestions.length]={label:option.innerHTML,value:$(option).attr("value")})}));var searchquery=state.caseSensitive?query:query.toLocaleLowerCase(),context=$.extend({options:suggestions},options,state);return templates.render("core/form_autocomplete_suggestions",context).then((function(html,js){return templates.replaceNode(suggestionsElement,html,js),suggestionsElement=$(document.getElementById(state.suggestionsId)),Aria.unhide(suggestionsElement.get()),suggestionsElement.show(),suggestionsElement.children().each((function(index,node){node=$(node),options.caseSensitive&&node.text().indexOf(searchquery)>-1||!options.caseSensitive&&node.text().toLocaleLowerCase().indexOf(searchquery)>-1?(Aria.unhide(node.get()),node.show(),matchingElements=!0):(node.hide(),Aria.hide(node.get()))})),inputElement.attr("aria-expanded",!0),originalSelect.attr("data-notice")?suggestionsElement.html(originalSelect.attr("data-notice")):matchingElements?options.tags||activateItem(0,state):str.get_string("nosuggestions","form").done((function(nosuggestionsstr){suggestionsElement.html(nosuggestionsstr)})),suggestionsElement})).then((function(){return M.util.js_complete(pendingKey)})).catch(notification.exception)},createItem=function(options,state,originalSelect){var inputElement=$(document.getElementById(state.inputId)),tags=inputElement.val().split(","),found=!1;return $.each(tags,(function(tagindex,tag){if(""!==(tag=tag.trim())&&(options.multiple||originalSelect.children("option").prop("selected",!1),originalSelect.children("option").each((function(index,ele){$(ele).attr("value")==tag&&(found=!0,$(ele).prop("selected",!0))})),!found)){var option=$("<option>");option.append(document.createTextNode(tag)),option.attr("value",tag),originalSelect.append(option),option.prop("selected",!0),option.attr("data-iscustom",!0)}})),updateSelectionList(options,state,originalSelect).then((function(){notifyChange(originalSelect)})).then((function(){inputElement.val("")})).then((function(){return closeSuggestions(state)}))},selectCurrentItem=function(options,state,originalSelect){var inputElement=$(document.getElementById(state.inputId)),selectedItemValue=$(document.getElementById(state.suggestionsId)).children("[aria-selected=true]").attr("data-value");return options.multiple||originalSelect.children("option").prop("selected",!1),originalSelect.children("option").each((function(index,ele){$(ele).attr("value")==selectedItemValue&&$(ele).prop("selected",!0)})),updateSelectionList(options,state,originalSelect).then((function(){notifyChange(originalSelect)})).then((function(){return options.closeSuggestionsOnSelect?(inputElement.val(""),closeSuggestions(state)):(inputElement.focus(),updateSuggestions(options,state,inputElement.val(),originalSelect))}))},updateAjax=function(e,options,state,originalSelect,ajaxHandler){var pendingPromise=addPendingJSPromise("updateAjax"),parentElement=$(document.getElementById(state.selectId)).parent();LoadingIcon.addIconToContainerRemoveOnCompletion(parentElement,pendingPromise);var query=$(e.currentTarget).val();return ajaxHandler.transport(options.selector,query,(function(results){var processedResults=ajaxHandler.processResults(options.selector,results),existingValues=[];if(originalSelect.children("option").each((function(optionIndex,option){(option=$(option)).prop("selected")?existingValues.push(String(option.attr("value"))):option.remove()})),!options.multiple&&0===originalSelect.children("option").length){var option=$("<option>");originalSelect.append(option)}$.isArray(processedResults)?($.each(processedResults,(function(resultIndex,result){if(-1===existingValues.indexOf(String(result.value))){var option=$("<option>");option.append(result.label),option.attr("value",result.value),originalSelect.append(option)}})),originalSelect.attr("data-notice","")):originalSelect.attr("data-notice",processedResults),pendingPromise.resolve(updateSuggestions(options,state,"",originalSelect))}),(function(error){pendingPromise.reject(error)})),pendingPromise},addNavigation=function(options,state,originalSelect){var inputElement=$(document.getElementById(state.inputId));(inputElement.on("keydown",(function(e){var pendingJsPromise=addPendingJSPromise("addNavigation-"+state.inputId+"-"+e.keyCode);switch(e.keyCode){case KEYS_DOWN:return options.showSuggestions?("true"===inputElement.attr("aria-expanded")?pendingJsPromise.resolve(function(state){var suggestionsElement=$(document.getElementById(state.suggestionsId)),element=suggestionsElement.children("[aria-selected=true]"),current=suggestionsElement.children(":not([aria-hidden])").index(element);return activateItem(current+1,state)}(state)):!inputElement.val()&&options.ajax?require([options.ajax],(function(ajaxHandler){pendingJsPromise.resolve(updateAjax(e,options,state,originalSelect,ajaxHandler))})):pendingJsPromise.resolve(updateSuggestions(options,state,inputElement.val(),originalSelect)),e.preventDefault(),!1):(pendingJsPromise.resolve(),!0);case KEYS_UP:return pendingJsPromise.resolve(function(state){var suggestionsElement=$(document.getElementById(state.suggestionsId)),element=suggestionsElement.children("[aria-selected=true]"),current=suggestionsElement.children(":not([aria-hidden])").index(element);return activateItem(current-1,state)}(state)),e.preventDefault(),!1;case KEYS_ENTER:var suggestionsElement=$(document.getElementById(state.suggestionsId));return"true"===inputElement.attr("aria-expanded")&&suggestionsElement.children("[aria-selected=true]").length>0?pendingJsPromise.resolve(selectCurrentItem(options,state,originalSelect)):options.tags?pendingJsPromise.resolve(createItem(options,state,originalSelect)):pendingJsPromise.resolve(),e.preventDefault(),!1;case KEYS_ESCAPE:return"true"===inputElement.attr("aria-expanded")?pendingJsPromise.resolve(closeSuggestions(state)):pendingJsPromise.resolve(),e.preventDefault(),!1}return pendingJsPromise.resolve(),!0})),inputElement.on("keypress",(function(e){return e.keyCode!==KEYS_COMMA||(options.tags&&addPendingJSPromise("keypress-"+e.keyCode).resolve(createItem(options,state,originalSelect)),e.preventDefault(),!1)})),inputElement.closest("form").on("submit",(function(){return options.tags&&addPendingJSPromise("form-autocomplete-submit").resolve(createItem(options,state,originalSelect)),!0})),inputElement.on("blur",(function(){var pendingPromise=addPendingJSPromise("form-autocomplete-blur");window.setTimeout((function(){var focusElement=$(document.activeElement),timeoutPromise=$.Deferred();focusElement.is(document.getElementById(state.suggestionsId))?inputElement.focus():!focusElement.is(inputElement)&&$(document.getElementById(state.inputId)).length&&(options.tags&&timeoutPromise.then((function(){return createItem(options,state,originalSelect)})).catch(),timeoutPromise.then((function(){return closeSuggestions(state)})).catch()),timeoutPromise.then((function(){return pendingPromise.resolve()})).catch(),timeoutPromise.resolve()}),500)})),options.showSuggestions)&&$(document.getElementById(state.downArrowId)).on("click",(function(e){var pendingPromise=addPendingJSPromise("form-autocomplete-show-suggestions");inputElement.focus(),!inputElement.val()&&options.ajax?require([options.ajax],(function(ajaxHandler){pendingPromise.resolve(updateAjax(e,options,state,originalSelect,ajaxHandler))})):pendingPromise.resolve(updateSuggestions(options,state,inputElement.val(),originalSelect))}));var suggestionsElement=$(document.getElementById(state.suggestionsId));suggestionsElement.parent().prop("onclick",null).off("click"),suggestionsElement.parent().on("click","#".concat(state.suggestionsId," [role=option]"),(function(e){var pendingPromise=addPendingJSPromise("form-autocomplete-parent"),element=$(e.currentTarget).closest("[role=option]"),current=$(document.getElementById(state.suggestionsId)).children(":not([aria-hidden])").index(element);activateItem(current,state).then((function(){return selectCurrentItem(options,state,originalSelect)})).then((function(){return pendingPromise.resolve()})).catch()}));var selectionElement=$(document.getElementById(state.selectionId));selectionElement.on("click","[role=option]",(function(e){addPendingJSPromise("form-autocomplete-clicks").resolve(deselectItem(options,state,$(e.currentTarget),originalSelect))})),selectionElement.on("focus",(function(){updateActiveSelectionFromState(state)})),selectionElement.on("keydown",(function(e){var pendingPromise=addPendingJSPromise("form-autocomplete-keydown-"+e.keyCode);switch(e.keyCode){case KEYS_RIGHT:case KEYS_DOWN:return e.preventDefault(),void pendingPromise.resolve(function(state){var selectionsElement=$(document.getElementById(state.selectionId)),element=selectionsElement.children("[data-active-selection]"),current=0;return element?(current=selectionsElement.children("[aria-selected=true]").index(element),current+=1):current=0,activateSelection(current,state)}(state));case KEYS_LEFT:case KEYS_UP:return e.preventDefault(),void pendingPromise.resolve(function(state){var selectionsElement=$(document.getElementById(state.selectionId)),element=selectionsElement.children("[data-active-selection]");if(!element)return activateSelection(0,state);var current=selectionsElement.children("[aria-selected=true]").index(element);return activateSelection(current-1,state)}(state));case KEYS_SPACE:case KEYS_ENTER:var selectedItem=$(document.getElementById(state.selectionId)).children("[data-active-selection]");return void(selectedItem&&(e.preventDefault(),pendingPromise.resolve(deselectItem(options,state,selectedItem,originalSelect))))}pendingPromise.resolve()})),options.showSuggestions&&(inputElement.on("focus",(function(e){var query=$(e.currentTarget).val();$(e.currentTarget).data("last-value",query)})),options.ajax?require([options.ajax],(function(ajaxHandler){var throttleTimeout=null,inProgress=!1,pendingKey="autocomplete-throttledhandler",handler=function(e){throttleTimeout=null,inProgress=!0,updateAjax(e,options,state,originalSelect,ajaxHandler).then((function(){return null===throttleTimeout&&M.util.js_complete(pendingKey),inProgress=!1,arguments[0]})).catch(notification.exception)},throttledHandler=function(e){window.clearTimeout(throttleTimeout),inProgress?throttleTimeout=window.setTimeout(throttledHandler.bind(this,e),100):(null===throttleTimeout&&M.util.js_pending(pendingKey),throttleTimeout=window.setTimeout(handler.bind(this,e),300))};inputElement.on("input",(function(e){var query=$(e.currentTarget).val();$(e.currentTarget).data("last-value")!==query&&throttledHandler(e),$(e.currentTarget).data("last-value",query)}))})):inputElement.on("input",(function(e){var query=$(e.currentTarget).val();$(e.currentTarget).data("last-value")!==query&&updateSuggestions(options,state,query,originalSelect),$(e.currentTarget).data("last-value",query)})))},addPendingJSPromise=function(key){var pendingKey="form-autocomplete:"+key;M.util.js_pending(pendingKey);var pendingPromise=$.Deferred();return pendingPromise.then((function(){return M.util.js_complete(pendingKey),arguments[0]})).catch(notification.exception),pendingPromise};return{enhance:function(selector,tags,ajax,placeholder,caseSensitive,showSuggestions,noSelectionString,closeSuggestionsOnSelect,templateOverrides){var options={selector:selector,tags:!1,ajax:!1,placeholder:placeholder,caseSensitive:!1,showSuggestions:!0,noSelectionString:noSelectionString,templates:$.extend({input:"core/form_autocomplete_input",items:"core/form_autocomplete_selection_items",layout:"core/form_autocomplete_layout",selection:"core/form_autocomplete_selection",suggestions:"core/form_autocomplete_suggestions"},templateOverrides)},pendingKey="autocomplete-setup-"+selector;M.util.js_pending(pendingKey),void 0!==tags&&(options.tags=tags),void 0!==ajax&&(options.ajax=ajax),void 0!==caseSensitive&&(options.caseSensitive=caseSensitive),void 0!==showSuggestions&&(options.showSuggestions=showSuggestions),void 0===noSelectionString&&str.get_string("noselection","form").done((function(result){options.noSelectionString=result})).fail(notification.exception);var originalSelect=$(selector);if(!originalSelect)return log.debug("Selector not found: "+selector),M.util.js_complete(pendingKey),!1;if("enhanced"===originalSelect.data("enhanced"))return M.util.js_complete(pendingKey),!1;originalSelect.data("enhanced","enhanced"),Aria.hide(originalSelect.get()),originalSelect.css("visibility","hidden");var state={selectId:originalSelect.attr("id"),inputId:"form_autocomplete_input-"+uniqueId,suggestionsId:"form_autocomplete_suggestions-"+uniqueId,selectionId:"form_autocomplete_selection-"+uniqueId,downArrowId:"form_autocomplete_downarrow-"+uniqueId,items:[]};uniqueId++,options.multiple=originalSelect.attr("multiple"),options.multiple||originalSelect.prepend("<option>"),options.closeSuggestionsOnSelect=void 0!==closeSuggestionsOnSelect?closeSuggestionsOnSelect:!options.multiple;var originalLabel=$("[for="+state.selectId+"]"),suggestions=[];originalSelect.children("option").each((function(index,option){suggestions[index]={label:option.innerHTML,value:$(option).attr("value")}}));var context=$.extend({},options,state);context.options=suggestions,context.items=[];var collectedjs="",renderLayout=templates.render(options.templates.layout,{}).then((function(html){return $(html)})),renderInput=templates.render(options.templates.input,context).then((function(html,js){return collectedjs+=js,$(html)})),renderDatalist=templates.render(options.templates.suggestions,context).then((function(html,js){return collectedjs+=js,$(html)})),renderSelection=templates.render(options.templates.selection,context).then((function(html,js){return collectedjs+=js,$(html)}));return $.when(renderLayout,renderInput,renderDatalist,renderSelection).then((function(layout,input,suggestions,selection){originalSelect.hide();var container=originalSelect.parent();input.find("input").attr("data-fieldtype","autocomplete"),container.append(layout),container.find('[data-region="form_autocomplete-input"]').replaceWith(input),container.find('[data-region="form_autocomplete-suggestions"]').replaceWith(suggestions),container.find('[data-region="form_autocomplete-selection"]').replaceWith(selection),templates.runTemplateJS(collectedjs),originalLabel.attr("for",state.inputId),addNavigation(options,state,originalSelect);var suggestionsElement=$(document.getElementById(state.suggestionsId));suggestionsElement.hide(),Aria.hide(suggestionsElement.get())})).then((function(){return updateSelectionList(options,state,originalSelect)})).then((function(){return M.util.js_complete(pendingKey)})).catch((function(error){M.util.js_complete(pendingKey),notification.exception(error)}))}}})); /** * Icon System base module. * * @module core/icon_system * @copyright 2017 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/icon_system",["jquery"],(function($){var IconSystem=function(){};return IconSystem.prototype.init=function(){return $.when(this)},IconSystem.prototype.renderIcon=function(key,component,title,template){throw new Error("Abstract function not implemented.")},IconSystem.prototype.getTemplateName=function(){throw new Error("Abstract function not implemented.")},IconSystem})); /** * Competency rule points module. * * @module core/icon_system_fontawesome * @copyright 2017 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/icon_system_fontawesome",["core/icon_system","jquery","core/ajax","core/mustache","core/localstorage","core/url"],(function(IconSystem,$,Ajax,Mustache,LocalStorage,Url){var staticMap=null,fetchMap=null,IconSystemFontawesome=function(){IconSystem.apply(this,arguments)};return(IconSystemFontawesome.prototype=Object.create(IconSystem.prototype)).init=function(){var currTheme=M.cfg.theme;if(staticMap)return $.when(this);var map=LocalStorage.get("core_iconsystem/theme/"+currTheme+"/core/iconmap-fontawesome");return map&&(map=JSON.parse(map)),map?(staticMap=map,$.when(this)):(null===fetchMap&&(fetchMap=Ajax.call([{methodname:"core_output_load_fontawesome_icon_system_map",args:{themename:M.cfg.theme}}],!0,!1,!1,0,M.cfg.themerev)[0]),fetchMap.then(function(map){return staticMap={},$.each(map,(function(index,value){staticMap[value.component+"/"+value.pix]=value.to})),LocalStorage.set("core_iconsystem/theme/"+currTheme+"/core/iconmap-fontawesome",JSON.stringify(staticMap)),this}.bind(this)))},IconSystemFontawesome.prototype.renderIcon=function(key,component,title,template){var mappedIcon=staticMap[component+"/"+key],unmappedIcon=!1;void 0===mappedIcon&&(unmappedIcon={attributes:[{name:"src",value:Url.imageUrl(key,component)},{name:"alt",value:title},{name:"title",value:title}]});var context={key:mappedIcon,title:title,alt:title,unmappedIcon:unmappedIcon};return void 0!==title&&""!==title||(context["aria-hidden"]=!0),Mustache.render(template,context).trim()},IconSystemFontawesome.prototype.getTemplateName=function(){return"core/pix_icon_fontawesome"},IconSystemFontawesome})); /** * Competency rule points module. * * @module core/icon_system_standard * @copyright 2017 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/icon_system_standard",["core/icon_system","core/url","core/mustache"],(function(IconSystem,CoreUrl,Mustache){var IconSystemStandard=function(){IconSystem.apply(this,arguments)};return(IconSystemStandard.prototype=Object.create(IconSystem.prototype)).renderIcon=function(key,component,title,template){var templatecontext={attributes:[{name:"src",value:CoreUrl.imageUrl(key,component)},{name:"alt",value:title},{name:"title",value:title}]};return void 0!==title&&""!=title||templatecontext.attributes.push({name:"aria-hidden",value:"true"}),Mustache.render(template,templatecontext).trim()},IconSystemStandard.prototype.getTemplateName=function(){return"core/pix_icon"},IconSystemStandard})); /** * Contain the logic for the loading icon. * * @module core/loading_icon * @class loading_icon * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/loadingicon",["jquery","core/templates"],(function($,Templates){var TEMPLATES_LOADING="core/loading",getIcon=function(){return Templates.render(TEMPLATES_LOADING,{})},addIconToContainerRemoveOnCompletion=function(container,loadingIconPromise){return getIcon().then((function(html){var loadingIcon=$(html).hide();return $(container).append(loadingIcon),loadingIcon.fadeIn(150),$.when(loadingIcon.promise(),loadingIconPromise)})).then((function(loadingIcon){return loadingIcon.fadeOut(100).promise()})).then((function(loadingIcon){loadingIcon.remove()}))};return{getIcon:getIcon,addIconToContainer:function(container){return getIcon().then((function(html){var loadingIcon=$(html).hide();return $(container).append(loadingIcon),loadingIcon.fadeIn(150),loadingIcon}))},addIconToContainerWithPromise:function(container){var loadingIconPromise=$.Deferred();return addIconToContainerRemoveOnCompletion(container,loadingIconPromise),loadingIconPromise},addIconToContainerRemoveOnCompletion:addIconToContainerRemoveOnCompletion}})); define("core/menu_navigation",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Keyboard initialization for a given html node. * * @module core/menu_navigation * @copyright 2021 Moodle * @author Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS_menuitem='[role="menuitem"]',SELECTORS_tab='[role="tab"]',SELECTORS_dropdowntoggle='[data-toggle="dropdown"]';let openDropdownNode=null;const clickErrorHandler=(item,fallback)=>null!==item?item:fallback,menuItemHelper=src=>{let parent;if(!src.dataset.disableactive){if(src.classList.contains("dropdown-item")){parent=src.closest(".dropdown-menu");const dropDownToggle=document.getElementById(parent.getAttribute("aria-labelledby"));dropDownToggle.classList.add("active"),dropDownToggle.setAttribute("tabindex",0)}else{if(!src.matches("".concat(SELECTORS_tab,",").concat(SELECTORS_menuitem))||src.matches(SELECTORS_dropdowntoggle))return;parent=src.parentElement.parentElement.querySelector(".dropdown-menu")}Array.prototype.forEach.call(parent.children,(node=>{const menuItem=node.querySelector(SELECTORS_menuitem);null!==menuItem&&(menuItem.classList.remove("active"),menuItem.removeAttribute("aria-current"))})),"menuitem"===src.getAttribute("role")&&src.setAttribute("aria-current","true")}},keyboardListenerEvents=e=>{const src=e.srcElement,firstNode=e.currentTarget.firstElementChild,lastNode=findUsableLastNode(e.currentTarget);if(src.classList.contains("dropdown-item"))"ArrowRight"!=e.key&&"ArrowLeft"!=e.key||(e.preventDefault(),null!==openDropdownNode&&openDropdownNode.parentElement.click())," "!=e.key&&"Enter"!=e.key||(e.preventDefault(),menuItemHelper(src),src.parentElement.classList.contains("dropdown")||src.click());else{const rtl=window.right_to_left(),arrowNext=rtl?"ArrowLeft":"ArrowRight",arrowPrevious=rtl?"ArrowRight":"ArrowLeft";"menuitem"===src.getAttribute("role")&&(e.key==arrowNext&&(e.preventDefault(),setFocusNext(src,firstNode)),e.key==arrowPrevious&&(e.preventDefault(),setFocusPrev(src,lastNode)),"ArrowUp"!=e.key&&"ArrowDown"!=e.key||(openDropdownNode=src,e.preventDefault()),"Home"==e.key&&(e.preventDefault(),setFocusHomeEnd(firstNode)),"End"==e.key&&(e.preventDefault(),setFocusHomeEnd(lastNode)))," "!=e.key&&"Enter"!=e.key||(e.preventDefault(),src.parentElement.classList.contains("dropdown")||src.click())}},clickListenerEvents=e=>{const src=e.srcElement;menuItemHelper(src)};_exports.default=elementRoot=>{elementRoot.removeEventListener("keydown",keyboardListenerEvents),elementRoot.removeEventListener("click",clickListenerEvents),elementRoot.addEventListener("keydown",keyboardListenerEvents),elementRoot.addEventListener("click",clickListenerEvents)};const setFocusNext=(currentNode,firstNode)=>{const listElement=currentNode.parentElement,nextListItem=(el=>{do{el=el.nextElementSibling}while(el&&!el.offsetHeight);return el})(listElement),nodeToSelect=clickErrorHandler(nextListItem,firstNode),itemSelector="tablist"===listElement.parentElement.getAttribute("role")?SELECTORS_tab:SELECTORS_menuitem;nodeToSelect.querySelector(itemSelector).focus()},setFocusPrev=(currentNode,lastNode)=>{const listElement=currentNode.parentElement,nextListItem=(el=>{do{el=el.previousElementSibling}while(el&&!el.offsetHeight);return el})(listElement),nodeToSelect=clickErrorHandler(nextListItem,lastNode),itemSelector="tablist"===listElement.parentElement.getAttribute("role")?SELECTORS_tab:SELECTORS_menuitem;nodeToSelect.querySelector(itemSelector).focus()},setFocusHomeEnd=node=>{node.querySelector(SELECTORS_menuitem).focus()},findUsableLastNode=elementRoot=>{if(elementRoot.lastElementChild.classList.contains("d-none")){const nodesToUse=Array.prototype.map.call(elementRoot.children,(node=>node)).reverse().filter((node=>{if(!node.classList.contains("d-none"))return node}));return 0!==nodesToUse.length?nodesToUse[0]:elementRoot.firstElementChild}return elementRoot.lastElementChild};return _exports.default})); /** * Contain the logic for modals. * * @module core/modal * @class core/modal * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/modal",["jquery","core/templates","core/notification","core/key_codes","core/custom_interaction_events","core/modal_backdrop","core_filters/events","core/modal_events","core/local/aria/focuslock","core/pending","core/aria","core/fullscreen"],(function($,Templates,Notification,KeyCodes,CustomEvents,ModalBackdrop,FilterEvents,ModalEvents,FocusLock,Pending,Aria,Fullscreen){var backdropPromise,SELECTORS_CONTAINER='[data-region="modal-container"]',SELECTORS_MODAL='[data-region="modal"]',SELECTORS_HEADER='[data-region="header"]',SELECTORS_TITLE='[data-region="title"]',SELECTORS_BODY='[data-region="body"]',SELECTORS_FOOTER='[data-region="footer"]',SELECTORS_HIDE='[data-action="hide"]',SELECTORS_DIALOG="[role=dialog]",SELECTORS_FORM="form",SELECTORS_MENU_BAR="[role=menubar]",SELECTORS_HAS_Z_INDEX=".moodle-has-zindex",TEMPLATES_LOADING="core/loading",TEMPLATES_BACKDROP="core/modal_backdrop",modalCounter=0,Modal=function(root){this.root=$(root),this.modal=this.root.find(SELECTORS_MODAL),this.header=this.modal.find(SELECTORS_HEADER),this.headerPromise=$.Deferred(),this.title=this.header.find(SELECTORS_TITLE),this.titlePromise=$.Deferred(),this.body=this.modal.find(SELECTORS_BODY),this.bodyPromise=$.Deferred(),this.footer=this.modal.find(SELECTORS_FOOTER),this.footerPromise=$.Deferred(),this.hiddenSiblings=[],this.isAttached=!1,this.bodyJS=null,this.footerJS=null,this.modalCount=modalCounter++,this.attachmentPoint=document.createElement("div"),document.body.append(this.attachmentPoint),this.focusOnClose=null,this.root.is(SELECTORS_CONTAINER)||Notification.exception({message:"Element is not a modal container"}),this.modal.length||Notification.exception({message:"Container does not contain a modal"}),this.header.length||Notification.exception({message:"Modal is missing a header region"}),this.title.length||Notification.exception({message:"Modal header is missing a title region"}),this.body.length||Notification.exception({message:"Modal is missing a body region"}),this.footer.length||Notification.exception({message:"Modal is missing a footer region"}),this.registerEventListeners()};return Modal.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root),this.isAttached||(FocusLock.trapFocus(this.root[0]),this.bodyJS&&(Templates.runTemplateJS(this.bodyJS),this.bodyJS=null),this.footerJS&&(Templates.runTemplateJS(this.footerJS),this.footerJS=null),this.isAttached=!0)},Modal.prototype.countOtherVisibleModals=function(){var count=0;return $("body").find(SELECTORS_CONTAINER).each(function(index,element){element=$(element),!this.root.is(element)&&element.hasClass("show")&&count++}.bind(this)),count},Modal.prototype.getBackdrop=function(){return backdropPromise||(backdropPromise=Templates.render(TEMPLATES_BACKDROP,{}).then((function(html){var element=$(html);return new ModalBackdrop(element)})).fail(Notification.exception)),backdropPromise},Modal.prototype.getRoot=function(){return this.root},Modal.prototype.getModal=function(){return this.modal},Modal.prototype.getTitle=function(){return this.title},Modal.prototype.getBody=function(){return this.body},Modal.prototype.getFooter=function(){return this.footer},Modal.prototype.getTitlePromise=function(){return this.titlePromise},Modal.prototype.getBodyPromise=function(){return this.bodyPromise},Modal.prototype.getFooterPromise=function(){return this.footerPromise},Modal.prototype.getModalCount=function(){return this.modalCount},Modal.prototype.setTitle=function(value){var title=this.getTitle();this.titlePromise=$.Deferred(),this.asyncSet(value,title.html.bind(title)).then(function(){this.titlePromise.resolve(title)}.bind(this)).catch(Notification.exception)},Modal.prototype.setBody=function(value){this.bodyPromise=$.Deferred();var body=this.getBody();if("string"==typeof value)body.html(value),FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),this.bodyPromise.resolve(body);else{var jsPendingId="amd-modal-js-pending-id-"+this.getModalCount();M.util.js_pending(jsPendingId);var contentPromise=null;if(body.css("overflow","hidden"),"pending"==(value=$.when(value)).state()){var height=body.innerHeight();height<100&&(height=100),body.animate({height:height+"px"},150),body.html(""),contentPromise=Templates.render(TEMPLATES_LOADING,{}).then((function(html){var loadingIcon=$(html).hide();return body.html(loadingIcon),loadingIcon.fadeIn(150),$.when(loadingIcon.promise(),value)})).then((function(loadingIcon){return loadingIcon.fadeOut(100).promise()})).then((function(){return value}))}else contentPromise=value;contentPromise.then(function(html,js){var result=null;if(this.isVisible()){body.css("opacity",0);var currentHeight=body.innerHeight();body.html(html),body.css("height","");var newHeight=body.innerHeight();body.css("height",currentHeight+"px"),result=body.animate({height:newHeight+"px",opacity:1},{duration:150,queue:!1}).promise()}else body.html(html);return js&&(this.isAttached?Templates.runTemplateJS(js):this.bodyJS=js),result}.bind(this)).then(function(result){return FilterEvents.notifyFilterContentUpdated(body),this.getRoot().trigger(ModalEvents.bodyRendered,this),result}.bind(this)).then(function(){this.bodyPromise.resolve(body)}.bind(this)).fail(Notification.exception).always((function(){body.css("height",""),body.css("overflow",""),body.css("opacity",""),M.util.js_complete(jsPendingId)})).fail(Notification.exception)}},Modal.prototype.setBodyContent=function(promise){return promise.then((_ref=>{let{html:html,js:js}=_ref;return this.setBody($.when(html,js))})).catch((exception=>{throw this.hide(),exception}))},Modal.prototype.setFooter=function(value){this.showFooter(),this.footerPromise=$.Deferred();var footer=this.getFooter();"string"==typeof value?(footer.html(value),this.footerPromise.resolve(footer)):Templates.render(TEMPLATES_LOADING,{}).then((function(html){return footer.html(html),value})).then(function(html,js){return footer.html(html),js&&(this.isAttached?Templates.runTemplateJS(js):this.footerJS=js),footer}.bind(this)).then(function(footer){this.footerPromise.resolve(footer)}.bind(this)).catch(Notification.exception)},Modal.prototype.hasFooterContent=function(){return!!this.getFooter().children().length},Modal.prototype.hideFooter=function(){this.getFooter().addClass("hidden")},Modal.prototype.showFooter=function(){this.getFooter().removeClass("hidden")},Modal.prototype.setLarge=function(){this.isLarge()||this.getModal().addClass("modal-lg")},Modal.prototype.isLarge=function(){return this.getModal().hasClass("modal-lg")},Modal.prototype.setSmall=function(){this.isSmall()||this.getModal().removeClass("modal-lg")},Modal.prototype.isSmall=function(){return!this.getModal().hasClass("modal-lg")},Modal.prototype.setScrollable=function(value){value?this.getModal()[0].classList.add("modal-dialog-scrollable"):this.getModal()[0].classList.remove("modal-dialog-scrollable")},Modal.prototype.calculateZIndex=function(){var items=$(SELECTORS_DIALOG+", "+SELECTORS_MENU_BAR+", "+SELECTORS_HAS_Z_INDEX),zIndex=parseInt(this.root.css("z-index"));return items.each((function(index,item){var itemZIndex=(item=$(item)).css("z-index")?parseInt(item.css("z-index")):0;itemZIndex>zIndex&&(zIndex=itemZIndex)})),zIndex},Modal.prototype.isVisible=function(){return this.root.hasClass("show")},Modal.prototype.hasFocus=function(){var target=$(document.activeElement);return this.root.is(target)||this.root.has(target).length},Modal.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")},Modal.prototype.getAttachmentPoint=function(){return $(Fullscreen.getElement()||this.attachmentPoint)},Modal.prototype.show=function(){if(this.isVisible())return $.Deferred().resolve();var pendingPromise=new Pending("core/modal:show");return this.hasFooterContent()?this.showFooter():this.hideFooter(),this.attachToDOM(),!this.focusOnClose&&document.activeElement&&(this.focusOnClose=document.activeElement),this.getBackdrop().then(function(backdrop){var newIndex=this.calculateZIndex()+2,newBackdropIndex=newIndex-1;this.root.css("z-index",newIndex),backdrop.setZIndex(newBackdropIndex),backdrop.show(),this.root.removeClass("hide").addClass("show"),this.accessibilityShow(),this.getModal().focus(),$("body").addClass("modal-open"),this.root.trigger(ModalEvents.shown,this)}.bind(this)).then(pendingPromise.resolve)},Modal.prototype.hideIfNotForm=function(){0==this.modal.find(SELECTORS_FORM).length&&this.hide()},Modal.prototype.hide=function(){this.getBackdrop().done(function(backdrop){FocusLock.untrapFocus(),this.countOtherVisibleModals()||(backdrop.hide(),$("body").removeClass("modal-open"));var currentIndex=parseInt(this.root.css("z-index"));this.root.css("z-index",""),backdrop.setZIndex(currentIndex-3),this.accessibilityHide(),this.hasTransitions()?this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this)):this.getRoot().removeClass("show").addClass("hide"),$(document.body).find(this.getRoot()).length&&$(document.body).append(this.getRoot()),this.root.trigger(ModalEvents.hidden,this)}.bind(this))},Modal.prototype.destroy=function(){this.hide(),this.root.remove(),this.root.trigger(ModalEvents.destroyed,this),this.attachmentPoint.remove()},Modal.prototype.accessibilityShow=function(){Aria.unhide(this.root.get()),Aria.hideSiblings(this.root.get()[0])},Modal.prototype.accessibilityHide=function(){Aria.unhideSiblings(this.root.get()[0]),Aria.hide(this.root.get())},Modal.prototype.registerEventListeners=function(){this.getRoot().on("keydown",function(e){this.isVisible()&&e.keyCode==KeyCodes.escape&&(this.removeOnClose?this.destroy():this.hide())}.bind(this)),this.getRoot().click(function(e){if(!$(e.target).closest(SELECTORS_MODAL).length&&$(e.target).closest(SELECTORS_CONTAINER).length){var outsideClickEvent=$.Event(ModalEvents.outsideClick);this.getRoot().trigger(outsideClickEvent,this),outsideClickEvent.isDefaultPrevented()||this.hideIfNotForm()}}.bind(this)),CustomEvents.define(this.getModal(),[CustomEvents.events.activate]),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE,function(e,data){this.removeOnClose?this.destroy():this.hide(),data.originalEvent.preventDefault()}.bind(this)),this.getRoot().on(ModalEvents.hidden,(()=>{this.focusOnClose&&this.focusOnClose.focus()}))},Modal.prototype.registerCloseOnCancel=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("cancel"),function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.registerCloseOnSave=function(){this.getModal().on(CustomEvents.events.activate,this.getActionSelector("save"),function(e,data){var saveEvent=$.Event(ModalEvents.save);this.getRoot().trigger(saveEvent,this),saveEvent.isDefaultPrevented()||(data.originalEvent.preventDefault(),this.removeOnClose?this.destroy():this.hide())}.bind(this))},Modal.prototype.asyncSet=function(value,setFunction){var p=value;return"object"==typeof value&&value.hasOwnProperty("then")||(p=$.Deferred()).resolve(value),p.then((function(content){setFunction(content)})).fail(Notification.exception),p},Modal.prototype.setButtonText=function(action,value){const button=this.getFooter().find(this.getActionSelector(action));if(!button)throw new Error("Unable to find the '"+action+"' button");return this.asyncSet(value,button.text.bind(button))},Modal.prototype.getActionSelector=function(action){return"[data-action='"+action+"']"},Modal.prototype.setRemoveOnClose=function(remove){this.removeOnClose=remove},Modal.prototype.setReturnElement=function(element){this.focusOnClose=element},Modal})); /** * Contain the logic for modal backdrops. * * @module core/modal_backdrop * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/modal_backdrop",["jquery","core/templates","core/notification","core/fullscreen"],(function($,Templates,Notification,Fullscreen){var SELECTORS_ROOT='[data-region="modal-backdrop"]',ModalBackdrop=function(root){this.root=$(root),this.isAttached=!1,this.attachmentPoint=document.createElement("div"),document.body.append(this.attachmentPoint),this.root.is(SELECTORS_ROOT)||Notification.exception({message:"Element is not a modal backdrop"})};return ModalBackdrop.prototype.getRoot=function(){return this.root},ModalBackdrop.prototype.getAttachmentPoint=function(){return $(Fullscreen.getElement()||this.attachmentPoint)},ModalBackdrop.prototype.attachToDOM=function(){this.getAttachmentPoint().append(this.root),this.isAttached||(this.isAttached=!0)},ModalBackdrop.prototype.setZIndex=function(value){this.root.css("z-index",value)},ModalBackdrop.prototype.isVisible=function(){return this.root.hasClass("show")},ModalBackdrop.prototype.hasTransitions=function(){return this.getRoot().hasClass("fade")},ModalBackdrop.prototype.show=function(){this.isVisible()||(this.attachToDOM(),this.root.removeClass("hide").addClass("show"))},ModalBackdrop.prototype.hide=function(){this.isVisible()&&(this.hasTransitions()?this.getRoot().one("transitionend webkitTransitionEnd oTransitionEnd",function(){this.getRoot().removeClass("show").addClass("hide")}.bind(this)):this.getRoot().removeClass("show").addClass("hide"),$(document.body).find(this.getRoot()).length&&$(document.body).append(this.getRoot()))},ModalBackdrop.prototype.destroy=function(){this.root.remove(),this.attachmentPoint.remove()},ModalBackdrop})); define("core/modal_cancel",["exports","core/modal","core/notification"],(function(_exports,_modal,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Contain the logic for the cancel modal. * * @module core/modal_cancel * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_notification=_interopRequireDefault(_notification);class _default extends _modal.default{constructor(root){super(root),this.getFooter().find(this.getActionSelector("cancel")).length||_notification.default.exception({message:"No cancel button found"})}registerEventListeners(){super.registerEventListeners(),this.registerCloseOnCancel()}}return _exports.default=_default,_exports.default})); /** * Contain the events a modal can fire. * * @module core/modal_events * @class modal_events * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/modal_events",[],(function(){return{shown:"modal:shown",hidden:"modal:hidden",destroyed:"modal:destroyed",bodyRendered:"modal:bodyRendered",outsideClick:"modal:outsideClick",save:"modal-save-cancel:save",cancel:"modal-save-cancel:cancel"}})); /** * Create a modal. * * @module core/modal_factory * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/modal_factory",["jquery","core/modal_events","core/modal_registry","core/modal","core/modal_save_cancel","core/modal_cancel","core/local/modal/alert","core/templates","core/notification","core/custom_interaction_events","core/pending"],(function($,ModalEvents,ModalRegistry,Modal,ModalSaveCancel,ModalCancel,ModalAlert,Templates,Notification,CustomEvents,Pending){var TEMPLATES_DEFAULT="core/modal",TEMPLATES_SAVE_CANCEL="core/modal_save_cancel",TEMPLATES_CANCEL="core/modal_cancel",TEMPLATES_ALERT="core/local/modal/alert",TYPES={DEFAULT:"DEFAULT",SAVE_CANCEL:"SAVE_CANCEL",CANCEL:"CANCEL",ALERT:"ALERT"};ModalRegistry.register(TYPES.DEFAULT,Modal,TEMPLATES_DEFAULT),ModalRegistry.register(TYPES.SAVE_CANCEL,ModalSaveCancel,TEMPLATES_SAVE_CANCEL),ModalRegistry.register(TYPES.CANCEL,ModalCancel,TEMPLATES_CANCEL),ModalRegistry.register(TYPES.ALERT,ModalAlert,TEMPLATES_ALERT);var createFromType=function(registryConf,templateContext){var templateName=registryConf.template,modalPromise=Templates.render(templateName,templateContext).then((function(html){var modalElement=$(html);return function(registryConf,modalElement){return modalElement=$(modalElement),new(0,registryConf.module)(modalElement)}(registryConf,modalElement)})).fail(Notification.exception);return modalPromise};return{create:function(modalConfig,triggerElement){var registryConf,type=modalConfig.type||TYPES.DEFAULT,isLarge=!!modalConfig.large,isScrollable=!modalConfig.hasOwnProperty("scrollable")||modalConfig.scrollable,templateContext={};(registryConf=ModalRegistry.get(type))||Notification.exception({message:"Unable to find modal of type: "+type}),void 0!==modalConfig.templateContext&&(templateContext=modalConfig.templateContext);var pendingModalPromise=new Pending("core/modal_factory:create"),modalPromise=createFromType(registryConf,templateContext).then((function(modal){return void 0!==modalConfig.title&&modal.setTitle(modalConfig.title),void 0!==modalConfig.body&&modal.setBody(modalConfig.body),void 0!==modalConfig.footer&&modal.setFooter(modalConfig.footer),modalConfig.buttons&&Object.entries(modalConfig.buttons).forEach((function(_ref){let[key,value]=_ref;modal.setButtonText(key,value)})),isLarge&&modal.setLarge(),void 0!==modalConfig.removeOnClose&&modal.setRemoveOnClose(modalConfig.removeOnClose),modal.setScrollable(isScrollable),pendingModalPromise.resolve(),modal}));return void 0!==triggerElement&&function(modalPromise,triggerElement,modalConfig){var actualTriggerElement=null,hasPreShowCallback="function"==typeof modalConfig.preShowCallback,triggeredCallback=function(e,data){var pendingPromise=new Pending("core/modal_factory:setUpTrigger:triggeredCallback");actualTriggerElement=$(e.currentTarget),modalPromise.then((function(modal){return hasPreShowCallback&&modalConfig.preShowCallback(actualTriggerElement,modal),modal.show(),modal})).then(pendingPromise.resolve),data.originalEvent.preventDefault()};if(Array.isArray(triggerElement)){var selector=triggerElement[1];triggerElement=triggerElement[0],CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,selector,triggeredCallback)}else CustomEvents.define(triggerElement,[CustomEvents.events.activate]),triggerElement.on(CustomEvents.events.activate,triggeredCallback);modalPromise.then((function(modal){return modal.getRoot().on(ModalEvents.hidden,(function(){null!==actualTriggerElement&&actualTriggerElement.focus()})),modal}))}(modalPromise,triggerElement,modalConfig),modalPromise},types:TYPES}})); /** * A registry for the different types of modal. * * @module core/modal_registry * @class modal_registry * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/modal_registry",["core/notification","core/prefetch"],(function(Notification,Prefetch){var registry={},get=function(type){return registry[type]};return{register:function(type,module,template){get(type)&&Notification.exception({message:"Modal of type '"+type+"' is already registered"}),module&&"function"==typeof module||Notification.exception({message:"You must provide a modal module"}),template||Notification.exception({message:"You must provide a modal template"}),registry[type]={module:module,template:template},Prefetch.prefetchTemplate(template)},get:get}})); define("core/modal_save_cancel",["exports","core/modal","core/notification"],(function(_exports,_modal,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Contain the logic for the save/cancel modal. * * @module core/modal_save_cancel * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_notification=_interopRequireDefault(_notification);class _default extends _modal.default{constructor(root){super(root),this.getFooter().find(this.getActionSelector("save")).length||_notification.default.exception({message:"No save button found"}),this.getFooter().find(this.getActionSelector("cancel")).length||_notification.default.exception({message:"No cancel button found"})}registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}setFooter(){_notification.default.exception({message:"Can not change the footer of a save cancel modal"})}setSaveButtonText(value){return this.setButtonText("save",value)}}return _exports.default=_default,_exports.default})); define("core/normalise",["exports","jquery"],(function(_exports,_jquery){var obj; /** * Normalisation helpers. * * @module core/normalise * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getList=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.getList=nodes=>nodes instanceof HTMLElement?[nodes]:nodes instanceof Array?nodes:nodes instanceof NodeList?Array.from(nodes):nodes instanceof _jquery.default?nodes.get():Array.from(nodes)})); 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})); /** * Factory to create a paged content widget. * * @module core/paged_content_factory * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_factory",["jquery","core/templates","core/notification","core/paged_content","core/paged_content_events","core/pubsub","core/ajax"],(function($,Templates,Notification,PagedContent,PagedContentEvents,PubSub,Ajax){var TEMPLATES_PAGED_CONTENT="core/paged_content",DEFAULT_ITEMS_PER_PAGE_SINGLE=25,DEFAULT_ITEMS_PER_PAGE_ARRAY=[25,50,100,0],DEFAULT_MAX_PAGES=3,buildItemsPerPagePagingBarContext=function(itemsPerPage){var context=[];$.isArray(itemsPerPage)?(context=itemsPerPage.map((function(num){return"number"==typeof num?{value:num,active:!1}:num}))).filter((function(item){return item.active})).length||(context[0].active=!0):context=[{value:itemsPerPage,active:!0}];return context},buildPagingBarTemplateContext=function(numberOfItems,itemsPerPage){return numberOfItems?function(numberOfItems,itemsPerPage){null===itemsPerPage&&(itemsPerPage=DEFAULT_ITEMS_PER_PAGE_SINGLE),$.isArray(itemsPerPage)&&(itemsPerPage=itemsPerPage[0]);var context={showitemsperpageselector:!1,itemsperpage:[{value:35,active:!0}],previous:!0,next:!0,activepagenumber:1,hidecontrolonsinglepage:!0,pages:[]};context.itemsperpage=buildItemsPerPagePagingBarContext(itemsPerPage);for(var numberOfPages=function(numberOfItems,itemsPerPage){var numberOfPages=1;if(numberOfItems>0){var partial=numberOfItems%itemsPerPage;numberOfPages=partial?(numberOfItems-=partial)/itemsPerPage+1:numberOfItems/itemsPerPage}return numberOfPages}(numberOfItems,itemsPerPage),i=1;i<=numberOfPages;i++){var page={number:i,page:""+i};1===i&&(page.active=!0),context.pages.push(page)}return context.barsize=10,context}(numberOfItems,itemsPerPage):function(itemsPerPage){null===itemsPerPage&&(itemsPerPage=DEFAULT_ITEMS_PER_PAGE_ARRAY);var context={showitemsperpageselector:!1,itemsperpage:[{value:35,active:!0}],previous:!0,next:!0,activepagenumber:1,hidecontrolonsinglepage:!0,pages:[]};return context.itemsperpage=buildItemsPerPagePagingBarContext(itemsPerPage),context.showitemsperpageselector=$.isArray(itemsPerPage)&&itemsPerPage.length>1,context}(itemsPerPage)},buildTemplateContext=function(numberOfItems,itemsPerPage,config){var context={pagingbar:!1,pagingdropdown:!1,skipjs:!0,ignorecontrolwhileloading:!0,controlplacementbottom:!1};return config.hasOwnProperty("ignoreControlWhileLoading")&&(context.ignorecontrolwhileloading=config.ignoreControlWhileLoading),config.hasOwnProperty("controlPlacementBottom")&&(context.controlplacementbottom=config.controlPlacementBottom),config.hasOwnProperty("hideControlOnSinglePage")&&(context.hidecontrolonsinglepage=config.hideControlOnSinglePage),config.hasOwnProperty("ariaLabels")&&(context.arialabels=config.ariaLabels),config.hasOwnProperty("dropdown")&&config.dropdown?context.pagingdropdown=function(itemsPerPage,config){if(null===itemsPerPage&&(itemsPerPage=DEFAULT_ITEMS_PER_PAGE_SINGLE),$.isArray(itemsPerPage))return{options:itemsPerPage};var context={options:[]},totalItems=0,lastIncrease=0,maxPages=DEFAULT_MAX_PAGES;config.hasOwnProperty("maxPages")&&(maxPages=config.maxPages);for(var i=1;i<=maxPages;i++){var itemCount=0;i<=2?(itemCount=itemsPerPage,lastIncrease=itemsPerPage):itemCount=lastIncrease*=2;var option={itemcount:itemCount,content:totalItems+=itemCount};1===i&&(option.active=!0),context.options.push(option)}return context}(itemsPerPage,config):(context.pagingbar=buildPagingBarTemplateContext(numberOfItems,itemsPerPage),config.hasOwnProperty("showFirstLast")&&config.showFirstLast&&(context.pagingbar.first=!0,context.pagingbar.last=!0)),context},createWithTotalAndLimit=function(numberOfItems,itemsPerPage,renderPagesContentCallback,config){config=config||{};var deferred=$.Deferred(),templateContext=buildTemplateContext(numberOfItems,itemsPerPage,config);return Templates.render(TEMPLATES_PAGED_CONTENT,templateContext).then((function(html,js){var id=(html=$(html)).attr("id");config.hasOwnProperty("eventNamespace")&&(id=config.eventNamespace);var container=html;PagedContent.init(container,renderPagesContentCallback,id),registerEvents(id,config),deferred.resolve(html,js)})).fail((function(exception){deferred.reject(exception)})).fail(Notification.exception),deferred.promise()},registerEvents=function(namespace,config){var persistentLimitKey;config.hasOwnProperty("persistentLimitKey")&&PubSub.subscribe(namespace+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT,(persistentLimitKey=config.persistentLimitKey,function(limit){var request={methodname:"core_user_update_user_preferences",args:{preferences:[{type:persistentLimitKey,value:limit}]}};Ajax.call([request])}))};return{create:function(renderPagesContentCallback,config){return createWithTotalAndLimit(null,null,renderPagesContentCallback,config)},createWithLimit:function(itemsPerPage,renderPagesContentCallback,config){return createWithTotalAndLimit(null,itemsPerPage,renderPagesContentCallback,config)},createWithTotalAndLimit:createWithTotalAndLimit,createFromStaticList:function(contentItems,itemsPerPage,renderContentCallback,config){void 0===config&&(config={});var numberOfItems=contentItems.length;return createWithTotalAndLimit(numberOfItems,itemsPerPage,(function(pagesData){var contentToRender=[];return pagesData.forEach((function(pageData){var begin=pageData.offset,end=pageData.limit?begin+pageData.limit:numberOfItems,items=contentItems.slice(begin,end);contentToRender.push(items)})),renderContentCallback(contentToRender)}),config)},createFromAjax:createWithTotalAndLimit,resetLastPageNumber:function(id,lastPageNumber){PubSub.publish(id+PagedContentEvents.ALL_ITEMS_LOADED,lastPageNumber)}}})); /** * Javascript to enhance the paged content paging bar. * * @module core/paging_bar * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core/paged_content_paging_bar",["jquery","core/custom_interaction_events","core/paged_content_events","core/str","core/pubsub","core/pending"],(function($,CustomEvents,PagedContentEvents,Str,PubSub,Pending){var SELECTORS_PAGE="[data-page]",SELECTORS_PAGE_ITEM='[data-region="page-item"]',SELECTORS_PAGE_LINK='[data-region="page-link"]',SELECTORS_FIRST_BUTTON='[data-control="first"]',SELECTORS_LAST_BUTTON='[data-control="last"]',SELECTORS_NEXT_BUTTON='[data-control="next"]',SELECTORS_PREVIOUS_BUTTON='[data-control="previous"]',SELECTORS_DOTS_BUTTONS="[data-dots]",SELECTORS_BEGINNING_DOTS_BUTTON='[data-dots="beginning"]',SELECTORS_ENDING_DOTS_BUTTON='[data-dots="ending"]',getPageByNumber=function(root,pageNumber){return root.find(SELECTORS_PAGE_ITEM+'[data-page-number="'+pageNumber+'"]')},setLastPageNumber=function(root,number){root.attr("data-last-page-number",number)},getLastPageNumber=function(root){return parseInt(root.attr("data-last-page-number"),10)},getActivePageNumber=function(root){return parseInt(root.attr("data-active-page-number"),10)},setActivePageNumber=function(root,number){root.attr("data-active-page-number",number)},getPageNumber=function(root,page){if(null!=page.attr("data-page"))return parseInt(page.attr("data-page-number"),10);var pageNumber=1,activePageNumber=null;switch(page.attr("data-control")){case"first":default:pageNumber=1;break;case"last":pageNumber=getLastPageNumber(root);break;case"next":activePageNumber=getActivePageNumber(root);var lastPage=getLastPageNumber(root);pageNumber=lastPage?activePageNumber&&activePageNumber<lastPage?activePageNumber+1:lastPage:activePageNumber+1;break;case"previous":pageNumber=(activePageNumber=getActivePageNumber(root))&&activePageNumber>1?activePageNumber-1:1}return parseInt(pageNumber,10)},show=function(root){root.removeClass("hidden")},hide=function(root){root.addClass("hidden")},disableNextControlButtons=function(root){var nextButton=root.find(SELECTORS_NEXT_BUTTON),lastButton=root.find(SELECTORS_LAST_BUTTON);nextButton.addClass("disabled"),nextButton.attr("aria-disabled",!0),lastButton.addClass("disabled"),lastButton.attr("aria-disabled",!0)},enableNextControlButtons=function(root){var nextButton=root.find(SELECTORS_NEXT_BUTTON),lastButton=root.find(SELECTORS_LAST_BUTTON);nextButton.removeClass("disabled"),nextButton.removeAttr("aria-disabled"),lastButton.removeClass("disabled"),lastButton.removeAttr("aria-disabled")},disablePreviousControlButtons=function(root){var previousButton=root.find(SELECTORS_PREVIOUS_BUTTON),firstButton=root.find(SELECTORS_FIRST_BUTTON);previousButton.addClass("disabled"),previousButton.attr("aria-disabled",!0),firstButton.addClass("disabled"),firstButton.attr("aria-disabled",!0)},adjustPagingBarSize=function(root){var activePageNumber=getActivePageNumber(root),lastPageNumber=getLastPageNumber(root),dotsButtons=root.find(SELECTORS_DOTS_BUTTONS),beginningDotsButton=root.find(SELECTORS_BEGINNING_DOTS_BUTTON),endingDotsButton=root.find(SELECTORS_ENDING_DOTS_BUTTON),pages=root.find(SELECTORS_PAGE),barSize=parseInt(root.attr("data-bar-size"),10);if(barSize&&lastPageNumber>barSize){var minpage=Math.max(activePageNumber-Math.round(barSize/2),1),maxpage=minpage+barSize-1;maxpage>=lastPageNumber&&(minpage=(maxpage=lastPageNumber)-barSize+1),minpage>1?(show(beginningDotsButton),minpage++):hide(beginningDotsButton),maxpage<lastPageNumber?(show(endingDotsButton),maxpage--):hide(endingDotsButton),dotsButtons.addClass("disabled"),dotsButtons.attr("aria-disabled",!0),hide(pages),pages.each((function(index,page){page=$(page),index+1>=minpage&&index+1<=maxpage&&show(page)}))}else hide(dotsButtons)},enablePreviousControlButtons=function(root){var previousButton=root.find(SELECTORS_PREVIOUS_BUTTON),firstButton=root.find(SELECTORS_FIRST_BUTTON);previousButton.removeClass("disabled"),previousButton.removeAttr("aria-disabled"),firstButton.removeClass("disabled"),firstButton.removeAttr("aria-disabled")},showPage=function(root,pageNumber,id){var pendingPromise=new Pending("core/paged_content_paging_bar:showPage"),lastPageNumber=getLastPageNumber(root),isSamePage=pageNumber==getActivePageNumber(root),limit=function(root){return parseInt(root.attr("data-items-per-page"),10)}(root),offset=(pageNumber-1)*limit;if(!isSamePage){root.find(SELECTORS_PAGE_ITEM).removeClass("active").removeAttr("aria-current");var page=getPageByNumber(root,pageNumber);page.addClass("active"),page.attr("aria-current",!0),setActivePageNumber(root,pageNumber),adjustPagingBarSize(root)}lastPageNumber&&pageNumber>=lastPageNumber?disableNextControlButtons(root):enableNextControlButtons(root),pageNumber>1?enablePreviousControlButtons(root):disablePreviousControlButtons(root),function(root){var pageAriaLabelComponents=function(root){return root.attr("data-aria-label-components-pagination-item").split(",").map((function(component){return component.trim()}))}(root),activePageAriaLabelComponents=function(root){return root.attr("data-aria-label-components-pagination-active-item").split(",").map((function(component){return component.trim()}))}(root),activePageNumber=getActivePageNumber(root),pageItems=root.find(SELECTORS_PAGE_ITEM),stringRequests=pageItems.toArray().map((function(index,page){page=$(page);var pageNumber=getPageNumber(root,page);return pageNumber===activePageNumber?{key:activePageAriaLabelComponents[0],component:activePageAriaLabelComponents[1],param:pageNumber}:{key:pageAriaLabelComponents[0],component:pageAriaLabelComponents[1],param:pageNumber}}));Str.get_strings(stringRequests).then((function(strings){return pageItems.each((function(index,page){page=$(page);var string=strings[index];page.attr("aria-label",string),page.find(SELECTORS_PAGE_LINK).attr("aria-label",string)})),strings})).catch((function(){}))}(root),PubSub.publish(id+PagedContentEvents.SHOW_PAGES,[{pageNumber:pageNumber,limit:limit,offset:offset}]),pendingPromise.resolve()};return{init:function(root,id){var pages=(root=$(root)).find(SELECTORS_PAGE);if(function(root,items){var lastPageNumber=0;setActivePageNumber(root,0),items.each((function(index,item){var pageNumber=index+1;(item=$(item)).attr("data-page-number",pageNumber),lastPageNumber++,item.hasClass("active")&&setActivePageNumber(root,pageNumber)})),setLastPageNumber(root,lastPageNumber)}(root,pages),function(root,id){var ignoreControlWhileLoading=root.attr("data-ignore-control-while-loading"),loading=!1;""==ignoreControlWhileLoading&&(ignoreControlWhileLoading=!0),CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_PAGE_ITEM,(function(e,data){if(data.originalEvent.preventDefault(),data.originalEvent.stopPropagation(),!ignoreControlWhileLoading||!loading){var page=$(e.target).closest(SELECTORS_PAGE_ITEM);if(!page.hasClass("disabled")){var pageNumber=getPageNumber(root,page);showPage(root,pageNumber,id),loading=!0}}})),PubSub.subscribe(id+PagedContentEvents.ALL_ITEMS_LOADED,(function(pageNumber){loading=!1;var currentLastPage=getLastPageNumber(root);(!currentLastPage||pageNumber<currentLastPage)&&setLastPageNumber(root,pageNumber),1===pageNumber&&root.attr("data-hide-control-on-single-page")?(hide(root),disableNextControlButtons(root),disablePreviousControlButtons(root)):(show(root),disableNextControlButtons(root))})),PubSub.subscribe(id+PagedContentEvents.PAGES_SHOWN,(function(){loading=!1})),PubSub.subscribe(id+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT,(function(limit){!function(root,limit){root.attr("data-items-per-page",limit)}(root,limit),setLastPageNumber(root,0),setActivePageNumber(root,0),show(root),showPage(root,1,id)}))}(root,id),function(root){var number=getActivePageNumber(root);return!isNaN(number)&&0!=number}(root)){var activePageNumber=getActivePageNumber(root);getPageByNumber(root,activePageNumber).click(),1==activePageNumber&&disablePreviousControlButtons(root)}else(function(root){return root.find(SELECTORS_NEXT_BUTTON)})(root).click();adjustPagingBarSize(root)},disableNextControlButtons:disableNextControlButtons,enableNextControlButtons:enableNextControlButtons,disablePreviousControlButtons:disablePreviousControlButtons,enablePreviousControlButtons:enablePreviousControlButtons,showPage:showPage,rootSelector:'[data-region="paging-bar"]'}})); /** * A helper to manage pendingJS checks. * * @module core/pending * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("core/pending",["jquery"],(function($){var request=function(pendingKey){var pendingPromise=$.Deferred();return pendingKey=pendingKey||{},M.util.js_pending(pendingKey),pendingPromise.then((function(){return M.util.js_complete(pendingKey)})).catch(),pendingPromise};return request.prototype.constructor=request,request})); define("core/str",["exports","jquery","core/ajax","core/localstorage"],(function(_exports,_jquery,_ajax,_localstorage){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Fetch and return language strings. * * @module core/str * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @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),_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=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_"),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=>{const defaultLang=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_");strings.forEach((_ref2=>{let{key:key,component:component,value:value,lang:lang=defaultLang}=_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())}))}})); /** * Template renderer for Moodle. Load and render Moodle templates with Mustache. * * @module core/templates * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @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:$("html").attr("lang").replace(/-/g,"_")}});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=$("<script>").attr("type","text/javascript").html(source);$("head").append(newscript)}},domReplace=function(element,newHTML,newJS,replaceChildNodes){var replaceNode=$(element);if(replaceNode.length){var newNodes=$(newHTML);return replaceChildNodes?(new Y.NodeList(replaceNode.children().get()).destroy(!0),replaceNode.empty(),replaceNode.append(newNodes)):(new Y.NodeList(replaceNode.get()).destroy(!0),replaceNode.replaceWith(newNodes)),runTemplateJS(newJS),filterEvents.notifyFilterContentUpdated(newNodes),newNodes.get()}return[]};Renderer.prototype.scanForPartials=function(templateSource){var tokens=mustache.parse(templateSource),partials=[],findPartial=function(tokens,partials){var i,token;for(i=0;i<tokens.length;i++)">"!=(token=tokens[i])[0]&&"<"!=token[0]||partials.push(token[1]),token.length>4&&findPartial(token[4],partials)};return findPartial(tokens,partials),partials},Renderer.prototype.cachePartials=function(templateName,parentage){var searchKey=this.currentThemeName+"/"+templateName;return searchKey in cachePartialPromises||(parentage=parentage||[searchKey],cachePartialPromises[searchKey]=$.Deferred(),this.getTemplate(templateName).then(function(templateSource){var fetchThemAll=this.scanForPartials(templateSource).filter(function(partialName){return!(parentage.indexOf(this.currentThemeName+"/"+partialName)>=0)&&partialName!=templateName}.bind(this)).map(function(partialName){return parentage.push(this.currentThemeName+"/"+partialName),this.cachePartials(partialName,parentage)}.bind(this));return $.when.apply($,fetchThemAll).then((function(){return cachePartialPromises[searchKey].resolve(templateSource)}))}.bind(this)).catch(cachePartialPromises[searchKey].reject)),cachePartialPromises[searchKey]},Renderer.prototype.render=function(templateName,context,themeName){void 0===themeName&&(themeName=config.theme),this.currentThemeName=themeName;var modulename=config.iconsystemmodule,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.iconsystem)})),ready.then(function(){return this.cachePartials(templateName)}.bind(this)).then(function(templateSource){return this.doRender(templateSource,context,themeName)}.bind(this))};return{render:function(templateName,context,themeName){return(new Renderer).render(templateName,context,themeName)},prefetchTemplates:function(templateNames,themeName){var renderer=new Renderer;return void 0===themeName&&(themeName=config.theme),renderer.prefetchTemplates(templateNames,themeName)},renderForPromise:function(templateName,context,themeName){return(new Renderer).render(templateName,context,themeName).then((function(html,js){return{html:html,js:js}}))},renderPix:function(key,component,title){return(new Renderer).renderIcon(key,getNormalisedComponent(component),title)},runTemplateJS:runTemplateJS,replaceNodeContents:function(element,newHTML,newJS){return domReplace(element,newHTML,newJS,!0)},replaceNode:function(element,newHTML,newJS){return domReplace(element,newHTML,newJS,!1)},prependNodeContents:function(element,html,js){return function(element,html,js){var node=$(element);if(node.length){var newContent=$(html);return node.prepend(newContent),runTemplateJS(js),filterEvents.notifyFilterContentUpdated(node),newContent.get()}return[]}(element,html,js)},appendNodeContents:function(element,html,js){return function(element,html,js){var node=$(element);if(node.length){var newContent=$(html);return node.append(newContent),runTemplateJS(js),filterEvents.notifyFilterContentUpdated(node),newContent.get()}return[]}(element,html,js)}}})); define("core/userfeedback",["exports","core/ajax","core/notification"],(function(_exports,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Handle clicking on action links of the feedback alert. * * @module core/cta_feedback * @copyright 2020 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.registerEventListeners=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);const Selectors={regions:{root:'[data-region="core/userfeedback"]'},actions:{}};Selectors.actions.give="".concat(Selectors.regions.root,' [data-action="give"]'),Selectors.actions.remind="".concat(Selectors.regions.root,' [data-action="remind"]');_exports.registerEventListeners=()=>{document.addEventListener("click",(e=>{const giveAction=e.target.closest(Selectors.actions.give);if(giveAction){if(e.preventDefault(),!window.open(giveAction.href))throw new Error("Unable to open popup");Promise.resolve(giveAction).then(hideRoot).then(recordAction).catch(_notification.default.exception)}const remindAction=e.target.closest(Selectors.actions.remind);remindAction&&(e.preventDefault(),Promise.resolve(remindAction).then(hideRoot).then(recordAction).catch(_notification.default.exception))}))};const recordAction=clickedItem=>clickedItem.dataset.record?_ajax.default.call([{methodname:"core_create_userfeedback_action_record",args:{action:clickedItem.dataset.action,contextid:M.cfg.contextid}}])[0]:Promise.resolve(),hideRoot=clickedItem=>(clickedItem.dataset.hide&&clickedItem.closest(Selectors.regions.root).remove(),clickedItem)})); define("core/utility",["core/str","core/pending","core/toast","core/notification"],(function(Str,_pending,_toast,_notification){var obj;Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}let registered=!1;const getModalString=(dataset,type,field)=>dataset["".concat(type).concat(field,"Str")]?Str.get_string.apply(null,JSON.parse(dataset["".concat(type).concat(field,"Str")])):Promise.resolve(dataset["".concat(type).concat(field)]),displayConfirmation=(source,type)=>(0,_notification.saveCancelPromise)(getModalString(source.dataset,type,"Title"),getModalString(source.dataset,type,"Content"),getModalString(source.dataset,type,"YesButton")).then((()=>{if("true"===source.dataset["".concat(type,"Toast")]){const stringForToast=getModalString(source.dataset,type,"ToastConfirmation");"string"==typeof stringForToast?(0,_toast.add)(stringForToast):stringForToast.then((str=>(0,_toast.add)(str))).catch((e=>(0,_notification.exception)(e)))}window.location.href=source.dataset["".concat(type,"Destination")]})).catch((()=>{}));registered||((()=>{document.addEventListener("click",(e=>{const confirmRequest=e.target.closest('[data-confirmation="modal"]');confirmRequest&&(e.preventDefault(),displayConfirmation(confirmRequest,"confirmation"));const modalConfirmation=e.target.closest('[data-modal="confirmation"]');modalConfirmation&&(e.preventDefault(),displayConfirmation(modalConfirmation,"modal"));const alertRequest=e.target.closest('[data-modal="alert"]');alertRequest&&(e.preventDefault(),(async(title,content)=>{const pendingPromise=new _pending.default("core/confirm:alert"),ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"]));ModalFactory.create({type:ModalFactory.types.ALERT,title:title,body:content,removeOnClose:!0}).then((function(modal){return modal.show(),pendingPromise.resolve(),modal}))})(getModalString(alertRequest.dataset,"modal","Title"),getModalString(alertRequest.dataset,"modal","Content")))}))})(),registered=!0)})); define("core/utils",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.throttle=_exports.debounce=void 0;_exports.throttle=(func,wait)=>{let onCooldown=!1,runAgain=null;const run=function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];runAgain=null!==runAgain,onCooldown||(func.apply(this,args),onCooldown=!0,setTimeout((()=>{const recurse=runAgain;onCooldown=!1,runAgain=null,recurse&&run(args)}),wait))};return run};_exports.debounce=(func,wait)=>{let timeout=null;return function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];clearTimeout(timeout),timeout=setTimeout((()=>{func.apply(this,args)}),wait)}}})); define("core_availability/availability_more",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Show more action for availablity information. * * @module core_availability/availability_more * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const Selectors_regions={availability:'[data-region="availability-multiple"]'},Selectors_actions={showmorelink:'[data-action="showmore"]'},Selectors_classes={hidden:"d-none",visible:"d-block"},showMoreHandler=event=>{const triggerElement=event.target.closest(Selectors_actions.showmorelink);if(null===triggerElement)return;const container=triggerElement.closest(Selectors_regions.availability);container.querySelectorAll("."+Selectors_classes.hidden).forEach((function(node){node.classList.remove(Selectors_classes.hidden)})),container.querySelectorAll("."+Selectors_classes.visible).forEach((function(node){node.classList.remove(Selectors_classes.visible),node.classList.add(Selectors_classes.hidden)})),event.preventDefault()};_exports.init=()=>{const body=document.querySelector("body");body.dataset.showmoreactive||(document.addEventListener("click",showMoreHandler),body.dataset.showmoreactive=1)}})); /** * This module updates the UI during an asynchronous * backup or restore process. * * @module core_backup/async_backup * @copyright 2018 Matt Porritt <mattp@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.7 */ define("core_backup/async_backup",["jquery","core/ajax","core/str","core/notification","core/templates"],(function($,ajax,Str,notification,Templates){var backupid,contextid,restoreurl,typeid,backupintervalid,allbackupintervalid,allcopyintervalid,Asyncbackup={},checkdelay=15e3;function updateElement(backupid,type,percentage){var percentagewidth=Math.round(percentage)+"%",elementbar=document.querySelectorAll("[data-"+type+"id="+CSS.escape(backupid)+"]")[0],percentagetext=percentage.toFixed(2)+"%";elementbar.setAttribute("aria-valuenow",percentagewidth),elementbar.style.width=percentagewidth,elementbar.innerHTML=percentagetext}function updateInterval(intervalid,callback,value){return clearInterval(intervalid),setInterval(callback,value)}function updateProgressAll(progress){progress.forEach((function(element){var percentage=100*element.progress,backupid=element.backupid,type=element.operation,elementbar=document.querySelectorAll("[data-"+type+"id="+CSS.escape(backupid)+"]")[0];800==element.status?(elementbar.classList.add("bg-success"),updateElement(backupid,type,percentage)):900==element.status?(elementbar.classList.add("bg-danger"),elementbar.classList.add("complete"),elementbar.classList.remove("bg-success"),updateElement(backupid,type,100)):1e3==element.status&&(elementbar.classList.add("bg-success"),elementbar.classList.add("complete"),updateElement(backupid,type,100),"backup"==type?function(backupid){var statuscell=$("#"+backupid+"_bar").parent().parent(),tablerow=statuscell.parent(),cellsiblings=statuscell.siblings(),timecell=cellsiblings[1],timevalue=$(timecell).text(),filenamecell=cellsiblings[0],filename=$(filenamecell).text();ajax.call([{methodname:"core_backup_get_async_backup_links_backup",args:{filename:filename,contextid:contextid,backupid:backupid}}])[0].done((function(response){var context={filename:filename,time:timevalue,size:response.filesize,fileurl:response.fileurl,restoreurl:response.restoreurl};Templates.render("core/async_backup_progress_row",context).then((function(html,js){Templates.replaceNodeContents(tablerow,html,js)})).fail((function(){notification.exception(new Error("Failed to load table row"))}))}))}(backupid):function(backupid){var statuscell=$("#"+backupid+"_bar").parent().parent(),tablerow=statuscell.parent(),cellsiblings=statuscell.siblings(),coursecell=cellsiblings[0],timecell=cellsiblings[1],timevalue=$(timecell).text();ajax.call([{methodname:"core_backup_get_async_backup_links_restore",args:{backupid:backupid,contextid:contextid}}])[0].done((function(response){var context={resourcename:$(coursecell).text(),restoreurl:response.restoreurl,time:timevalue};Templates.render("core/async_restore_progress_row",context).then((function(html,js){Templates.replaceNodeContents(tablerow,html,js)})).fail((function(){notification.exception(new Error("Failed to load table row"))}))}))}(backupid))}))}function updateProgressCopy(progress){progress.forEach((function(element){var percentage=100*element.progress,backupid=element.backupid,type=element.operation,elementbar=document.querySelectorAll("[data-"+type+"id="+CSS.escape(backupid)+"]")[0];if("restore"==type){let restorecell=elementbar.closest("tr").children[3];Str.get_string("restore").then((function(content){restorecell.innerHTML=content})).catch((function(){notification.exception(new Error("Failed to load string: restore"))}))}800==element.status?(elementbar.classList.add("bg-success"),updateElement(backupid,type,percentage)):900==element.status?(elementbar.classList.add("bg-danger"),elementbar.classList.add("complete"),elementbar.classList.remove("bg-success"),updateElement(backupid,type,100)):1e3==element.status&&"restore"==type&&(elementbar.classList.add("bg-success"),elementbar.classList.add("complete"),updateElement(backupid,type,100),function(backupid){var elementbar=document.querySelectorAll("[data-restoreid="+CSS.escape(backupid)+"]")[0],restorecourse=elementbar.closest("tr").children[1],coursename=restorecourse.innerHTML,courselink=document.createElement("a"),elementbarparent=elementbar.closest("td"),operation=elementbarparent.previousElementSibling;Str.get_string("complete").then((function(content){operation.innerHTML=content})).catch((function(){notification.exception(new Error("Failed to load string: complete"))})),Templates.render("core/async_copy_complete_cell",{}).then((function(html,js){Templates.replaceNodeContents(elementbarparent,html,js)})).fail((function(){notification.exception(new Error("Failed to load table cell"))})),ajax.call([{methodname:"core_backup_get_async_backup_links_restore",args:{backupid:backupid,contextid:0}}])[0].done((function(response){courselink.setAttribute("href",response.restoreurl),courselink.innerHTML=coursename,restorecourse.innerHTML=null,restorecourse.appendChild(courselink)})).fail((function(){notification.exception(new Error("Failed to update table row"))}))}(backupid))}))}function getBackupProgress(){ajax.call([{methodname:"core_backup_get_async_backup_progress",args:{backupids:[backupid],contextid:contextid}}],!0,!0,!1,2e3)[0].done((function(response){!function(progress){var stringRequests,percentage=100*progress.progress,type="backup",elementbar=document.querySelectorAll("[data-backupid="+CSS.escape(backupid)+"]")[0],elementstatus=$("#"+backupid+"_status"),elementdetail=$("#"+backupid+"_detail"),elementbutton=$("#"+backupid+"_button");if(800==progress.status){elementbar.classList.add("bg-success"),updateElement(backupid,type,percentage);var strProcessing="async"+typeid+"processing";Str.get_string(strProcessing,"backup").then((function(title){elementstatus.text(title)})).catch((function(){notification.exception(new Error("Failed to load string: backup "+strProcessing))}))}else if(900==progress.status)elementbar.classList.add("bg-danger"),elementbar.classList.remove("bg-success"),updateElement(backupid,type,100),stringRequests=[{key:"async"+typeid+"error",component:"backup"},{key:"async"+typeid+"errordetail",component:"backup"}],Str.get_strings(stringRequests).then((function(strings){elementstatus.text(strings[0]),elementdetail.text(strings[1])})).catch((function(){notification.exception(new Error("Failed to load string"))})),$(".backup_progress").children("span").removeClass("backup_stage_current"),$(".backup_progress").children("span").last().addClass("backup_stage_current"),clearInterval(backupintervalid);else if(1e3==progress.status){elementbar.classList.add("bg-success"),updateElement(backupid,type,100);var strComplete="async"+typeid+"complete";Str.get_string(strComplete,"backup").then((function(title){elementstatus.text(title)})).catch((function(){notification.exception(new Error("Failed to load string: backup "+strComplete))})),"restore"==typeid?ajax.call([{methodname:"core_backup_get_async_backup_links_restore",args:{backupid:backupid,contextid:contextid}}])[0].done((function(response){var strButton="async"+typeid+"completebutton",stringRequests=[{key:"async"+typeid+"completedetail",component:"backup",param:response.restoreurl},{key:strButton,component:"backup"}];Str.get_strings(stringRequests).then((function(strings){elementdetail.html(strings[0]),elementbutton.text(strings[1]),elementbutton.attr("href",response.restoreurl)})).catch((function(){notification.exception(new Error("Failed to load string"))}))})):(stringRequests=[{key:"async"+typeid+"completedetail",component:"backup",param:restoreurl},{key:"async"+typeid+"completebutton",component:"backup"}],Str.get_strings(stringRequests).then((function(strings){elementdetail.html(strings[0]),elementbutton.text(strings[1]),elementbutton.attr("href",restoreurl)})).catch((function(){notification.exception(new Error("Failed to load string"))}))),$(".backup_progress").children("span").removeClass("backup_stage_current"),$(".backup_progress").children("span").last().addClass("backup_stage_current"),clearInterval(backupintervalid)}}(response[0]),checkdelay=15e3,backupintervalid=updateInterval(backupintervalid,getBackupProgress,15e3)})).fail((function(){backupintervalid=updateInterval(backupintervalid,getBackupProgress,checkdelay*=1.5)}))}function getAllBackupProgress(){var backupids=[];$(".progress").find(".progress-bar").not(".complete").each((function(){backupids.push(this.id.substring(0,32))})),backupids.length>0?ajax.call([{methodname:"core_backup_get_async_backup_progress",args:{backupids:backupids,contextid:contextid}}],!0,!0,!1,2e3)[0].done((function(response){updateProgressAll(response),checkdelay=15e3,allbackupintervalid=updateInterval(allbackupintervalid,getAllBackupProgress,15e3)})).fail((function(){allbackupintervalid=updateInterval(allbackupintervalid,getAllBackupProgress,checkdelay*=1.5)})):clearInterval(allbackupintervalid)}function getAllCopyProgress(){var copyids=[];$(".progress").find(".progress-bar[data-operation][data-backupid][data-restoreid]").not(".complete").each((function(){let progressvars={backupid:this.dataset.backupid,restoreid:this.dataset.restoreid,operation:this.dataset.operation};copyids.push(progressvars)})),copyids.length>0?ajax.call([{methodname:"core_backup_get_copy_progress",args:{copies:copyids}}],!0,!0,!1,2e3)[0].done((function(response){updateProgressCopy(response),checkdelay=15e3,allcopyintervalid=updateInterval(allcopyintervalid,getAllCopyProgress,15e3)})).fail((function(){allcopyintervalid=updateInterval(allcopyintervalid,getAllCopyProgress,checkdelay*=1.5)})):clearInterval(allcopyintervalid)}return Asyncbackup.asyncBackupAllStatus=function(context){contextid=context,allbackupintervalid=setInterval(getAllBackupProgress,checkdelay)},Asyncbackup.asyncCopyAllStatus=function(){allcopyintervalid=setInterval(getAllCopyProgress,checkdelay)},Asyncbackup.asyncBackupStatus=function(backup,context,restore,type){backupid=backup,contextid=context,restoreurl=restore,typeid="backup"==type?"backup":"restore",$(".backup_progress").children("a").removeAttr("href"),backupintervalid=setInterval(getBackupProgress,checkdelay)},Asyncbackup})); define("core_badges/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var name,value,_default={actions:{deletebackpack:(name="action",value="deletebackpack","[data-".concat(name,'="').concat(value,'"]'))},elements:{clearsearch:".input-group-append .clear-icon",main:"#backpacklist",backpackurl:"[data-backpackurl]"}};return _exports.default=_default,_exports.default})); define("core_badges/backpackactions",["exports","jquery","core_badges/selectors","core/str","core/pending","core/modal_factory","core/modal_events","core/config"],(function(_exports,_jquery,_selectors,_str,_pending,_modal_factory,_modal_events,_config){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Action methods related to backpacks. * * @module core_badges/backpackactions * @copyright 2020 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_selectors=_interopRequireDefault(_selectors),_pending=_interopRequireDefault(_pending),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_config=_interopRequireDefault(_config);_exports.init=()=>{const pendingPromise=new _pending.default,root=(0,_jquery.default)(_selectors.default.elements.main);registerListenerEvents(root),pendingPromise.resolve()};const registerListenerEvents=root=>{root.on("click",_selectors.default.actions.deletebackpack,(async e=>{e.preventDefault();const link=(0,_jquery.default)(e.currentTarget),modal=await buildModal(link);displayModal(modal,link)}))},buildModal=async link=>{const backpackurl=link.closest(_selectors.default.elements.backpackurl).attr("data-backpackurl");return _modal_factory.default.create({title:await(0,_str.get_string)("delexternalbackpack","core_badges"),body:await(0,_str.get_string)("delexternalbackpackconfirm","core_badges",backpackurl),type:_modal_factory.default.types.SAVE_CANCEL})},displayModal=async(modal,link)=>{modal.setSaveButtonText(await(0,_str.get_string)("delete","core")),modal.getRoot().on(_modal_events.default.save,(function(){window.location.href=link.attr("href")+"&sesskey="+_config.default.sesskey+"&confirm=1"})),modal.getRoot().on(_modal_events.default.hidden,(function(){modal.destroy()})),modal.show()}})); define("core_block/events",["exports","core/event_dispatcher"],(function(_exports,_event_dispatcher){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyBlockContentUpdated=_exports.eventTypes=void 0; /** * Javascript events for the `core_block` subsystem. * * @module core_block/events * @copyright 2021 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 * * @example <caption>Example of listening to a block event.</caption> * import {eventTypes as blockEventTypes} from 'core_block/events'; * * document.addEventListener(blockEventTypes.blockContentUpdated, e => { * window.console.log(e.target); // The HTMLElement relating to the block whose content was updated. * window.console.log(e.detail.instanceId); // The instanceId of the block that was updated. * }); */ const eventTypes={blockContentUpdated:"core_block/contentUpdated"};_exports.eventTypes=eventTypes;_exports.notifyBlockContentUpdated=element=>(0,_event_dispatcher.dispatchEvent)(eventTypes.blockContentUpdated,{instanceId:element.dataset.instanceId},element);let legacyEventsRegistered=!1;legacyEventsRegistered||(Y.use("event","moodle-core-event",(Y=>{document.addEventListener(eventTypes.blockContentUpdated,(e=>{Y.Global.fire(M.core.event.BLOCK_CONTENT_UPDATED,{instanceid:e.detail.instanceId})}))})),legacyEventsRegistered=!0)})); /** * This module is the highest level module for the calendar. It is * responsible for initialising all of the components required for * the calendar to run. It also coordinates the interaction between * components by listening for and responding to different events * triggered within the calendar UI. * * @module core_calendar/calendar * @copyright 2017 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/calendar",["jquery","core/ajax","core/str","core/templates","core/notification","core/custom_interaction_events","core/modal_events","core/modal_factory","core_calendar/modal_event_form","core_calendar/summary_modal","core_calendar/repository","core_calendar/events","core_calendar/view_manager","core_calendar/crud","core_calendar/selectors","core/config"],(function($,Ajax,Str,Templates,Notification,CustomEvents,ModalEvents,ModalFactory,ModalEventForm,SummaryModal,CalendarRepository,CalendarEvents,CalendarViewManager,CalendarCrud,CalendarSelectors,Config){var SELECTORS_DAY="[data-region='day']",SELECTORS_DAY_CONTENT="[data-region='day-content']",SELECTORS_LOADING_ICON=".loading-icon",SELECTORS_VIEW_DAY_LINK="[data-action='view-day-link']",SELECTORS_CALENDAR_MONTH_WRAPPER=".calendarwrapper",handleMoveEvent=function(e,eventId,originElement,destinationElement){var originTimestamp=null,destinationTimestamp=destinationElement.attr("data-day-timestamp");originElement&&(originTimestamp=originElement.attr("data-day-timestamp")),originElement&&originTimestamp==destinationTimestamp||Templates.render("core/loading",{}).then((function(html,js){destinationElement.find(SELECTORS_DAY_CONTENT).addClass("hidden"),Templates.appendNodeContents(destinationElement,html,js),originElement&&(originElement.find(SELECTORS_DAY_CONTENT).addClass("hidden"),Templates.appendNodeContents(originElement,html,js))})).then((function(){return CalendarRepository.updateEventStartDay(eventId,destinationTimestamp)})).then((function(){$("body").trigger(CalendarEvents.eventMoved,[eventId,originElement,destinationElement])})).always((function(){var destinationLoadingElement=destinationElement.find(SELECTORS_LOADING_ICON);if(destinationElement.find(SELECTORS_DAY_CONTENT).removeClass("hidden"),Templates.replaceNode(destinationLoadingElement,"",""),originElement){var originLoadingElement=originElement.find(SELECTORS_LOADING_ICON);originElement.find(SELECTORS_DAY_CONTENT).removeClass("hidden"),Templates.replaceNode(originLoadingElement,"","")}})).fail(Notification.exception)},registerEventListeners=function(root){const viewingFullCalendar=document.getElementById(CalendarSelectors.fullCalendarView);root.on("click",SELECTORS_VIEW_DAY_LINK,(function(e){var dayLink=$(e.target).closest(SELECTORS_VIEW_DAY_LINK),year=dayLink.data("year"),month=dayLink.data("month"),day=dayLink.data("day"),courseId=dayLink.data("courseid"),categoryId=dayLink.data("categoryid");const url="?view=day&time="+dayLink.data("timestamp");viewingFullCalendar?CalendarViewManager.refreshDayContent(root,year,month,day,courseId,categoryId,root,"core_calendar/calendar_day").then((function(){return e.preventDefault(),CalendarViewManager.updateUrl(url)})).fail(Notification.exception):window.location.assign(Config.wwwroot+"/calendar/view.php"+url)})),root.on("change",CalendarSelectors.elements.courseSelector,(function(){var courseId=$(this).val();CalendarViewManager.reloadCurrentMonth(root,courseId,null).then((function(){return root.find(CalendarSelectors.elements.courseSelector).val(courseId)})).fail(Notification.exception)}));var eventFormPromise=CalendarCrud.registerEventFormModal(root),contextId=$(SELECTORS_CALENDAR_MONTH_WRAPPER).data("context-id");!function(root,eventFormModalPromise){var body=$("body");body.on(CalendarEvents.created,(function(){CalendarViewManager.reloadCurrentMonth(root)})),body.on(CalendarEvents.deleted,(function(){CalendarViewManager.reloadCurrentMonth(root)})),body.on(CalendarEvents.updated,(function(){CalendarViewManager.reloadCurrentMonth(root)})),body.on(CalendarEvents.editActionEvent,(function(e,url){window.location.assign(url)})),body.on(CalendarEvents.moveEvent,handleMoveEvent),body.on(CalendarEvents.eventMoved,(function(){CalendarViewManager.reloadCurrentMonth(root)})),CalendarCrud.registerEditListeners(root,eventFormModalPromise)}(root,eventFormPromise),contextId&&root.on("click",SELECTORS_DAY,(function(e){var target=$(e.target);const displayingSmallBlockCalendar="side-pre"===root.parents("aside").data("blockregion");if(!viewingFullCalendar&&displayingSmallBlockCalendar){const url="?view=day&time="+target.closest(SELECTORS_DAY).data("day-timestamp");window.location.assign(Config.wwwroot+"/calendar/view.php"+url)}else{if(!target.closest(SELECTORS_VIEW_DAY_LINK).length){var startTime=$(this).attr("data-new-event-timestamp");eventFormPromise.then((function(modal){var wrapper=target.closest(CalendarSelectors.wrapper);modal.setCourseId(wrapper.data("courseid"));var categoryId=wrapper.data("categoryid");void 0!==categoryId&&modal.setCategoryId(categoryId),modal.setContextId(wrapper.data("contextId")),modal.setStartTime(startTime),modal.show()})).fail(Notification.exception)}}e.preventDefault()}))};return{init:function(root){root=$(root),CalendarViewManager.init(root),registerEventListeners(root)}}})); /** * This module is responsible for the calendar filter. * * @module core_calendar/calendar_filter * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/calendar_filter",["jquery","core_calendar/selectors","core_calendar/events","core/str","core/templates"],(function($,CalendarSelectors,CalendarEvents,Str,Templates){var toggleFilter=function(target){var data=getFilterData(target);return data.hidden=!data.hidden,M.util.js_pending("core_calendar/calendar_filter:toggleFilter"),Str.get_string("eventtype"+data.eventtype,"calendar").then((function(nameStr){return data.name=nameStr,data.icon=!0,data.key="i/"+data.eventtype+"event",data.component="core",data})).then((function(context){return Templates.render("core_calendar/event_filter_key",context)})).then((function(html,js){return Templates.replaceNode(target,html,js)})).then((function(){fireFilterChangedEvent(data),M.util.js_complete("core_calendar/calendar_filter:toggleFilter")}))},fireFilterChangedEvent=function(data){M.util.js_pending("month-mini-filterChanged"),$("body").trigger(CalendarEvents.filterChanged,{type:data.eventtype,hidden:data.hidden}),M.util.js_complete("month-mini-filterChanged")},getFilterData=function(target){return{eventtype:target.data("eventtype"),hidden:target.data("eventtype-hidden")}};return{init:function(root){!function(root){root.on("click",CalendarSelectors.eventFilterItem,(function(e){var target=$(e.currentTarget);toggleFilter(target),e.preventDefault()})),$("body").on(CalendarEvents.viewUpdated,(function(){root.find(CalendarSelectors.eventFilterItem).each((function(i,filter){if((filter=$(filter)).data("eventtype-hidden")){var data=getFilterData(filter);fireFilterChangedEvent(data)}}))}))}(root=$(root))}}})); /** * This module is the highest level module for the calendar. It is * responsible for initialising all of the components required for * the calendar to run. It also coordinates the interaction between * components by listening for and responding to different events * triggered within the calendar UI. * * @module core_calendar/calendar_mini * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/calendar_mini",["jquery","core_calendar/selectors","core_calendar/events","core_calendar/view_manager"],(function($,CalendarSelectors,CalendarEvents,CalendarViewManager){var reloadMonth=function(e){var root=e.data,body=$("body"),namespace="."+root.attr("id");root.is(":visible")?CalendarViewManager.reloadCurrentMonth(root):(body.off(CalendarEvents.created+namespace),body.off(CalendarEvents.deleted+namespace),body.off(CalendarEvents.updated+namespace),body.off(CalendarEvents.eventMoved+namespace))};return{init:function(root,loadOnInit){root=$(root),CalendarViewManager.init(root),function(root){$("body").on(CalendarEvents.filterChanged,(function(e,data){root.find(CalendarSelectors.eventType[data.type]).toggleClass("calendar_event_"+data.type,!data.hidden)}));var namespace="."+root.attr("id");$("body").on("change"+namespace,CalendarSelectors.elements.courseSelector,(function(){if(root.is(":visible")){var courseId=$(this).val();CalendarViewManager.reloadCurrentMonth(root,courseId,null)}else $("body").off("change"+namespace)}))}(root),function(root){var body=$("body"),namespace="."+root.attr("id");body.on(CalendarEvents.created+namespace,root,reloadMonth),body.on(CalendarEvents.deleted+namespace,root,reloadMonth),body.on(CalendarEvents.updated+namespace,root,reloadMonth),body.on(CalendarEvents.eventMoved+namespace,root,reloadMonth)}(root),loadOnInit&&CalendarViewManager.reloadCurrentMonth(root)}}})); /** * This module handles display of multiple mini calendars in a view, and * movement through them. * * @deprecated since 4.0 MDL-72810. * @todo MDL-73117 This will be deleted in Moodle 4.4. * @module core_calendar/calendar_threemonth * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/calendar_threemonth",["jquery","core/notification","core_calendar/selectors","core_calendar/events","core/templates","core_calendar/view_manager"],(function($,Notification,CalendarSelectors,CalendarEvents,Templates,CalendarViewManager){return{init:function(root){!function(root){$("body").on([CalendarEvents.monthChanged,CalendarEvents.dayChanged].join(" "),(function(e,year,month,courseId,categoryId){root.queue((function(next){return processRequest(e,year,month,courseId,categoryId).then((function(){return next()})).fail(Notification.exception)}))}));var processRequest=function(e,year,month,courseId,categoryId){var newParent=root.find('[data-year="'+year+'"][data-month="'+month+'"]').closest(CalendarSelectors.calendarPeriods.month),allMonths=root.find(CalendarSelectors.calendarPeriods.month),previousMonth=$(allMonths[0]),nextMonth=$(allMonths[2]),placeHolder=$("<span>");placeHolder.attr("data-template","core_calendar/threemonth_month"),placeHolder.attr("data-includenavigation",!1),placeHolder.attr("data-mini",!0);var requestYear,requestMonth,oldMonth,placeHolderContainer=$("<div>");if(placeHolderContainer.hide(),placeHolderContainer.append(placeHolder),newParent.is(previousMonth))placeHolderContainer.insertBefore(previousMonth),requestYear=previousMonth.data("previousYear"),requestMonth=previousMonth.data("previousMonth"),oldMonth=nextMonth;else{if(!newParent.is(nextMonth))return $.Deferred().resolve();placeHolderContainer.insertAfter(nextMonth),requestYear=nextMonth.data("nextYear"),requestMonth=nextMonth.data("nextMonth"),oldMonth=previousMonth}return CalendarViewManager.refreshMonthContent(placeHolder,requestYear,requestMonth,courseId,categoryId,placeHolder).then((function(){var slideUpPromise=$.Deferred(),slideDownPromise=$.Deferred();return oldMonth.slideUp("fast",(function(){$(this).remove(),slideUpPromise.resolve()})),placeHolderContainer.slideDown("fast",(function(){slideDownPromise.resolve()})),$.when(slideUpPromise,slideDownPromise)}))};root.on("click",CalendarSelectors.links.miniDayLink,(function(e){var miniDayLink=$(e.target),year=miniDayLink.data("year"),month=miniDayLink.data("month"),day=miniDayLink.text(),courseId=miniDayLink.data("courseid"),categoryId=miniDayLink.data("categoryid"),calendarRoot=$("body").find(CalendarSelectors.calendarMain);CalendarViewManager.refreshDayContent(calendarRoot,year,month,day,courseId,categoryId,calendarRoot.find('[id^="calendar-"][data-template^="core_calendar/"]'),"core_calendar/calendar_day"),e.preventDefault(),CalendarViewManager.updateUrl("?view=day")}))}(root=$(root))}}})); /** * A javascript module to store calendar drag and drop data. * * This module is unfortunately required because of the limitations * of the HTML5 drag and drop API and it's ability to provide data * between the different stages of the drag/drop lifecycle. * * @module core_calendar/drag_drop_data_store * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/drag_drop_data_store",[],(function(){var eventId=null,durationDays=null,minTimestart=null,maxTimestart=null,minError=null,maxError=null,setEventId=function(id){eventId=id},setDurationDays=function(days){durationDays=days},setMinTimestart=function(timestamp){minTimestart=timestamp},setMaxTimestart=function(timestamp){maxTimestart=timestamp},setMinError=function(message){minError=message},setMaxError=function(message){maxError=message};return{setEventId:setEventId,getEventId:function(){return eventId},hasEventId:function(){return null!==eventId},setDurationDays:setDurationDays,getDurationDays:function(){return durationDays},setMinTimestart:setMinTimestart,getMinTimestart:function(){return minTimestart},hasMinTimestart:function(){return null!==minTimestart},setMaxTimestart:setMaxTimestart,getMaxTimestart:function(){return maxTimestart},hasMaxTimestart:function(){return null!==maxTimestart},setMinError:setMinError,getMinError:function(){return minError},setMaxError:setMaxError,getMaxError:function(){return maxError},clearAll:function(){setEventId(null),setDurationDays(null),setMinTimestart(null),setMaxTimestart(null),setMinError(null),setMaxError(null)}}})); /** * A javascript module to enhance the event form. * * @module core_calendar/event_form * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/event_form",["jquery","core_calendar/repository","core/notification"],(function($,CalendarRepository,Notification){var SELECTORS_EVENT_GROUP_COURSE_ID='[name="groupcourseid"]',SELECTORS_EVENT_GROUP_ID='[name="groupid"]',SELECTORS_SELECT_OPTION="option",addCourseGroupSelectListeners=function(formElement){var courseGroupSelect=formElement.find(SELECTORS_EVENT_GROUP_COURSE_ID);courseGroupSelect.on("change",(function(){var courseId=formElement.find(SELECTORS_EVENT_GROUP_COURSE_ID).val();CalendarRepository.getCourseGroupsData(courseId).then((function(groups){return function(groups){var groupSelect=formElement.find(SELECTORS_EVENT_GROUP_ID),groupSelectOptions=groupSelect.find(SELECTORS_SELECT_OPTION),courseGroups=$(groups);groupSelectOptions.remove(),groupSelect.prop("disabled",!1),courseGroups.each((function(id,group){$(groupSelect).append($("<option></option>").attr("value",group.id).text(group.name))}))}(groups)})).catch(Notification.exception)}))};return{init:function(formId){var formElement=$("#"+formId);addCourseGroupSelectListeners(formElement)}}})); define("core_calendar/export",["exports","core/copy_to_clipboard"],(function(_exports,_copy_to_clipboard){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * A javascript module to enhance the calendar export form. * * @module core_calendar/export * @copyright 2021 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const selectors_copyUrlId="copyexporturl";_exports.init=()=>{const copyUrl=document.getElementById(selectors_copyUrlId);copyUrl.removeAttribute("disabled"),copyUrl.focus()}})); /** * A javascript module to handle calendar drag and drop in the calendar * month view navigation. * * This code is run each time the calendar month view is re-rendered. We * only register the event handlers once per page load so that the in place * DOM updates that happen on month change don't continue to register handlers. * * @module core_calendar/month_navigation_drag_drop * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/month_navigation_drag_drop",["jquery","core_calendar/drag_drop_data_store"],(function($,DataStore){var SELECTORS_DRAGGABLE='[draggable="true"][data-region="event-item"]',SELECTORS_DROP_ZONE='[data-drop-zone="nav-link"]',registered=!1,hoverTimer=null,root=null,updateHoverState=function(target,hovered){hovered?target.addClass("bg-primary text-white"):target.removeClass("bg-primary text-white")},addDropZoneIndicator=function(){root.find(SELECTORS_DROP_ZONE).addClass("drop-target")},removeDropZoneIndicator=function(){root.find(SELECTORS_DROP_ZONE).removeClass("drop-target")},getTargetFromEvent=function(e){var target=$(e.target).closest(SELECTORS_DROP_ZONE);return target.length?target:null},dragstartHandler=function(e){$(e.target).closest(SELECTORS_DRAGGABLE).length&&addDropZoneIndicator()},dragoverHandler=function(e){if(DataStore.hasEventId()){e.preventDefault();var target=getTargetFromEvent(e);target&&DataStore.hasEventId()&&(hoverTimer||(hoverTimer=setTimeout((function(){target.click(),hoverTimer=null}),1e3)),updateHoverState(target,!0),removeDropZoneIndicator())}},dragleaveHandler=function(e){if(DataStore.hasEventId()){var target=getTargetFromEvent(e);target&&(hoverTimer&&(clearTimeout(hoverTimer),hoverTimer=null),updateHoverState(target,!1),addDropZoneIndicator(),e.preventDefault())}},dropHandler=function(e){if(DataStore.hasEventId()){removeDropZoneIndicator();var target=getTargetFromEvent(e);target&&(updateHoverState(target,!1),e.preventDefault())}};return{init:function(rootElement){registered||(document.addEventListener("dragstart",dragstartHandler,!1),document.addEventListener("dragover",dragoverHandler,!1),document.addEventListener("dragleave",dragleaveHandler,!1),document.addEventListener("drop",dropHandler,!1),document.addEventListener("dragend",removeDropZoneIndicator,!1),registered=!0),root=$(rootElement),DataStore.hasEventId()&&addDropZoneIndicator()}}})); /** * A javascript module to handle calendar drag and drop in the calendar * month view. * * @module core_calendar/month_view_drag_drop * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/month_view_drag_drop",["jquery","core/notification","core/str","core_calendar/events","core_calendar/drag_drop_data_store"],(function($,Notification,Str,CalendarEvents,DataStore){var SELECTORS_ROOT="[data-region='calendar']",SELECTORS_DRAGGABLE='[draggable="true"][data-region="event-item"]',SELECTORS_DROP_ZONE='[data-drop-zone="month-view-day"]',SELECTORS_WEEK='[data-region="month-view-week"]',ALL_CLASSES="bg-faded bg-danger text-white bg-primary text-white",registered=!1,getDropZoneFromEvent=function(e){var dropZone=$(e.target).closest(SELECTORS_DROP_ZONE);return dropZone.length?dropZone:null},isValidDropZone=function(dropZone){var dropTimestamp=dropZone.attr("data-day-timestamp"),minTimestart=DataStore.getMinTimestart(),maxTimestart=DataStore.getMaxTimestart();return!(minTimestart&&minTimestart>dropTimestamp)&&!(maxTimestart&&maxTimestart<dropTimestamp)},clearAllDropZonesState=function(){$(SELECTORS_ROOT).find(SELECTORS_DROP_ZONE).each((function(index,dropZone){(dropZone=$(dropZone)).removeClass(ALL_CLASSES)}))},updateHoverState=function(dropZone,hovered,count){void 0===count&&(count=DataStore.getDurationDays());var valid=isValidDropZone(dropZone);if(dropZone.removeClass(ALL_CLASSES),hovered?valid?dropZone.addClass("bg-primary text-white"):dropZone.addClass("bg-danger text-white"):(dropZone.removeClass("bg-primary text-white bg-danger text-white"),valid||dropZone.addClass("bg-faded")),--count>0){var nextDropZone=dropZone.next();if(!nextDropZone.length){var nextWeek=dropZone.closest(SELECTORS_WEEK).next();nextWeek.length&&(nextDropZone=nextWeek.children(SELECTORS_DROP_ZONE).first())}nextDropZone.length&&updateHoverState(nextDropZone,hovered,count)}},updateAllDropZonesState=function(){$(SELECTORS_ROOT).find(SELECTORS_DROP_ZONE).each((function(index,dropZone){dropZone=$(dropZone),isValidDropZone(dropZone)||updateHoverState(dropZone,!1)}))},dragstartHandler=function(e){var draggableElement=$(e.target).closest(SELECTORS_DRAGGABLE);if(draggableElement.length){var eventId=draggableElement.find("[data-event-id]").attr("data-event-id"),minTimestart=draggableElement.attr("data-min-day-timestamp"),maxTimestart=draggableElement.attr("data-max-day-timestamp"),minError=draggableElement.attr("data-min-day-error"),maxError=draggableElement.attr("data-max-day-error"),duration=$(SELECTORS_ROOT+' [data-event-id="'+eventId+'"]').length;DataStore.setEventId(eventId),DataStore.setDurationDays(duration),minTimestart&&DataStore.setMinTimestart(minTimestart),maxTimestart&&DataStore.setMaxTimestart(maxTimestart),minError&&DataStore.setMinError(minError),maxError&&DataStore.setMaxError(maxError),e.dataTransfer.effectAllowed="move",e.dataTransfer.dropEffect="move",e.dataTransfer.setData("text/plain",eventId),e.dropEffect="move",updateAllDropZonesState()}},dragoverHandler=function(e){if(DataStore.hasEventId()){e.preventDefault();var dropZone=getDropZoneFromEvent(e);dropZone&&updateHoverState(dropZone,!0)}},dragleaveHandler=function(e){if(DataStore.hasEventId()){var dropZone=getDropZoneFromEvent(e);dropZone&&(updateHoverState(dropZone,!1),e.preventDefault())}},dropHandler=function(e){if(DataStore.hasEventId()){var dropZone=getDropZoneFromEvent(e);if(!dropZone)return DataStore.clearAll(),void clearAllDropZonesState();if(isValidDropZone(dropZone)){var eventId=DataStore.getEventId(),eventElement=$(SELECTORS_ROOT+' [data-event-id="'+eventId+'"]'),origin=null;eventElement.length&&(origin=eventElement.closest(SELECTORS_DROP_ZONE)),$("body").trigger(CalendarEvents.moveEvent,[eventId,origin,dropZone])}else{var message=function(dropZone){var dropTimestamp=dropZone.attr("data-day-timestamp"),minTimestart=DataStore.getMinTimestart(),maxTimestart=DataStore.getMaxTimestart();return minTimestart&&minTimestart>dropTimestamp?DataStore.getMinError():maxTimestart&&maxTimestart<dropTimestamp?DataStore.getMaxError():null}(dropZone);Str.get_string("errorinvaliddate","calendar").then((function(string){Notification.exception({name:string,message:message||string})}))}DataStore.clearAll(),clearAllDropZonesState(),e.preventDefault()}},dragendHandler=function(){DataStore.clearAll(),clearAllDropZonesState()},calendarMonthChangedHandler=function(){updateAllDropZonesState()};return{init:function(){registered||(document.addEventListener("dragstart",dragstartHandler,!1),document.addEventListener("dragover",dragoverHandler,!1),document.addEventListener("dragleave",dragleaveHandler,!1),document.addEventListener("drop",dropHandler,!1),document.addEventListener("dragend",dragendHandler,!1),$("body").on(CalendarEvents.monthChanged,calendarMonthChangedHandler),registered=!0)}}})); define("core_calendar/popover",["theme_boost/popover","jquery","core_calendar/selectors"],(function(_popover,_jquery,CalendarSelectors){var obj; /** * Javascript popover for the `core_calendar` subsystem. * * @module core_calendar/popover * @copyright 2021 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj},CalendarSelectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(CalendarSelectors);const isPopoverConfigured=new Map,showPopover=target=>{if(!isPopoverConfigured.has(target)){const dateEle=(0,_jquery.default)(target);dateEle.popover({trigger:"manual",placement:"top",html:!0,content:()=>{const source=dateEle.find(CalendarSelectors.elements.dateContent),content=(0,_jquery.default)("<div>");if(source.length){const temptContent=source.find(".hidden").clone(!1);content.html(temptContent.html())}return content.html()}}),isPopoverConfigured.set(target,!0)}var dateContainer;dateContainer=target,"none"===window.getComputedStyle(dateContainer.querySelector(CalendarSelectors.elements.dateContent)).display&&((0,_jquery.default)(target).popover("show"),target.addEventListener("mouseleave",hidePopover),target.addEventListener("focusout",hidePopover))},hidePopover=e=>{const target=e.target,dateContainer=e.target.closest(CalendarSelectors.elements.dateContainer);if(dateContainer&&isPopoverConfigured.has(dateContainer)){const isTargetActive=target.contains(document.activeElement),isTargetHover=target.matches(":hover");isTargetActive||isTargetHover||((0,_jquery.default)(dateContainer).popover("hide"),dateContainer.removeEventListener("mouseleave",hidePopover),dateContainer.removeEventListener("focusout",hidePopover))}};let listenersRegistered=!1;listenersRegistered||((()=>{const showPopoverHandler=e=>{const dateContainer=e.target.closest(CalendarSelectors.elements.dateContainer);dateContainer&&(e.preventDefault(),showPopover(dateContainer))};document.addEventListener("mouseover",showPopoverHandler),document.addEventListener("focusin",showPopoverHandler)})(),listenersRegistered=!0)})); define("core_calendar/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * A javascript module to handle calendar ajax actions. * * @module core_calendar/repository * @copyright 2017 Simey Lameze <lameze@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateEventStartDay=_exports.submitCreateUpdateForm=_exports.getEventById=_exports.getCourseGroupsData=_exports.getCalendarUpcomingData=_exports.getCalendarMonthData=_exports.getCalendarDayData=_exports.deleteSubscription=_exports.deleteEvent=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.deleteEvent=function(eventId){let deleteSeries=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const request={methodname:"core_calendar_delete_calendar_events",args:{events:[{eventid:eventId,repeat:deleteSeries}]}};return _ajax.default.call([request])[0]};_exports.getEventById=eventId=>{const request={methodname:"core_calendar_get_calendar_event_by_id",args:{eventid:eventId}};return _ajax.default.call([request])[0]};_exports.submitCreateUpdateForm=formData=>{const request={methodname:"core_calendar_submit_create_update_form",args:{formdata:formData}};return _ajax.default.call([request])[0]};_exports.getCalendarMonthData=function(year,month,courseId,categoryId,includeNavigation,mini){let day=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1,view=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"month";const request={methodname:"core_calendar_get_calendar_monthly_view",args:{year:year,month:month,courseid:courseId,categoryid:categoryId,includenavigation:includeNavigation,mini:mini,day:day,view:view}};return _ajax.default.call([request])[0]};_exports.getCalendarDayData=(year,month,day,courseId,categoryId)=>{const request={methodname:"core_calendar_get_calendar_day_view",args:{year:year,month:month,day:day,courseid:courseId,categoryid:categoryId}};return _ajax.default.call([request])[0]};_exports.updateEventStartDay=(eventId,dayTimestamp)=>{const request={methodname:"core_calendar_update_event_start_day",args:{eventid:eventId,daytimestamp:dayTimestamp}};return _ajax.default.call([request])[0]};_exports.getCalendarUpcomingData=(courseId,categoryId)=>{const request={methodname:"core_calendar_get_calendar_upcoming_view",args:{courseid:courseId,categoryid:categoryId}};return _ajax.default.call([request])[0]};_exports.getCourseGroupsData=courseId=>{const request={methodname:"core_group_get_course_groups",args:{courseid:courseId}};return _ajax.default.call([request])[0]};_exports.deleteSubscription=subscriptionId=>{const request={methodname:"core_calendar_delete_subscription",args:{subscriptionid:subscriptionId}};return _ajax.default.call([request])[0]}})); /** * This module is responsible for handle calendar day and upcoming view. * * @module core_calendar/calendar * @copyright 2017 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/calendar_view",["jquery","core/str","core/notification","core_calendar/selectors","core_calendar/events","core_calendar/view_manager","core_calendar/repository","core/modal_factory","core_calendar/modal_event_form","core/modal_events","core_calendar/crud"],(function($,Str,Notification,CalendarSelectors,CalendarEvents,CalendarViewManager,CalendarRepository,ModalFactory,ModalEventForm,ModalEvents,CalendarCrud){return{init:function(root,type){root=$(root),CalendarViewManager.init(root,type),function(root,type){var body=$("body");CalendarCrud.registerRemove(root);var reloadFunction="reloadCurrent"+type.charAt(0).toUpperCase()+type.slice(1);body.on(CalendarEvents.created,(function(){CalendarViewManager[reloadFunction](root)})),body.on(CalendarEvents.deleted,(function(){CalendarViewManager[reloadFunction](root)})),body.on(CalendarEvents.updated,(function(){CalendarViewManager[reloadFunction](root)})),root.on("change",CalendarSelectors.courseSelector,(function(){var courseId=$(this).val();CalendarViewManager[reloadFunction](root,courseId,null).then((function(){return root.find(CalendarSelectors.courseSelector).val(courseId)})).then((function(){CalendarViewManager.updateUrl("?view=upcoming&course="+courseId)})).fail(Notification.exception)})),body.on(CalendarEvents.filterChanged,(function(e,data){var daysWithEvent=root.find(CalendarSelectors.eventType[data.type]);1==data.hidden?daysWithEvent.addClass("hidden"):daysWithEvent.removeClass("hidden"),CalendarViewManager.foldDayEvents(root)}));var eventFormPromise=CalendarCrud.registerEventFormModal(root);CalendarCrud.registerEditListeners(root,eventFormPromise)}(root,type)}}})); /** * A module to handle CRUD operations within the UI. * * @module core_calendar/crud * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/crud",["jquery","core/str","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_factory","core/modal_events","core_calendar/modal_event_form","core_calendar/repository","core_calendar/events","core_calendar/modal_delete","core_calendar/selectors","core/pending"],(function($,Str,Notification,CustomEvents,Modal,ModalRegistry,ModalFactory,ModalEvents,ModalEventForm,CalendarRepository,CalendarEvents,ModalDelete,CalendarSelectors,Pending){return{registerRemove:function(root){root.on("click",CalendarSelectors.actions.remove,(function(e){var eventSource=$(this).closest(CalendarSelectors.eventItem);!function(eventId,eventTitle,eventCount){var deletePromise,pendingPromise=new Pending("core_calendar/crud:confirmDeletion"),deleteStrings=[{key:"deleteevent",component:"calendar"}],isRepeatedEvent=(eventCount=parseInt(eventCount,10))>1;isRepeatedEvent?(deleteStrings.push({key:"confirmeventseriesdelete",component:"calendar",param:{name:eventTitle,count:eventCount}}),deletePromise=ModalFactory.create({type:ModalDelete.TYPE})):(deleteStrings.push({key:"confirmeventdelete",component:"calendar",param:eventTitle}),deletePromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL}));var stringsPromise=Str.get_strings(deleteStrings);$.when(stringsPromise,deletePromise).then((function(strings,deleteModal){return deleteModal.setRemoveOnClose(!0),deleteModal.setTitle(strings[0]),deleteModal.setBody(strings[1]),isRepeatedEvent||deleteModal.setSaveButtonText(strings[0]),deleteModal.show(),deleteModal.getRoot().on(ModalEvents.save,(function(){var pendingPromise=new Pending("calendar/crud:initModal:deletedevent");CalendarRepository.deleteEvent(eventId,!1).then((function(){$("body").trigger(CalendarEvents.deleted,[eventId,!1])})).then(pendingPromise.resolve).catch(Notification.exception)})),deleteModal.getRoot().on(CalendarEvents.deleteAll,(function(){var pendingPromise=new Pending("calendar/crud:initModal:deletedallevent");CalendarRepository.deleteEvent(eventId,!0).then((function(){$("body").trigger(CalendarEvents.deleted,[eventId,!0])})).then(pendingPromise.resolve).catch(Notification.exception)})),deleteModal})).then((function(modal){return pendingPromise.resolve(),modal})).catch(Notification.exception)}(eventSource.data("eventId"),eventSource.data("eventTitle"),eventSource.data("eventCount")),e.preventDefault()}))},registerEditListeners:function(root,eventFormModalPromise){var pendingPromise=new Pending("core_calendar/crud:registerEditListeners");return eventFormModalPromise.then((function(modal){return $("body").on(CalendarEvents.editEvent,(function(e,eventId){var target=root.find("[data-event-id=".concat(eventId,"]")),calendarWrapper=root.find(CalendarSelectors.wrapper);modal.setEventId(eventId),modal.setContextId(calendarWrapper.data("contextId")),modal.setReturnElement(target),modal.show(),e.stopImmediatePropagation()})),modal})).then((function(modal){return pendingPromise.resolve(),modal})).catch(Notification.exception)},registerEventFormModal:function(root){var eventFormPromise=ModalFactory.create({type:ModalEventForm.TYPE,large:!0});return root.on("click",CalendarSelectors.actions.create,(function(e){eventFormPromise.then((function(modal){var wrapper=root.find(CalendarSelectors.wrapper),categoryId=wrapper.data("categoryid");void 0!==categoryId&&modal.setCategoryId(categoryId);var today=root.find(CalendarSelectors.today),firstDay=root.find(CalendarSelectors.day);!today.length&&firstDay.length&&modal.setStartTime(firstDay.data("newEventTimestamp")),modal.setContextId(wrapper.data("contextId")),modal.setCourseId(wrapper.data("courseid")),modal.show()})).fail(Notification.exception),e.preventDefault()})),root.on("click",CalendarSelectors.actions.edit,(function(e){e.preventDefault();var target=$(e.currentTarget),calendarWrapper=target.closest(CalendarSelectors.wrapper),eventWrapper=target.closest(CalendarSelectors.eventItem);eventFormPromise.then((function(modal){modal.setEventId(eventWrapper.data("eventId")),modal.setContextId(calendarWrapper.data("contextId")),modal.setCourseId(eventWrapper.data("courseId")),modal.show(),e.stopImmediatePropagation()})).fail(Notification.exception)})),eventFormPromise}}})); /** * Contain the events the calendar component can fire. * * @module core_calendar/events * @copyright 2017 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/events",[],(function(){return{created:"calendar-events:created",deleted:"calendar-events:deleted",deleteAll:"calendar-events:delete_all",updated:"calendar-events:updated",editEvent:"calendar-events:edit_event",editActionEvent:"calendar-events:edit_action_event",eventMoved:"calendar-events:event_moved",dayChanged:"calendar-events:day_changed",monthChanged:"calendar-events:month_changed",moveEvent:"calendar-events:move_event",filterChanged:"calendar-events:filter_changed",courseChanged:"calendar-events:course_changed",viewUpdated:"calendar-events:view_updated"}})); define("core_calendar/manage_subscriptions",["exports","core_calendar/selectors","core_calendar/repository","core/modal_factory","core/modal_events","core/notification","core/prefetch","core/str","core/local/inplace_editable/events"],(function(_exports,CalendarSelectors,CalendarRepository,Modal,ModalEvents,_notification,_prefetch,_str,_events){var obj;function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * A module to handle Delete/Update operations of the manage subscription page. * * @module core_calendar/manage_subscriptions * @copyright 2021 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,CalendarSelectors=_interopRequireWildcard(CalendarSelectors),CalendarRepository=_interopRequireWildcard(CalendarRepository),Modal=_interopRequireWildcard(Modal),ModalEvents=_interopRequireWildcard(ModalEvents),_prefetch=(obj=_prefetch)&&obj.__esModule?obj:{default:obj};const getSubscriptionName=element=>element.closest("tr").dataset.subname,registerEventListeners=()=>{document.addEventListener("click",(e=>{const deleteAction=e.target.closest(CalendarSelectors.actions.deleteSubscription);if(deleteAction){e.preventDefault();((element,messageCode)=>{const subscriptionName=getSubscriptionName(element);return Modal.create({type:Modal.types.SAVE_CANCEL,title:(0,_str.get_string)("confirmation","admin"),body:(0,_str.get_string)(messageCode,"calendar",subscriptionName),buttons:{save:(0,_str.get_string)("yes")}}).then((modal=>(modal.getRoot().on(ModalEvents.hidden,(()=>{element.focus()})),modal.show(),modal)))})(deleteAction,"confirmsubscriptiondelete").then((modal=>(modal.getRoot().on(ModalEvents.save,(()=>{const subscriptionId=parseInt(deleteAction.closest("tr").dataset.subid);CalendarRepository.deleteSubscription(subscriptionId).then((data=>{const response=(async(element,data)=>{const subscriptionName=getSubscriptionName(element),message=data.status?await(0,_str.get_string)("subscriptionremoved","calendar",subscriptionName):data.warnings[0].message,type=data.status?"info":"error";return(0,_notification.addNotification)({message:message,type:type})})(deleteAction,data);return response.then((()=>{const subscriptionRow=(subscriptionId=>document.querySelector('tr[data-subid="'.concat(subscriptionId,'"]')))(subscriptionId);return subscriptionRow.remove()}))})).catch(_notification.exception)})),modal))).catch(_notification.exception)}})),document.addEventListener(_events.eventTypes.elementUpdated,(e=>{"core_calendar"==e.target.getAttribute("data-component")&&(0,_notification.fetchNotifications)()}))};_exports.init=()=>{_prefetch.default.prefetchStrings("moodle",["yes"]),_prefetch.default.prefetchStrings("core_admin",["confirmation"]),_prefetch.default.prefetchStrings("core_calendar",["confirmsubscriptiondelete","subscriptionremoved"]),registerEventListeners()}})); /** * Contain the logic for the delete modal. * * @module core_calendar/modal_delete * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/modal_delete",["jquery","core/notification","core/custom_interaction_events","core/modal","core/modal_events","core/modal_registry","core_calendar/events"],(function($,Notification,CustomEvents,Modal,ModalEvents,ModalRegistry,CalendarEvents){var registered=!1,SELECTORS_DELETE_ONE_BUTTON='[data-action="deleteone"]',SELECTORS_DELETE_ALL_BUTTON='[data-action="deleteall"]',SELECTORS_CANCEL_BUTTON='[data-action="cancel"]',ModalDelete=function(root){Modal.call(this,root),this.setRemoveOnClose(!0)};return ModalDelete.TYPE="core_calendar-modal_delete",(ModalDelete.prototype=Object.create(Modal.prototype)).constructor=ModalDelete,ModalDelete.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_DELETE_ONE_BUTTON,function(e,data){var saveEvent=$.Event(ModalEvents.save);this.getRoot().trigger(saveEvent,this),saveEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this)),this.getModal().on(CustomEvents.events.activate,SELECTORS_DELETE_ALL_BUTTON,function(e,data){var saveEvent=$.Event(CalendarEvents.deleteAll);this.getRoot().trigger(saveEvent,this),saveEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this)),this.getModal().on(CustomEvents.events.activate,SELECTORS_CANCEL_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalDelete.TYPE,ModalDelete,"calendar/event_delete_modal"),registered=!0),ModalDelete})); /** * Contain the logic for the quick add or update event modal. * * @module core_calendar/modal_quick_add_event * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/modal_event_form",["jquery","core_form/events","core/str","core/notification","core/templates","core/custom_interaction_events","core/modal","core/modal_registry","core/fragment","core_calendar/events","core_calendar/repository"],(function($,FormEvents,Str,Notification,Templates,CustomEvents,Modal,ModalRegistry,Fragment,CalendarEvents,Repository){var registered=!1,SELECTORS_SAVE_BUTTON='[data-action="save"]',SELECTORS_LOADING_ICON_CONTAINER='[data-region="loading-icon-container"]',ModalEventForm=function(root){Modal.call(this,root),this.eventId=null,this.startTime=null,this.courseId=null,this.categoryId=null,this.contextId=null,this.reloadingBody=!1,this.reloadingTitle=!1,this.saveButton=this.getFooter().find(SELECTORS_SAVE_BUTTON)};return ModalEventForm.TYPE="core_calendar-modal_event_form",(ModalEventForm.prototype=Object.create(Modal.prototype)).constructor=ModalEventForm,ModalEventForm.prototype.setContextId=function(id){this.contextId=id},ModalEventForm.prototype.getContextId=function(){return this.contextId},ModalEventForm.prototype.setCourseId=function(id){this.courseId=id},ModalEventForm.prototype.getCourseId=function(){return this.courseId},ModalEventForm.prototype.setCategoryId=function(id){this.categoryId=id},ModalEventForm.prototype.getCategoryId=function(){return this.categoryId},ModalEventForm.prototype.hasCourseId=function(){return null!==this.courseId},ModalEventForm.prototype.hasCategoryId=function(){return null!==this.categoryId},ModalEventForm.prototype.setEventId=function(id){this.eventId=id},ModalEventForm.prototype.getEventId=function(){return this.eventId},ModalEventForm.prototype.hasEventId=function(){return null!==this.eventId},ModalEventForm.prototype.setStartTime=function(time){this.startTime=time},ModalEventForm.prototype.getStartTime=function(){return this.startTime},ModalEventForm.prototype.hasStartTime=function(){return null!==this.startTime},ModalEventForm.prototype.getForm=function(){return this.getBody().find("form")},ModalEventForm.prototype.disableButtons=function(){this.saveButton.prop("disabled",!0)},ModalEventForm.prototype.enableButtons=function(){this.saveButton.prop("disabled",!1)},ModalEventForm.prototype.reloadTitleContent=function(){return this.reloadingTitle||(this.reloadingTitle=!0,this.hasEventId()?this.titlePromise=Str.get_string("editevent","calendar"):this.titlePromise=Str.get_string("newevent","calendar"),this.titlePromise.then(function(string){return this.setTitle(string),string}.bind(this)).always(function(){this.reloadingTitle=!1}.bind(this)).fail(Notification.exception)),this.titlePromise},ModalEventForm.prototype.reloadBodyContent=function(formData){if(this.reloadingBody)return this.bodyPromise;this.reloadingBody=!0,this.disableButtons();var args={};return this.hasEventId()&&(args.eventid=this.getEventId()),this.hasStartTime()&&(args.starttime=this.getStartTime()),this.hasCourseId()&&(args.courseid=this.getCourseId()),this.hasCategoryId()&&(args.categoryid=this.getCategoryId()),void 0!==formData&&(args.formdata=formData),this.bodyPromise=Fragment.loadFragment("calendar","event_form",this.getContextId(),args),this.setBody(this.bodyPromise),this.bodyPromise.then(function(){this.enableButtons()}.bind(this)).fail(Notification.exception).always(function(){this.reloadingBody=!1}.bind(this)).fail(Notification.exception),this.bodyPromise},ModalEventForm.prototype.reloadAllContent=function(){return $.when(this.reloadTitleContent(),this.reloadBodyContent())},ModalEventForm.prototype.show=function(){this.reloadAllContent(),Modal.prototype.show.call(this)},ModalEventForm.prototype.hide=function(){Modal.prototype.hide.call(this),this.setEventId(null),this.setStartTime(null),this.setCourseId(null),this.setCategoryId(null)},ModalEventForm.prototype.getFormData=function(){return this.getForm().serialize()},ModalEventForm.prototype.save=function(){var invalid,loadingContainer=this.saveButton.find(SELECTORS_LOADING_ICON_CONTAINER);if((invalid=this.getForm().find('[aria-invalid="true"]')).length)return invalid.first().focus(),Promise.resolve();loadingContainer.removeClass("hidden"),this.disableButtons();var formData=this.getFormData();return Repository.submitCreateUpdateForm(formData).then(function(response){if(response.validationerror)this.reloadBodyContent(formData);else{var isExisting=this.hasEventId();this.hide(),isExisting?$("body").trigger(CalendarEvents.updated,[response.event]):$("body").trigger(CalendarEvents.created,[response.event])}}.bind(this)).always(function(){loadingContainer.addClass("hidden"),this.enableButtons()}.bind(this)).fail(Notification.exception)},ModalEventForm.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_SAVE_BUTTON,function(e,data){this.getForm().submit(),data.originalEvent.preventDefault(),e.stopPropagation()}.bind(this)),this.getModal().on("submit",function(e){FormEvents.notifyFormSubmittedByJavascript(this.getForm()[0]),this.save(),e.preventDefault(),e.stopPropagation()}.bind(this))},registered||(ModalRegistry.register(ModalEventForm.TYPE,ModalEventForm,"calendar/modal_event_form"),registered=!0),ModalEventForm})); /** * This module is responsible for the calendar filter. * * @module core_calendar/calendar_selectors * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/selectors",[],(function(){return{eventFilterItem:"[data-action='filter-event-type']",eventType:{site:"[data-eventtype-site]",category:"[data-eventtype-category]",course:"[data-eventtype-course]",group:"[data-eventtype-group]",user:"[data-eventtype-user]",other:"[data-eventtype-other]"},popoverType:{site:"[data-popover-eventtype-site]",category:"[data-popover-eventtype-category]",course:"[data-popover-eventtype-course]",group:"[data-popover-eventtype-group]",user:"[data-popover-eventtype-user]",other:"[data-popover-eventtype-other]"},calendarPeriods:{month:"[data-period='month']"},courseSelector:'select[name="course"]',viewSelector:'div[data-region="view-selector"]',actions:{create:'[data-action="new-event-button"]',edit:'[data-action="edit"]',remove:'[data-action="delete"]',viewEvent:'[data-action="view-event"]',deleteSubscription:'[data-action="delete-subscription"]'},elements:{courseSelector:'select[name="course"]',dateContainer:".clickable.hasevent",dateContent:'[data-region="day-content"]',monthDetailed:".calendarmonth.calendartable"},today:".today",day:'[data-region="day"]',calendarMain:'[data-region="calendar"]',wrapper:".calendarwrapper",eventItem:'[data-type="event"]',links:{navLink:".calendarwrapper .arrow_link",eventLink:"[data-region='event-item']",miniDayLink:"[data-region='mini-day-link']"},containers:{loadingIcon:'[data-region="overlay-icon-container"]'},mainCalendar:".maincalendar .heightcontainer",fullCalendarView:"page-calendar-view"}})); /** * A javascript module to handle summary modal. * * @module core_calendar/summary_modal * @copyright 2017 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_calendar/summary_modal",["jquery","core/str","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_factory","core/modal_events","core_calendar/repository","core_calendar/events","core_calendar/crud"],(function($,Str,Notification,CustomEvents,Modal,ModalRegistry,ModalFactory,ModalEvents,CalendarRepository,CalendarEvents,CalendarCrud){var registered=!1,SELECTORS_ROOT="[data-region='summary-modal-container']",SELECTORS_EDIT_BUTTON='[data-action="edit"]',SELECTORS_DELETE_BUTTON='[data-action="delete"]',ModalEventSummary=function(root){Modal.call(this,root)};return ModalEventSummary.TYPE="core_calendar-event_summary",(ModalEventSummary.prototype=Object.create(Modal.prototype)).constructor=ModalEventSummary,ModalEventSummary.prototype.getEditButton=function(){return void 0===this.editButton&&(this.editButton=this.getFooter().find(SELECTORS_EDIT_BUTTON)),this.editButton},ModalEventSummary.prototype.getDeleteButton=function(){return void 0===this.deleteButton&&(this.deleteButton=this.getFooter().find(SELECTORS_DELETE_BUTTON)),this.deleteButton},ModalEventSummary.prototype.getEventId=function(){return this.getBody().find(SELECTORS_ROOT).attr("data-event-id")},ModalEventSummary.prototype.getEventTitle=function(){return this.getBody().find(SELECTORS_ROOT).attr("data-event-title")},ModalEventSummary.prototype.getEventCount=function(){return this.getBody().find(SELECTORS_ROOT).attr("data-event-count")},ModalEventSummary.prototype.getEditUrl=function(){return this.getBody().find(SELECTORS_ROOT).attr("data-edit-url")},ModalEventSummary.prototype.isActionEvent=function(){return"true"==this.getBody().find(SELECTORS_ROOT).attr("data-action-event")},ModalEventSummary.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),M.util.js_pending("core_calendar/summary_modal:registerEventListeners:bodyRendered"),this.getRoot().on(ModalEvents.bodyRendered,function(){this.getModal().data({eventTitle:this.getEventTitle(),eventId:this.getEventId(),eventCount:this.getEventCount()}).attr("data-type","event"),CalendarCrud.registerRemove(this.getModal()),M.util.js_complete("core_calendar/summary_modal:registerEventListeners:bodyRendered")}.bind(this)),$("body").on(CalendarEvents.deleted,function(){this.hide()}.bind(this)),CustomEvents.define(this.getEditButton(),[CustomEvents.events.activate]),this.getEditButton().on(CustomEvents.events.activate,function(e,data){this.isActionEvent()?$("body").trigger(CalendarEvents.editActionEvent,[this.getEditUrl()]):$("body").trigger(CalendarEvents.editEvent,[this.getEventId()]),this.hide(),e.preventDefault(),e.stopPropagation(),data.originalEvent.preventDefault(),data.originalEvent.stopPropagation()}.bind(this))},registered||(ModalRegistry.register(ModalEventSummary.TYPE,ModalEventSummary,"core_calendar/event_summary_modal"),registered=!0),ModalEventSummary})); define("core_calendar/view_manager",["exports","jquery","core/templates","core/notification","core_calendar/repository","core_calendar/events","core_calendar/selectors","core/modal_factory","core/modal_events","core_calendar/summary_modal","core/custom_interaction_events","core/str","core/pending","core/prefetch"],(function(_exports,_jquery,_templates,_notification,CalendarRepository,_events,CalendarSelectors,_modal_factory,_modal_events,_summary_modal,_custom_interaction_events,_str,_pending,_prefetch){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A javascript module to handler calendar view changes. * * @module core_calendar/view_manager * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateUrl=_exports.reloadCurrentUpcoming=_exports.reloadCurrentMonth=_exports.reloadCurrentDay=_exports.registerEventListenersForMonthDetailed=_exports.refreshMonthContent=_exports.refreshDayContent=_exports.init=_exports.foldDayEvents=_exports.changeMonth=_exports.changeDay=void 0,_jquery=_interopRequireDefault(_jquery),_templates=_interopRequireDefault(_templates),_notification=_interopRequireDefault(_notification),CalendarRepository=_interopRequireWildcard(CalendarRepository),_events=_interopRequireDefault(_events),CalendarSelectors=_interopRequireWildcard(CalendarSelectors),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_summary_modal=_interopRequireDefault(_summary_modal),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_pending=_interopRequireDefault(_pending);const foldDayEvents=()=>{const days=(0,_jquery.default)(CalendarSelectors.elements.monthDetailed).find(CalendarSelectors.day);0!==days.length&&days.each((function(){const dayContainer=(0,_jquery.default)(this),eventsSelector="".concat(CalendarSelectors.elements.dateContent," ul li[data-event-eventtype]"),filteredEventsSelector="".concat(CalendarSelectors.elements.dateContent,' ul li[data-event-filtered="true"]'),moreEventsSelector="".concat(CalendarSelectors.elements.dateContent,' [data-action="view-more-events"]'),events=dayContainer.find(eventsSelector);if(0===events.length)return;const numberOfFiltered=dayContainer.find(filteredEventsSelector).length,numberOfEvents=events.length-numberOfFiltered;let count=1;events.each((function(){const event=(0,_jquery.default)(this);"true"!==event.attr("data-event-filtered")?count>5-(5===numberOfEvents?0:1)?(event.attr("data-event-folded","true"),event.hide()):(event.attr("data-event-folded","false"),event.show(),count++):event.attr("data-event-folded","false")}));const moreEventsLink=dayContainer.find(moreEventsSelector);if(numberOfEvents>5){const numberOfHiddenEvents=numberOfEvents-5+1;moreEventsLink.show(),(0,_str.get_string)("moreevents","calendar",numberOfHiddenEvents).then((str=>{const link=moreEventsLink.find("strong a");return moreEventsLink.attr("data-event-folded","false"),link.text(str),str})).fail()}else moreEventsLink.hide()}))};_exports.foldDayEvents=foldDayEvents;const registerEventListenersForMonthDetailed=pendingId=>{const events="".concat(_events.default.viewUpdated);(0,_jquery.default)("body").on(events,(function(e){foldDayEvents()})),foldDayEvents(),(0,_jquery.default)("body").on(_events.default.filterChanged,(function(e,data){const root=(0,_jquery.default)(CalendarSelectors.elements.monthDetailed),pending=new _pending.default(pendingId),target=root.find(CalendarSelectors.eventType[data.type]),transitionPromise=_jquery.default.Deferred();data.hidden?transitionPromise.then((function(){return target.attr("data-event-filtered","true"),target.hide().promise()})).fail():transitionPromise.then((function(){return target.attr("data-event-filtered","false"),target.show().promise()})).fail(),transitionPromise.then((function(){foldDayEvents()})).always(pending.resolve).fail(),transitionPromise.resolve()}))};_exports.registerEventListenersForMonthDetailed=registerEventListenersForMonthDetailed;const refreshMonthContent=function(root,year,month,courseId,categoryId){let target=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,template=arguments.length>6&&void 0!==arguments[6]?arguments[6]:"",day=arguments.length>7&&void 0!==arguments[7]?arguments[7]:1;startLoading(root),target=target||root.find(CalendarSelectors.wrapper),template=template||root.attr("data-template"),M.util.js_pending([root.get("id"),year,month,courseId].join("-"));const includenavigation=root.data("includenavigation"),mini=root.data("mini"),viewMode=target.data("view");return CalendarRepository.getCalendarMonthData(year,month,courseId,categoryId,includenavigation,mini,day,viewMode).then((context=>_templates.default.render(template,context))).then(((html,js)=>_templates.default.replaceNode(target,html,js))).then((()=>{document.querySelector("body").dispatchEvent(new CustomEvent(_events.default.viewUpdated))})).always((()=>(M.util.js_complete([root.get("id"),year,month,courseId].join("-")),stopLoading(root)))).fail(_notification.default.exception)};_exports.refreshMonthContent=refreshMonthContent;const changeMonth=function(root,url,year,month,courseId,categoryId){let day=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1;return refreshMonthContent(root,year,month,courseId,categoryId,null,"",day).then((function(){url.length&&"#"!==url&&updateUrl(url);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return args})).then((function(){(0,_jquery.default)("body").trigger(_events.default.monthChanged,[year,month,courseId,categoryId]);for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];return args}))};_exports.changeMonth=changeMonth;_exports.reloadCurrentMonth=function(root){let courseId=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,categoryId=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const year=root.find(CalendarSelectors.wrapper).data("year"),month=root.find(CalendarSelectors.wrapper).data("month"),day=root.find(CalendarSelectors.wrapper).data("day");return courseId=courseId||root.find(CalendarSelectors.wrapper).data("courseid"),categoryId=categoryId||root.find(CalendarSelectors.wrapper).data("categoryid"),refreshMonthContent(root,year,month,courseId,categoryId,null,"",day).then((function(){(0,_jquery.default)("body").trigger(_events.default.courseChanged,[year,month,courseId,categoryId]);for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++)args[_key3]=arguments[_key3];return args}))};const refreshDayContent=function(root,year,month,day,courseId,categoryId){let target=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,template=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"";startLoading(root),target&&0!=target.length||(target=root.find(CalendarSelectors.wrapper)),template=template||root.attr("data-template"),M.util.js_pending([root.get("id"),year,month,day,courseId,categoryId].join("-"));const includenavigation=root.data("includenavigation");return CalendarRepository.getCalendarDayData(year,month,day,courseId,categoryId,includenavigation).then((context=>(context.viewingday=!0,context.showviewselector=!0,_templates.default.render(template,context)))).then(((html,js)=>_templates.default.replaceNode(target,html,js))).then((()=>{document.querySelector("body").dispatchEvent(new CustomEvent(_events.default.viewUpdated))})).always((()=>(M.util.js_complete([root.get("id"),year,month,day,courseId,categoryId].join("-")),stopLoading(root)))).fail(_notification.default.exception)};_exports.refreshDayContent=refreshDayContent;_exports.reloadCurrentDay=function(root){let courseId=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,categoryId=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const wrapper=root.find(CalendarSelectors.wrapper),year=wrapper.data("year"),month=wrapper.data("month"),day=wrapper.data("day");return courseId=courseId||root.find(CalendarSelectors.wrapper).data("courseid"),categoryId=categoryId||root.find(CalendarSelectors.wrapper).data("categoryid"),refreshDayContent(root,year,month,day,courseId,categoryId)};const changeDay=(root,url,year,month,day,courseId,categoryId)=>refreshDayContent(root,year,month,day,courseId,categoryId).then((function(){url.length&&"#"!==url&&updateUrl(url);for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++)args[_key4]=arguments[_key4];return args})).then((function(){(0,_jquery.default)("body").trigger(_events.default.dayChanged,[year,month,courseId,categoryId]);for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++)args[_key5]=arguments[_key5];return args}));_exports.changeDay=changeDay;const updateUrl=url=>{document.getElementById(CalendarSelectors.fullCalendarView)&&window.history.pushState({},"",url)};_exports.updateUrl=updateUrl;const startLoading=root=>{root.find(CalendarSelectors.containers.loadingIcon).removeClass("hidden")},stopLoading=root=>{root.find(CalendarSelectors.containers.loadingIcon).addClass("hidden")},reloadCurrentUpcoming=function(root){let courseId=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,categoryId=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,target=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,template=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"";return startLoading(root),target=target||root.find(CalendarSelectors.wrapper),template=template||root.attr("data-template"),courseId=courseId||root.find(CalendarSelectors.wrapper).data("courseid"),categoryId=categoryId||root.find(CalendarSelectors.wrapper).data("categoryid"),CalendarRepository.getCalendarUpcomingData(courseId,categoryId).then((context=>(context.viewingupcoming=!0,context.showviewselector=!0,_templates.default.render(template,context)))).then(((html,js)=>_templates.default.replaceNode(target,html,js))).then((()=>{document.querySelector("body").dispatchEvent(new CustomEvent(_events.default.viewUpdated))})).always((function(){return stopLoading(root)})).fail(_notification.default.exception)};_exports.reloadCurrentUpcoming=reloadCurrentUpcoming;const renderEventSummaryModal=eventId=>{const pendingPromise=new _pending.default("core_calendar/view_manager:renderEventSummaryModal");return CalendarRepository.getEventById(eventId).then((getEventResponse=>{if(!getEventResponse.event)throw new Error("Error encountered while trying to fetch calendar event with ID: "+eventId);return getEventResponse.event})).then((eventData=>{const modalParams={title:eventData.name,type:_summary_modal.default.TYPE,body:_templates.default.render("core_calendar/event_summary_body",eventData),templateContext:{canedit:eventData.canedit,candelete:eventData.candelete,headerclasses:(eventType=eventData.normalisedeventtype,"calendar_event_"+eventType),isactionevent:eventData.isactionevent,url:eventData.url,action:eventData.action}};var eventType;return _modal_factory.default.create(modalParams)})).then((modal=>(modal.getRoot().on(_modal_events.default.hidden,(function(){modal.destroy()})),modal.show(),modal))).then((modal=>(pendingPromise.resolve(),modal))).catch(_notification.default.exception)};_exports.init=(root,view)=>{(0,_prefetch.prefetchStrings)("calendar",["moreevents"]),foldDayEvents(),(root=>{(root=(0,_jquery.default)(root)).on("click",CalendarSelectors.links.eventLink,(e=>{const target=e.target;let eventLink=null,eventId=null;const pendingPromise=new _pending.default("core_calendar/view_manager:eventLink:click");eventLink=target.matches(CalendarSelectors.actions.viewEvent)?target:target.closest(CalendarSelectors.actions.viewEvent),eventId=eventLink?eventLink.dataset.eventId:target.querySelector(CalendarSelectors.actions.viewEvent).dataset.eventId,eventId?(e.preventDefault(),e.stopPropagation(),renderEventSummaryModal(eventId).then(pendingPromise.resolve).catch()):pendingPromise.resolve()})),root.on("click",CalendarSelectors.links.navLink,(e=>{const wrapper=root.find(CalendarSelectors.wrapper),view=wrapper.data("view"),courseId=wrapper.data("courseid"),categoryId=wrapper.data("categoryid"),link=e.currentTarget;"month"===view||"monthblock"===view?(changeMonth(root,link.href,link.dataset.year,link.dataset.month,courseId,categoryId,link.dataset.day),e.preventDefault()):"day"===view&&(changeDay(root,link.href,link.dataset.year,link.dataset.month,link.dataset.day,courseId,categoryId),e.preventDefault())}));const viewSelector=root.find(CalendarSelectors.viewSelector);_custom_interaction_events.default.define(viewSelector,[_custom_interaction_events.default.events.activate]),viewSelector.on(_custom_interaction_events.default.events.activate,(e=>{e.preventDefault();const option=e.target;if(option.classList.contains("active"))return;const view=option.dataset.view,year=option.dataset.year,month=option.dataset.month,day=option.dataset.day,courseId=option.dataset.courseid,categoryId=option.dataset.categoryid;"month"==view?refreshMonthContent(root,year,month,courseId,categoryId,root,"core_calendar/calendar_month",day).then((()=>{updateUrl("?view=month")})).fail(_notification.default.exception):"day"==view?refreshDayContent(root,year,month,day,courseId,categoryId,root,"core_calendar/calendar_day").then((()=>{updateUrl("?view=day")})).fail(_notification.default.exception):"upcoming"==view&&reloadCurrentUpcoming(root,courseId,categoryId,root,"core_calendar/calendar_upcoming").then((()=>{updateUrl("?view=upcoming")})).fail(_notification.default.exception)}))})(root);const calendarTable=root.find(CalendarSelectors.elements.monthDetailed);if(calendarTable.length){"month-detailed-".concat(calendarTable.id,"-filterChanged");registerEventListenersForMonthDetailed(calendarTable)}}})); /** * Module to manage content bank actions, such as delete or rename. * * @module core_contentbank/actions * @copyright 2020 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_contentbank/actions",["jquery","core/ajax","core/notification","core/str","core/templates","core/url","core/modal_factory","core/modal_events"],(function($,Ajax,Notification,Str,Templates,Url,ModalFactory,ModalEvents){var ACTIONS_DELETE_CONTENT='[data-action="deletecontent"]',ACTIONS_RENAME_CONTENT='[data-action="renamecontent"]',ACTIONS_SET_CONTENT_VISIBILITY='[data-action="setcontentvisibility"]',Actions=function(){this.registerEvents()};return Actions.prototype.registerEvents=function(){$(ACTIONS_DELETE_CONTENT).click((function(e){e.preventDefault();var contentname=$(this).data("contentname"),contentuses=$(this).data("uses"),contentid=$(this).data("contentid"),contextid=$(this).data("contextid"),strings=[{key:"deletecontent",component:"core_contentbank"},{key:"deletecontentconfirm",component:"core_contentbank",param:{name:contentname}},{key:"deletecontentconfirmlinked",component:"core_contentbank"},{key:"delete",component:"core"}],deleteButtonText="";Str.get_strings(strings).then((function(langStrings){var modalTitle=langStrings[0],modalContent=langStrings[1];return contentuses>0&&(modalContent+=" "+langStrings[2]),deleteButtonText=langStrings[3],ModalFactory.create({title:modalTitle,body:modalContent,type:ModalFactory.types.SAVE_CANCEL,large:!0})})).done((function(modal){modal.setSaveButtonText(deleteButtonText),modal.getRoot().on(ModalEvents.save,(function(){return function(contentid,contextid){var request={methodname:"core_contentbank_delete_content",args:{contentids:{contentid:contentid}}},requestType="success";Ajax.call([request])[0].then((function(data){return data.result?"contentdeleted":(requestType="error","contentnotdeleted")})).done((function(message){var params={contextid:contextid};"success"==requestType?params.statusmsg=message:params.errormsg=message,window.location.href=Url.relativeUrl("contentbank/index.php",params,!1)})).fail(Notification.exception)}(contentid,contextid)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show()})).catch(Notification.exception)})),$(ACTIONS_RENAME_CONTENT).click((function(e){e.preventDefault();var contentname=$(this).data("contentname"),contentid=$(this).data("contentid"),saveButtonText="";Str.get_strings([{key:"renamecontent",component:"core_contentbank"},{key:"rename",component:"core_contentbank"}]).then((function(langStrings){var modalTitle=langStrings[0];return saveButtonText=langStrings[1],ModalFactory.create({title:modalTitle,body:Templates.render("core_contentbank/renamecontent",{contentid:contentid,name:contentname}),type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){modal.setSaveButtonText(saveButtonText),modal.getRoot().on(ModalEvents.save,(function(e){var newname=$("#newname").val().trim();if(newname)!function(contentid,name){var request={methodname:"core_contentbank_rename_content",args:{contentid:contentid,name:name}},requestType="success";Ajax.call([request])[0].then((function(data){return data.result?"contentrenamed":(requestType="error",data.warnings[0].message)})).then((function(message){var params=null;"success"==requestType?(params={id:contentid,statusmsg:message},window.location.href=Url.relativeUrl("contentbank/view.php",params,!1)):(Notification.addNotification({message:message,type:"error"}),Notification.fetchNotifications())})).catch(Notification.exception)}(contentid,newname);else{Str.get_strings([{key:"error"},{key:"emptynamenotallowed",component:"core_contentbank"}]).then((function(langStrings){Notification.alert(langStrings[0],langStrings[1])})).catch(Notification.exception),e.preventDefault()}})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show()})).catch(Notification.exception)})),$(ACTIONS_SET_CONTENT_VISIBILITY).click((function(e){e.preventDefault(),function(contentid,visibility){var request={methodname:"core_contentbank_set_content_visibility",args:{contentid:contentid,visibility:visibility}},requestType="success";Ajax.call([request])[0].then((function(data){return data.result?"contentvisibilitychanged":(requestType="error",data.warnings[0].message)})).then((function(message){var params=null;"success"==requestType?(params={id:contentid,statusmsg:message},window.location.href=Url.relativeUrl("contentbank/view.php",params,!1)):(Notification.addNotification({message:message,type:"error"}),Notification.fetchNotifications())})).catch(Notification.exception)}($(this).data("contentid"),$(this).data("visibility"))}))},{init:function(){return new Actions}}})); define("core_contentbank/search",["exports","jquery","core_contentbank/selectors","core/str","core/pending","core/utils"],(function(_exports,_jquery,_selectors,_str,_pending,_utils){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Search methods for finding contents in the content bank. * * @module core_contentbank/search * @copyright 2020 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_selectors=_interopRequireDefault(_selectors),_pending=_interopRequireDefault(_pending);_exports.init=()=>{const pendingPromise=new _pending.default,root=(0,_jquery.default)(_selectors.default.regions.contentbank);registerListenerEvents(root),pendingPromise.resolve()};const registerListenerEvents=root=>{const searchInput=root.find(_selectors.default.elements.searchinput)[0];root.on("click",_selectors.default.actions.search,(function(e){e.preventDefault(),toggleSearchResultsView(root,searchInput.value)})),root.on("click",_selectors.default.actions.clearSearch,(function(e){e.preventDefault(),searchInput.value="",searchInput.focus(),toggleSearchResultsView(root,searchInput.value)})),searchInput.addEventListener("input",(0,_utils.debounce)((()=>{toggleSearchResultsView(root,searchInput.value)}),300))},toggleSearchResultsView=async(body,searchQuery)=>{const clearSearchButton=body.find(_selectors.default.actions.clearSearch)[0],navbarBreadcrumb=body.find(_selectors.default.elements.cbnavbarbreadcrumb)[0],navbarTotal=body.find(_selectors.default.elements.cbnavbartotalsearch)[0],filteredContents=filterContents(body,searchQuery);searchQuery.length>0?(clearSearchButton.classList.remove("d-none"),navbarBreadcrumb.classList.add("d-none"),navbarTotal.innerHTML=await(0,_str.get_string)("itemsfound","core_contentbank",filteredContents.length),navbarTotal.classList.remove("d-none")):(clearSearchButton.classList.add("d-none"),navbarBreadcrumb.classList.remove("d-none"),navbarTotal.classList.add("d-none"))},filterContents=(body,searchTerm)=>{const contents=Array.from(body.find(_selectors.default.elements.listitem)),searchResults=[];return contents.forEach((content=>{const contentName=content.getAttribute("data-name");if(""===searchTerm||contentName.toLowerCase().includes(searchTerm.toLowerCase())){searchResults.push(content);content.querySelector(_selectors.default.regions.cbcontentname).innerHTML=highlight(contentName,searchTerm),content.classList.remove("d-none")}else content.classList.add("d-none")})),searchResults},highlight=(text,highlightText)=>{let result=text;if(""!==highlightText){const pos=text.toLowerCase().indexOf(highlightText.toLowerCase());pos>-1&&(result=text.substr(0,pos)+'<span class="matchtext">'+text.substr(pos,highlightText.length)+"</span>"+text.substr(pos+highlightText.length))}return result}})); define("core_contentbank/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Define all of the selectors we will be using on the contentbank interface. * * @module core_contentbank/selectors * @copyright 2020 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const getDataSelector=(name,value)=>"[data-".concat(name,'="').concat(value,'"]');var _default={regions:{cbcontentname:getDataSelector("region","cb-content-name"),contentbank:getDataSelector("region","contentbank"),filearea:getDataSelector("region","filearea")},actions:{search:getDataSelector("action","searchcontent"),clearSearch:getDataSelector("action","clearsearch"),viewgrid:getDataSelector("action","viewgrid"),viewlist:getDataSelector("action","viewlist"),sortname:getDataSelector("action","sortname"),sortuses:getDataSelector("action","sortuses"),sortdate:getDataSelector("action","sortdate"),sortsize:getDataSelector("action","sortsize"),sorttype:getDataSelector("action","sorttype"),sortauthor:getDataSelector("action","sortauthor")},elements:{listitem:".cb-listitem",heading:".cb-heading",cell:".cb-column",cbnavbarbreadcrumb:".cb-navbar-breadbrumb",cbnavbartotalsearch:".cb-navbar-totalsearch",searchinput:'[role="searchbox"]',sortbutton:".cb-btnsort"}};return _exports.default=_default,_exports.default})); define("core_contentbank/sort",["exports","./selectors","core/str","core/prefetch","core/ajax","core/notification"],(function(_exports,_selectors,_str,_prefetch,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Content bank UI actions. * * @module core_contentbank/sort * @copyright 2020 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_selectors=_interopRequireDefault(_selectors),_prefetch=_interopRequireDefault(_prefetch),_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);_exports.init=()=>{const contentBank=document.querySelector(_selectors.default.regions.contentbank);_prefetch.default.prefetchStrings("contentbank",["contentname","uses","lastmodified","size","type","author"]),_prefetch.default.prefetchStrings("moodle",["sortbyx","sortbyxreverse"]),registerListenerEvents(contentBank)};const registerListenerEvents=contentBank=>{contentBank.addEventListener("click",(e=>{const viewList=contentBank.querySelector(_selectors.default.actions.viewlist),viewGrid=contentBank.querySelector(_selectors.default.actions.viewgrid),fileArea=contentBank.querySelector(_selectors.default.regions.filearea),shownItems=fileArea.querySelectorAll(_selectors.default.elements.listitem);if(e.target.closest(_selectors.default.actions.viewgrid)){if(contentBank.classList.remove("view-list"),contentBank.classList.add("view-grid"),fileArea&&shownItems){fileArea.setAttribute("role","list"),shownItems.forEach((listItem=>{listItem.setAttribute("role","listitem"),listItem.querySelectorAll(_selectors.default.elements.cell).forEach((cell=>cell.removeAttribute("role")))}));const heading=fileArea.querySelector(_selectors.default.elements.heading);heading&&(heading.removeAttribute("role"),heading.querySelectorAll(_selectors.default.elements.cell).forEach((cell=>cell.removeAttribute("role"))))}return viewGrid.classList.add("active"),viewList.classList.remove("active"),void setViewListPreference(!1)}if(e.target.closest(_selectors.default.actions.viewlist)){if(contentBank.classList.remove("view-grid"),contentBank.classList.add("view-list"),fileArea&&shownItems){fileArea.setAttribute("role","table"),shownItems.forEach((listItem=>{listItem.setAttribute("role","row"),listItem.querySelectorAll(_selectors.default.elements.cell).forEach((cell=>cell.setAttribute("role","cell")))}));const heading=fileArea.querySelector(_selectors.default.elements.heading);heading&&(heading.setAttribute("role","row"),heading.querySelectorAll(_selectors.default.elements.cell).forEach((cell=>cell.setAttribute("role","columnheader"))))}return viewList.classList.add("active"),viewGrid.classList.remove("active"),void setViewListPreference(!0)}if(fileArea&&shownItems){const sortByName=e.target.closest(_selectors.default.actions.sortname);if(sortByName){const ascending=updateSortButtons(contentBank,sortByName);return void updateSortOrder(fileArea,shownItems,"data-file",ascending)}const sortByUses=e.target.closest(_selectors.default.actions.sortuses);if(sortByUses){const ascending=updateSortButtons(contentBank,sortByUses);return void updateSortOrder(fileArea,shownItems,"data-uses",ascending)}const sortByDate=e.target.closest(_selectors.default.actions.sortdate);if(sortByDate){const ascending=updateSortButtons(contentBank,sortByDate);return void updateSortOrder(fileArea,shownItems,"data-timemodified",ascending)}const sortBySize=e.target.closest(_selectors.default.actions.sortsize);if(sortBySize){const ascending=updateSortButtons(contentBank,sortBySize);return void updateSortOrder(fileArea,shownItems,"data-bytes",ascending)}const sortByType=e.target.closest(_selectors.default.actions.sorttype);if(sortByType){const ascending=updateSortButtons(contentBank,sortByType);return void updateSortOrder(fileArea,shownItems,"data-type",ascending)}const sortByAuthor=e.target.closest(_selectors.default.actions.sortauthor);if(sortByAuthor){const ascending=updateSortButtons(contentBank,sortByAuthor);updateSortOrder(fileArea,shownItems,"data-author",ascending)}}else;}))},setViewListPreference=function(viewList){!1===viewList&&(viewList=null);const request={methodname:"core_user_update_user_preferences",args:{preferences:[{type:"core_contentbank_view_list",value:viewList}]}};return _ajax.default.call([request])[0].catch(_notification.default.exception)},updateSortButtons=(contentBank,sortButton)=>{contentBank.querySelectorAll(_selectors.default.elements.sortbutton).forEach((button=>{button!==sortButton&&(button.classList.remove("dir-asc"),button.classList.remove("dir-desc"),button.classList.add("dir-none"),button.closest(_selectors.default.elements.cell).setAttribute("aria-sort","none"),updateButtonTitle(button,!1))}));let ascending=!0;return sortButton.classList.contains("dir-none")?(sortButton.classList.remove("dir-none"),sortButton.classList.add("dir-asc"),sortButton.closest(_selectors.default.elements.cell).setAttribute("aria-sort","ascending")):sortButton.classList.contains("dir-asc")?(sortButton.classList.remove("dir-asc"),sortButton.classList.add("dir-desc"),sortButton.closest(_selectors.default.elements.cell).setAttribute("aria-sort","descending"),ascending=!1):sortButton.classList.contains("dir-desc")&&(sortButton.classList.remove("dir-desc"),sortButton.classList.add("dir-asc"),sortButton.closest(_selectors.default.elements.cell).setAttribute("aria-sort","ascending")),updateButtonTitle(sortButton,ascending),ascending},updateButtonTitle=(button,ascending)=>{const sortString=ascending?"sortbyxreverse":"sortbyx";return(0,_str.get_string)(button.dataset.string,"contentbank").then((columnName=>(0,_str.get_string)(sortString,"core",columnName))).then((sortByString=>(button.setAttribute("title",sortByString),sortByString))).catch()},updateSortOrder=(fileArea,itemList,attribute,ascending)=>{[].slice.call(itemList).sort((function(a,b){let aa=a.getAttribute(attribute),bb=b.getAttribute(attribute);return isNaN(aa)||(aa=parseInt(aa),bb=parseInt(bb)),ascending?aa>bb?1:-1:aa<bb?1:-1})).forEach((listItem=>fileArea.appendChild(listItem)))}})); define("core_contentbank/upload",["exports","core_form/modalform","core/str"],(function(_exports,_modalform,_str){var obj; /** * Module to handle AJAX interactions with content bank upload files. * * @module core_contentbank/upload * @copyright 2021 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initModal=void 0,_modalform=(obj=_modalform)&&obj.__esModule?obj:{default:obj};_exports.initModal=(elementSelector,formClass,contextId,contentId)=>{document.querySelector(elementSelector).addEventListener("click",(function(e){e.preventDefault();const form=new _modalform.default({formClass:formClass,args:{contextid:contextId,id:contentId},modalConfig:{title:(0,_str.get_string)("upload","contentbank")},returnFocus:e.target});form.addEventListener(form.events.FORM_SUBMITTED,(event=>{document.location=event.detail.returnurl})),form.show()}))}})); /** * This module provides the course copy modal from the course and * category management screen. * * @module core_course/copy_modal * @copyright 2020 onward The Moodle Users Association <https://moodleassociation.org/> * @author Matt Porritt <mattp@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.9 */ define("core_course/copy_modal",["jquery","core/str","core/modal_factory","core/modal_events","core/ajax","core/fragment","core/notification","core/config"],(function($,Str,ModalFactory,ModalEvents,ajax,Fragment,Notification,Config){var contextid,course,modalObj,CopyModal={},spinner='<p class="text-center"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></p>';function updateModalBody(formdata){void 0===formdata&&(formdata={});var params={jsonformdata:JSON.stringify(formdata),courseid:course.id};modalObj.setBody(spinner),Str.get_string("copycoursetitle","backup",course.shortname).then((function(title){modalObj.setTitle(title),modalObj.setBody(Fragment.loadFragment("course","new_base_form",contextid,params))})).catch((function(){Notification.exception(new Error("Failed to load string: copycoursetitle"))}))}function processModalForm(e){e.preventDefault();var copyform=modalObj.getRoot().find("form").serialize(),formjson=JSON.stringify(copyform),invalid=$.merge(modalObj.getRoot().find('[aria-invalid="true"]'),modalObj.getRoot().find(".error"));invalid.length?invalid.first().focus():ajax.call([{methodname:"core_backup_submit_copy_form",args:{jsonformdata:formjson}}])[0].done((function(){if(modalObj.setBody(spinner),modalObj.hide(),1==e.formredirect){let redirect=Config.wwwroot+"/backup/copyprogress.php?id="+course.id;window.location.assign(redirect)}})).fail((function(){updateModalBody(copyform)}))}return CopyModal.init=function(context){contextid=context,Str.get_string("loading").then((function(title){ModalFactory.create({type:ModalFactory.types.DEFAULT,title:title,body:spinner,large:!0}).done((function(modal){(modalObj=modal).getRoot().on("click","#id_submitreturn",processModalForm),modalObj.getRoot().on("click","#id_submitdisplay",(function(e){e.formredirect=!0,processModalForm(e)})),modalObj.getRoot().on("click","#id_cancel",(function(e){e.preventDefault(),modalObj.setBody(spinner),modalObj.hide()}))}))})).catch((function(){Notification.exception(new Error("Failed to load string: loading"))})),$(".action-copy").on("click",(function(e){e.preventDefault();let url=new URL(this.getAttribute("href")),courseid=new URLSearchParams(url.search).get("id");ajax.call([{methodname:"core_course_get_courses",args:{options:{ids:[courseid]}}}])[0].done((function(response){course=response[0],updateModalBody()})).fail((function(){Notification.exception(new Error("Failed to load course"))})),modalObj.show()}))},CopyModal})); define("core_course/downloadcontent",["exports","core/config","core/custom_interaction_events","core/modal_factory","jquery","core/pending","core/key_codes"],(function(_exports,_config,_custom_interaction_events,ModalFactory,_jquery,_pending,_key_codes){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Functions related to downloading course content. * * @module core_course/downloadcontent * @copyright 2020 Michael Hawkins <michaelh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_config=_interopRequireDefault(_config),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),ModalFactory=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(ModalFactory),_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending);_exports.init=()=>{const pendingPromise=new _pending.default;(0,_jquery.default)("[data-downloadcourse]").on("click keydown",(e=>{"click"!==e.type&&e.which!==_key_codes.enter&&e.which!==_key_codes.space||(e.preventDefault(),displayDownloadConfirmation(e.currentTarget))})),pendingPromise.resolve()};const displayDownloadConfirmation=downloadModalTrigger=>{ModalFactory.create({title:downloadModalTrigger.dataset.downloadTitle,type:ModalFactory.types.SAVE_CANCEL,body:"<p>".concat(downloadModalTrigger.dataset.downloadBody,"</p>"),buttons:{save:downloadModalTrigger.dataset.downloadButtonText},templateContext:{classes:"downloadcoursecontentmodal"}}).then((modal=>{modal.show();const saveButton=document.querySelector('.modal .downloadcoursecontentmodal [data-action="save"]'),cancelButton=document.querySelector('.modal .downloadcoursecontentmodal [data-action="cancel"]'),modalContainer=document.querySelector('.modal[data-region="modal-container"]');(0,_jquery.default)(saveButton).on(_custom_interaction_events.default.events.activate,(e=>downloadContent(e,downloadModalTrigger,modal))),(0,_jquery.default)(cancelButton).on(_custom_interaction_events.default.events.activate,(()=>{modal.destroy()})),modalContainer.querySelector(".downloadcoursecontentmodal")&&(0,_jquery.default)(modalContainer).on(_custom_interaction_events.default.events.activate,(()=>{modal.destroy()}))}))},downloadContent=(e,downloadModalTrigger,modal)=>{e.preventDefault();const downloadForm=document.createElement("form");downloadForm.action=downloadModalTrigger.dataset.downloadLink,downloadForm.method="POST",downloadForm.target="_blank";const downloadSesskey=document.createElement("input");downloadSesskey.name="sesskey",downloadSesskey.value=_config.default.sesskey,downloadForm.appendChild(downloadSesskey),downloadForm.style.display="none",document.body.appendChild(downloadForm),downloadForm.submit(),document.body.removeChild(downloadForm),modal.destroy()}})); define("core_course/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={favourited:"core_course:favourited",unfavorited:"core_course:unfavorited",manualCompletionToggled:"core_course:manualcompletiontoggled",stateChanged:"core_course:stateChanged",sectionRefreshed:"core_course:sectionRefreshed"},_exports.default})); define("core_course/formatchooser",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Course format selection handler. * * @module core_course/formatchooser * @copyright 2022 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */ const Selectors_fields={selector:'[data-formatchooser-field="selector"]',updateButton:'[data-formatchooser-field="updateButton"]'};_exports.init=()=>{document.querySelector(Selectors_fields.selector).addEventListener("change",(e=>{const form=e.target.closest("form"),updateButton=form.querySelector(Selectors_fields.updateButton),fieldset=updateButton.closest("fieldset"),url=new URL(form.action);url.hash=fieldset.id,form.action=url.toString(),updateButton.click()}))}})); define("core_course/local/activitychooser/dialogue",["exports","jquery","core/modal_events","core_course/local/activitychooser/selectors","core/templates","core/key_codes","core/loadingicon","core_course/local/activitychooser/repository","core/notification","core/utils"],(function(_exports,_jquery,ModalEvents,_selectors,Templates,_key_codes,_loadingicon,Repository,_notification,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.displayChooser=void 0,_jquery=_interopRequireDefault(_jquery),ModalEvents=_interopRequireWildcard(ModalEvents),_selectors=_interopRequireDefault(_selectors),Templates=_interopRequireWildcard(Templates),Repository=_interopRequireWildcard(Repository),_notification=_interopRequireDefault(_notification);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const showModuleHelp=function(carousel,moduleData){let modal=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;null!==modal&&!0===moduleData.showFooter&&modal.setFooter(Templates.render("core_course/local/activitychooser/footer_partial",moduleData));const help=carousel.find(_selectors.default.regions.help)[0];help.innerHTML="",help.classList.add("m-auto");const spinnerPromise=(0,_loadingicon.addIconToContainer)(help);let transitionPromiseResolver=null;const transitionPromise=new Promise((resolve=>{transitionPromiseResolver=resolve})),contentPromise=Templates.renderForPromise("core_course/local/activitychooser/help",moduleData);Promise.all([contentPromise,spinnerPromise,transitionPromise]).then((_ref=>{let[{html:html,js:js}]=_ref;return Templates.replaceNodeContents(help,html,js)})).then((()=>(help.querySelector(_selectors.default.regions.chooserSummary.header).focus(),help))).catch(_notification.default.exception),carousel.one("slid.bs.carousel",(()=>{transitionPromiseResolver()})),carousel.carousel("next")},registerListenerEvents=(modal,mappedModules,partialFavourite,footerData)=>{const bodyClickListener=async e=>{if(e.target.closest(_selectors.default.actions.optionActions.showSummary)){const carousel=(0,_jquery.default)(modal.getBody()[0].querySelector(_selectors.default.regions.carousel)),moduleName=e.target.closest(_selectors.default.regions.chooserOption.container).dataset.modname,moduleData=mappedModules.get(moduleName);moduleData.showFooter=modal.hasFooterContent(),showModuleHelp(carousel,moduleData,modal)}if(e.target.closest(_selectors.default.actions.optionActions.manageFavourite)){const caller=e.target.closest(_selectors.default.actions.optionActions.manageFavourite);await(async(modalBody,caller,partialFavourite)=>{const isFavourite=caller.dataset.favourited,id=caller.dataset.id,name=caller.dataset.name,internal=caller.dataset.internal;"true"===isFavourite?(await Repository.unfavouriteModule(name,id),partialFavourite(internal,!1,modalBody)):(await Repository.favouriteModule(name,id),partialFavourite(internal,!0,modalBody))})(modal.getBody()[0],caller,partialFavourite);const activeSectionId=modal.getBody()[0].querySelector(_selectors.default.elements.activetab).getAttribute("href"),sectionChooserOptions=modal.getBody()[0].querySelector(_selectors.default.regions.getSectionChooserOptions(activeSectionId)),firstChooserOption=sectionChooserOptions.querySelector(_selectors.default.regions.chooserOption.container);toggleFocusableChooserOption(firstChooserOption,!0),initChooserOptionsKeyboardNavigation(modal.getBody()[0],mappedModules,sectionChooserOptions,modal)}if(e.target.matches(_selectors.default.actions.closeOption)){const carousel=(0,_jquery.default)(modal.getBody()[0].querySelector(_selectors.default.regions.carousel));carousel.carousel("prev"),carousel.on("slid.bs.carousel",(()=>{modal.getBody()[0].querySelector(_selectors.default.regions.modules).querySelector(_selectors.default.regions.getModuleSelector(e.target.dataset.modname)).focus()}))}if(e.target.closest(_selectors.default.actions.clearSearch)){const searchInput=modal.getBody()[0].querySelector(_selectors.default.actions.search);searchInput.value="",searchInput.focus(),toggleSearchResultsView(modal,mappedModules,searchInput.value)}},footerClickListener=async e=>{if(!0===footerData.footer){const footerjs=await(pluginName=footerData.customfooterjs,"function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require([pluginName],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require(pluginName)):Promise.resolve(_systemImportTransformerGlobalIdentifier[pluginName]));await footerjs.footerClickListener(e,footerData,modal)}var pluginName};modal.getBodyPromise().then((body=>body[0])).then((body=>((0,_jquery.default)(body.querySelector(_selectors.default.regions.carousel)).carousel({interval:!1,pause:!0,keyboard:!1}),body))).then((body=>(body.addEventListener("click",bodyClickListener),body))).then((body=>{const searchInput=body.querySelector(_selectors.default.actions.search);return searchInput.addEventListener("input",(0,_utils.debounce)((()=>{toggleSearchResultsView(modal,mappedModules,searchInput.value)}),300)),body})).then((body=>{const activeSectionId=body.querySelector(_selectors.default.elements.activetab).getAttribute("href"),sectionChooserOptions=body.querySelector(_selectors.default.regions.getSectionChooserOptions(activeSectionId)),firstChooserOption=sectionChooserOptions.querySelector(_selectors.default.regions.chooserOption.container);return toggleFocusableChooserOption(firstChooserOption,!0),initChooserOptionsKeyboardNavigation(body,mappedModules,sectionChooserOptions,modal),body})).catch(),modal.getFooterPromise().then((footer=>footer[0])).then((footer=>(footer.addEventListener("click",footerClickListener),footer))).catch()},initChooserOptionsKeyboardNavigation=function(body,mappedModules,chooserOptionsContainer){let modal=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;const chooserOptions=chooserOptionsContainer.querySelectorAll(_selectors.default.regions.chooserOption.container);Array.from(chooserOptions).forEach((element=>element.addEventListener("keydown",(e=>{if((e.keyCode===_key_codes.enter||e.keyCode===_key_codes.space)&&e.target.matches(_selectors.default.actions.optionActions.showSummary)){e.preventDefault();const moduleName=e.target.closest(_selectors.default.regions.chooserOption.container).dataset.modname,moduleData=mappedModules.get(moduleName),carousel=(0,_jquery.default)(body.querySelector(_selectors.default.regions.carousel));carousel.carousel({interval:!1,pause:!0,keyboard:!1}),moduleData.showFooter=modal.hasFooterContent(),showModuleHelp(carousel,moduleData,modal)}if(e.keyCode===_key_codes.arrowRight){e.preventDefault();const currentOption=e.target.closest(_selectors.default.regions.chooserOption.container),nextOption=currentOption.nextElementSibling,firstOption=chooserOptionsContainer.firstElementChild,toFocusOption=clickErrorHandler(nextOption,firstOption);focusChooserOption(toFocusOption,currentOption)}if(e.keyCode===_key_codes.arrowLeft){e.preventDefault();const currentOption=e.target.closest(_selectors.default.regions.chooserOption.container),previousOption=currentOption.previousElementSibling,lastOption=chooserOptionsContainer.lastElementChild,toFocusOption=clickErrorHandler(previousOption,lastOption);focusChooserOption(toFocusOption,currentOption)}if(e.keyCode===_key_codes.home){e.preventDefault();const currentOption=e.target.closest(_selectors.default.regions.chooserOption.container),firstOption=chooserOptionsContainer.firstElementChild;focusChooserOption(firstOption,currentOption)}if(e.keyCode===_key_codes.end){e.preventDefault();const currentOption=e.target.closest(_selectors.default.regions.chooserOption.container),lastOption=chooserOptionsContainer.lastElementChild;focusChooserOption(lastOption,currentOption)}}))))},focusChooserOption=function(currentChooserOption){let previousChooserOption=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;null!==previousChooserOption&&toggleFocusableChooserOption(previousChooserOption,!1),toggleFocusableChooserOption(currentChooserOption,!0),currentChooserOption.focus()},toggleFocusableChooserOption=(chooserOption,isFocusable)=>{const chooserOptionLink=chooserOption.querySelector(_selectors.default.actions.addChooser),chooserOptionHelp=chooserOption.querySelector(_selectors.default.actions.optionActions.showSummary),chooserOptionFavourite=chooserOption.querySelector(_selectors.default.actions.optionActions.manageFavourite);isFocusable?(chooserOption.tabIndex=0,chooserOptionLink.tabIndex=0,chooserOptionHelp.tabIndex=0,chooserOptionFavourite.tabIndex=0):(chooserOption.tabIndex=-1,chooserOptionLink.tabIndex=-1,chooserOptionHelp.tabIndex=-1,chooserOptionFavourite.tabIndex=-1)},clickErrorHandler=(item,fallback)=>null!==item?item:fallback,toggleSearchResultsView=async(modal,mappedModules,searchQuery)=>{const modalBody=modal.getBody()[0],searchResultsContainer=modalBody.querySelector(_selectors.default.regions.searchResults),chooserContainer=modalBody.querySelector(_selectors.default.regions.chooser),clearSearchButton=modalBody.querySelector(_selectors.default.actions.clearSearch);if(searchQuery.length>0){const searchResultsData=searchModules(mappedModules,searchQuery);await(async(searchResultsContainer,searchResultsData)=>{const templateData={searchresultsnumber:searchResultsData.length,searchresults:searchResultsData},{html:html,js:js}=await Templates.renderForPromise("core_course/local/activitychooser/search_results",templateData);await Templates.replaceNodeContents(searchResultsContainer,html,js)})(searchResultsContainer,searchResultsData);const searchResultItemsContainer=searchResultsContainer.querySelector(_selectors.default.regions.searchResultItems),firstSearchResultItem=searchResultItemsContainer.querySelector(_selectors.default.regions.chooserOption.container);firstSearchResultItem&&(toggleFocusableChooserOption(firstSearchResultItem,!0),initChooserOptionsKeyboardNavigation(modalBody,mappedModules,searchResultItemsContainer,modal)),clearSearchButton.classList.remove("d-none"),chooserContainer.setAttribute("hidden","hidden"),searchResultsContainer.removeAttribute("hidden")}else clearSearchButton.classList.add("d-none"),searchResultsContainer.setAttribute("hidden","hidden"),chooserContainer.removeAttribute("hidden")},searchModules=(modules,searchTerm)=>{if(""===searchTerm)return modules;searchTerm=searchTerm.toLowerCase();const searchResults=[];return modules.forEach((activity=>{const activityName=activity.title.toLowerCase(),activityDesc=activity.help.toLowerCase();(activityName.includes(searchTerm)||activityDesc.includes(searchTerm))&&searchResults.push(activity)})),searchResults},disableFocusAllChooserOptions=sectionChooserOptions=>{sectionChooserOptions.querySelectorAll(_selectors.default.regions.chooserOption.container).forEach((chooserOption=>{toggleFocusableChooserOption(chooserOption,!1)}))};_exports.displayChooser=(modalPromise,sectionModules,partialFavourite,footerData)=>{const mappedModules=new Map;sectionModules.forEach((module=>{mappedModules.set(module.componentname+"_"+module.link,module)})),modalPromise.then((modal=>(registerListenerEvents(modal,mappedModules,partialFavourite,footerData),((modal,mappedModules)=>{modal.getModal()[0].tabIndex=-1,modal.getBodyPromise().then((body=>{(0,_jquery.default)(_selectors.default.elements.tab).on("shown.bs.tab",(e=>{const activeSectionId=e.target.getAttribute("href"),activeSectionChooserOptions=body[0].querySelector(_selectors.default.regions.getSectionChooserOptions(activeSectionId)),firstChooserOption=activeSectionChooserOptions.querySelector(_selectors.default.regions.chooserOption.container),prevActiveSectionId=e.relatedTarget.getAttribute("href"),prevActiveSectionChooserOptions=body[0].querySelector(_selectors.default.regions.getSectionChooserOptions(prevActiveSectionId));disableFocusAllChooserOptions(prevActiveSectionChooserOptions),toggleFocusableChooserOption(firstChooserOption,!0),initChooserOptionsKeyboardNavigation(body[0],mappedModules,activeSectionChooserOptions,modal)}))})).catch(_notification.default.exception)})(modal,mappedModules),modal.getRoot().on(ModalEvents.hidden,(()=>{modal.destroy()})),modal))).catch()}})); define("core_course/local/activitychooser/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * * @module core_course/repository * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.unfavouriteModule=_exports.fetchFooterData=_exports.favouriteModule=_exports.activityModules=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.activityModules=courseid=>{const request={methodname:"core_course_get_course_content_items",args:{courseid:courseid}};return _ajax.default.call([request])[0]};_exports.favouriteModule=(modName,modID)=>{const request={methodname:"core_course_add_content_item_to_user_favourites",args:{componentname:modName,contentitemid:modID}};return _ajax.default.call([request])[0]};_exports.unfavouriteModule=(modName,modID)=>{const request={methodname:"core_course_remove_content_item_from_user_favourites",args:{componentname:modName,contentitemid:modID}};return _ajax.default.call([request])[0]};_exports.fetchFooterData=(courseid,sectionid)=>{const request={methodname:"core_course_get_activity_chooser_footer",args:{courseid:courseid,sectionid:sectionid}};return _ajax.default.call([request])[0]}})); define("core_course/local/activitychooser/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Define all of the selectors we will be using on the grading interface. * * @module core_course/local/chooser/selectors * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const getDataSelector=(name,value)=>"[data-".concat(name,'="').concat(value,'"]');var _default={regions:{chooser:getDataSelector("region","chooser-container"),getSectionChooserOptions:containerid=>"".concat(containerid," ").concat(getDataSelector("region","chooser-options-container")),chooserOption:{container:getDataSelector("region","chooser-option-container"),actions:getDataSelector("region","chooser-option-actions-container"),info:getDataSelector("region","chooser-option-info-container")},chooserSummary:{container:getDataSelector("region","chooser-option-summary-container"),content:getDataSelector("region","chooser-option-summary-content-container"),header:getDataSelector("region","summary-header"),actions:getDataSelector("region","chooser-option-summary-actions-container")},carousel:getDataSelector("region","carousel"),help:getDataSelector("region","help"),modules:getDataSelector("region","modules"),favouriteTabNav:getDataSelector("region","favourite-tab-nav"),defaultTabNav:getDataSelector("region","default-tab-nav"),activityTabNav:getDataSelector("region","activity-tab-nav"),favouriteTab:getDataSelector("region","favourites"),recommendedTab:getDataSelector("region","recommended"),defaultTab:getDataSelector("region","default"),activityTab:getDataSelector("region","activity"),resourceTab:getDataSelector("region","resources"),getModuleSelector:modname=>'[role="menuitem"][data-modname="'.concat(modname,'"]'),searchResults:getDataSelector("region","search-results-container"),searchResultItems:getDataSelector("region","search-result-items-container")},actions:{optionActions:{showSummary:getDataSelector("action","show-option-summary"),manageFavourite:getDataSelector("action","manage-module-favourite")},addChooser:getDataSelector("action","add-chooser-option"),closeOption:getDataSelector("action","close-chooser-option-summary"),hide:getDataSelector("action","hide"),search:getDataSelector("action","search"),clearSearch:getDataSelector("action","clearsearch")},render:{favourites:getDataSelector("render","favourites-area")},elements:{section:".section",sectionmodchooser:"button.section-modchooser-link",sitemenu:".block_site_main_menu",sitetopic:"div.sitetopic",tab:'a[data-toggle="tab"]',activetab:'a[data-toggle="tab"][aria-selected="true"]',visibletabs:'a[data-toggle="tab"]:not(.d-none)'}};return _exports.default=_default,_exports.default})); define("core_course/manual_completion_toggle",["exports","core/templates","core/notification","core_course/repository","core_course/events","core/pending"],(function(_exports,_templates,_notification,_repository,CourseEvents,_pending){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Provides the functionality for toggling the manual completion state of a course module through * the manual completion button. * * @module core_course/manual_completion_toggle * @copyright 2021 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_templates=_interopRequireDefault(_templates),_notification=_interopRequireDefault(_notification),CourseEvents=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(CourseEvents),_pending=_interopRequireDefault(_pending);const SELECTORS_MANUAL_TOGGLE="button[data-action=toggle-manual-completion]",TOGGLE_TYPES_TOGGLE_MARK_DONE="manual:mark-done";let registered=!1;_exports.init=()=>{registered||(document.addEventListener("click",(e=>{const toggleButton=e.target.closest(SELECTORS_MANUAL_TOGGLE);toggleButton&&(e.preventDefault(),toggleManualCompletionState(toggleButton).catch(_notification.default.exception))})),registered=!0)};const toggleManualCompletionState=async toggleButton=>{const pendingPromise=new _pending.default("core_course:toggleManualCompletionState"),originalInnerHtml=toggleButton.innerHTML;toggleButton.setAttribute("disabled","disabled");const toggleType=toggleButton.getAttribute("data-toggletype"),cmid=toggleButton.getAttribute("data-cmid"),activityname=toggleButton.getAttribute("data-activityname"),completed=toggleType===TOGGLE_TYPES_TOGGLE_MARK_DONE;_templates.default.renderForPromise("core/loading",{}).then((loadingHtml=>{_templates.default.replaceNodeContents(toggleButton,loadingHtml,"")})).catch((()=>{}));try{await(0,_repository.toggleManualCompletion)(cmid,completed);const templateContext={cmid:cmid,activityname:activityname,overallcomplete:completed,overallincomplete:!completed,istrackeduser:!0},renderObject=await _templates.default.renderForPromise("core_course/completion_manual",templateContext),newToggleButton=(await _templates.default.replaceNode(toggleButton,renderObject.html,renderObject.js)).pop(),withAvailability=toggleButton.getAttribute("data-withavailability"),toggledEvent=new CustomEvent(CourseEvents.manualCompletionToggled,{bubbles:!0,detail:{cmid:cmid,activityname:activityname,completed:completed,withAvailability:withAvailability}});newToggleButton.dispatchEvent(toggledEvent)}catch(exception){toggleButton.removeAttribute("disabled"),toggleButton.innerHTML=originalInnerHtml,_notification.default.exception(exception)}pendingPromise.resolve()}})); define("core_course/recommendations",["exports","core/ajax","core/notification"],(function(_exports,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A javascript module to handle toggling activity chooser recommendations. * * @module core_course/recommendations * @copyright 2020 Adrian Greeve <adrian@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);const toggleRecommendation=e=>{let data={methodname:"core_course_toggle_activity_recommendation",args:{area:e.currentTarget.dataset.area,id:e.currentTarget.dataset.id}};_ajax.default.call([data])[0].fail(_notification.default.exception)};_exports.init=()=>{document.querySelectorAll("[data-area]").forEach((checkbox=>{checkbox.addEventListener("change",toggleRecommendation)}))}})); define("core_course/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * A javascript module to handle course ajax actions. * * @module core_course/repository * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};var _default={getEnrolledCoursesByTimelineClassification:(classification,limit,offset,sort)=>{const args={classification:classification};void 0!==limit&&(args.limit=limit),void 0!==offset&&(args.offset=offset),void 0!==sort&&(args.sort=sort);const request={methodname:"core_course_get_enrolled_courses_by_timeline_classification",args:args};return _ajax.default.call([request])[0]},getLastAccessedCourses:(userid,limit,offset,sort)=>{const args={};void 0!==userid&&(args.userid=userid),void 0!==limit&&(args.limit=limit),void 0!==offset&&(args.offset=offset),void 0!==sort&&(args.sort=sort);const request={methodname:"core_course_get_recent_courses",args:args};return _ajax.default.call([request])[0]},getUsersFromCourseModuleID:function(cmid,groupID){let onlyActive=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var request={methodname:"core_course_get_enrolled_users_by_cmid",args:{cmid:cmid,groupid:groupID,onlyactive:onlyActive}};return _ajax.default.call([request])[0]},toggleManualCompletion:(cmid,completed)=>{const request={methodname:"core_completion_update_activity_completion_status_manually",args:{cmid:cmid,completed:completed}};return _ajax.default.call([request])[0]},getEnrolledCoursesWithEventsByTimelineClassification:function(classification){let limit=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,offset=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,sort=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,searchValue=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,eventsFrom=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,eventsTo=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;const args={classification:classification,limit:limit,offset:offset,sort:sort,eventsfrom:eventsFrom,eventsto:eventsTo,searchvalue:searchValue},request={methodname:"core_course_get_enrolled_courses_with_action_events_by_timeline_classification",args:args};return _ajax.default.call([request])[0]}};return _exports.default=_default,_exports.default})); define("core_course/view",["exports","core_course/events"],(function(_exports,CourseEvents){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,CourseEvents=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * JS module for the course homepage. * * @module core_course/view * @copyright 2021 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(CourseEvents);let registered=!1;_exports.init=()=>{registered||(document.addEventListener(CourseEvents.manualCompletionToggled,(e=>{parseInt(e.detail.withAvailability)&&window.location.reload()})),registered=!0)}})); /** * Various actions on modules and sections in the editing mode - hiding, duplicating, deleting, etc. * * @module core_course/actions * @copyright 2016 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.3 */ define("core_course/actions",["jquery","core/ajax","core/templates","core/notification","core/str","core/url","core/yui","core/modal_factory","core/modal_events","core/key_codes","core/log","core_courseformat/courseeditor","core/event_dispatcher","core_course/events"],(function($,ajax,templates,notification,str,url,Y,ModalFactory,ModalEvents,KeyCodes,log,editor,EventDispatcher,CourseEvents){const componentActions=["moveSection","moveCm","addSection","deleteSection","sectionHide","sectionShow","cmHide","cmShow","cmStealth","cmMoveRight","cmMoveLeft"],courseeditor=editor.getCurrentCourseEditor();let formatname;var CSS_EDITINPROGRESS="editinprogress",CSS_EDITINGMOVE="editing_move",SELECTOR={ACTIVITYLI:"li.activity",ACTIONAREA:".actions",ACTIVITYACTION:"a.cm-edit-action",MENU:".moodle-actionmenu[data-enhance=moodle-core-actionmenu]",TOGGLE:".toggle-display,.dropdown-toggle",SECTIONLI:"li.section",SECTIONACTIONMENU:".section_action_menu",SECTIONITEM:'[data-for="section_title"]',ADDSECTIONS:".changenumsections [data-add-sections]",SECTIONBADGES:'[data-region="sectionbadges"]'};Y.use("moodle-course-coursebase",(function(){var courseformatselector=M.course.format.get_section_selector();courseformatselector&&(SELECTOR.SECTIONLI=courseformatselector)}));const dispatchEvent=function(eventName,detail,container,options){return container instanceof Element||void 0===container.get||(container=container.get(0)),EventDispatcher.dispatchEvent(eventName,detail,container,options)};var getModuleId=function(element){const item=element.get(0);if(item.dataset.id)return item.dataset.id;let id;return Y.use("moodle-course-util",(function(Y){id=Y.Moodle.core_course.util.cm.getId(Y.Node(item))})),id},addActivitySpinner=function(activity){activity.addClass(CSS_EDITINPROGRESS);var actionarea=activity.find(SELECTOR.ACTIONAREA).get(0);if(actionarea){var spinner=M.util.add_spinner(Y,Y.Node(actionarea));return spinner.show(),void 0!==activity.data("id")&&courseeditor.dispatch("cmLock",[activity.data("id")],!0),spinner}return null},addSectionSpinner=function(sectionelement){sectionelement.addClass(CSS_EDITINPROGRESS);var actionarea=sectionelement.find(SELECTOR.SECTIONACTIONMENU).get(0);if(actionarea){var spinner=M.util.add_spinner(Y,Y.Node(actionarea));return spinner.show(),void 0!==sectionelement.data("id")&&courseeditor.dispatch("sectionLock",[sectionelement.data("id")],!0),spinner}return null},addSectionLightbox=function(sectionelement){const item=sectionelement.get(0);var lightbox=M.util.add_lightbox(Y,Y.Node(item));return"section"==item.dataset.for&&item.dataset.id&&(courseeditor.dispatch("sectionLock",[item.dataset.id],!0),lightbox.setAttribute("data-state","section"),lightbox.setAttribute("data-state-id",item.dataset.id)),lightbox.show(),lightbox},removeSpinner=function(element,spinner,delay){window.setTimeout((function(){if(element.removeClass(CSS_EDITINPROGRESS),spinner&&spinner.hide(),void 0!==element.data("id")){const mutation="section"===element.data("for")?"sectionLock":"cmLock";courseeditor.dispatch(mutation,[element.data("id")],!1)}}),delay)},removeLightbox=function(lightbox,delay){lightbox&&window.setTimeout((function(){lightbox.hide(),lightbox.getAttribute("data-state")&&courseeditor.dispatch("".concat(lightbox.getAttribute("data-state"),"Lock"),[lightbox.getAttribute("data-state-id")],!1)}),delay)},initActionMenu=function(elementid){Y.use("moodle-course-coursebase",(function(){M.course.coursebase.invoke_function("setup_for_resource","#"+elementid)})),M.core.actionmenu&&M.core.actionmenu.newDOMNode&&M.core.actionmenu.newDOMNode(Y.one("#"+elementid))},editModule=function(moduleElement,cmid,target){var lightbox,action=target.attr("data-action"),spinner=addActivitySpinner(moduleElement),promises=ajax.call([{methodname:"core_course_edit_module",args:{id:cmid,action:action,sectionreturn:target.attr("data-sectionreturn")?target.attr("data-sectionreturn"):0}}],!0);"duplicate"===action&&(lightbox=addSectionLightbox(target.closest(SELECTOR.SECTIONLI))),$.when.apply($,promises).done((function(data){var mainElement,tabables,isInside,foundElement,elementToFocus=(mainElement=moduleElement,tabables=$("a:visible"),isInside=!1,foundElement=null,tabables.each((function(){if($.contains(mainElement[0],this))isInside=!0;else if(isInside)return foundElement=this,!1;return!0})),foundElement);moduleElement.replaceWith(data);let affectedids=[];$("<div>"+data+"</div>").find(SELECTOR.ACTIVITYLI).each((function(index){initActionMenu($(this).attr("id")),0===index&&(!function(elementId,action){var mainelement=$("#"+elementId),selector="[data-action="+action+"]";"groupsseparate"!==action&&"groupsvisible"!==action&&"groupsnone"!==action||(selector="[data-action=groupsseparate],[data-action=groupsvisible],[data-action=groupsnone]"),mainelement.find(selector).is(":visible")?mainelement.find(selector).focus():mainelement.find(SELECTOR.MENU).find(SELECTOR.TOGGLE).focus()}($(this).attr("id"),action),elementToFocus=null),affectedids.push(getModuleId($(this)))})),elementToFocus&&elementToFocus.focus(),removeSpinner(moduleElement,spinner,400),removeLightbox(lightbox,400),moduleElement.trigger($.Event("coursemoduleedited",{ajaxreturn:data,action:action})),courseeditor.dispatch("legacyActivityAction",action,cmid,affectedids)})).fail((function(ex){removeSpinner(moduleElement,spinner),removeLightbox(lightbox);var e=$.Event("coursemoduleeditfailed",{exception:ex,action:action});moduleElement.trigger(e),e.isDefaultPrevented()||notification.exception(ex)}))},refreshModule=function(element,cmid,sectionreturn){void 0===sectionreturn&&(sectionreturn=courseeditor.sectionReturn);const activityElement=$(element);var spinner=addActivitySpinner(activityElement),promises=ajax.call([{methodname:"core_course_get_module",args:{id:cmid,sectionreturn:sectionreturn}}],!0);return new Promise(((resolve,reject)=>{$.when.apply($,promises).done((function(data){removeSpinner(activityElement,spinner,400),replaceActivityHtmlWith(data),resolve(data)})).fail((function(){removeSpinner(activityElement,spinner),reject()}))}))},confirmDeleteModule=function(mainelement,onconfirm){var modtypename=mainelement.attr("class").match(/modtype_([^\s]*)/)[1],modulename=function(element){var name;Y.use("moodle-course-util",(function(Y){name=Y.Moodle.core_course.util.cm.getName(Y.Node(element.get(0)))}));const state=courseeditor.state,cmid=getModuleId(element);var _state$cm$get;return!name&&state&&cmid&&(name=null===(_state$cm$get=state.cm.get(cmid))||void 0===_state$cm$get?void 0:_state$cm$get.name),name}(mainelement);str.get_string("pluginname",modtypename).done((function(pluginname){var plugindata={type:pluginname,name:modulename};str.get_strings([{key:"confirm",component:"core"},{key:null===modulename?"deletechecktype":"deletechecktypename",param:plugindata},{key:"yes"},{key:"no"}]).done((function(s){notification.confirm(s[0],s[1],s[2],s[3],onconfirm)}))}))},replaceActionItem=function(actionitem,image,stringname,stringcomponent,newaction){var stringRequests=[{key:stringname,component:stringcomponent}];return str.get_strings(stringRequests).then((function(strings){return actionitem.find("span.menu-action-text").html(strings[0]),templates.renderPix(image,"core")})).then((function(pixhtml){actionitem.find(".icon").replaceWith(pixhtml),actionitem.attr("data-action",newaction)})).catch(notification.exception)},defaultEditSectionHandler=function(sectionElement,actionItem,data,courseformat,sectionid){var action=actionItem.attr("data-action");if("hide"===action||"show"===action){if("hide"===action?(sectionElement.addClass("hidden"),setSectionBadge(sectionElement[0],"hiddenfromstudents",!0,!1),replaceActionItem(actionItem,"i/show","showfromothers","format_"+courseformat,"show")):(setSectionBadge(sectionElement[0],"hiddenfromstudents",!1,!1),sectionElement.removeClass("hidden"),replaceActionItem(actionItem,"i/hide","hidefromothers","format_"+courseformat,"hide")),void 0!==data.modules)for(var i in data.modules)replaceActivityHtmlWith(data.modules[i]);void 0!==data.section_availability&§ionElement.find(".section_availability").first().replaceWith(data.section_availability);void 0!==courseeditor.state.section.get(sectionid)&&courseeditor.dispatch("sectionState",[sectionid])}else if("setmarker"===action){var oldmarker=$(SELECTOR.SECTIONLI+".current"),oldActionItem=oldmarker.find(SELECTOR.SECTIONACTIONMENU+" a[data-action=removemarker]");oldmarker.removeClass("current"),replaceActionItem(oldActionItem,"i/marker","highlight","core","setmarker"),sectionElement.addClass("current"),replaceActionItem(actionItem,"i/marked","highlightoff","core","removemarker"),courseeditor.dispatch("legacySectionAction",action,sectionid),setSectionBadge(sectionElement[0],"iscurrent",!0,!0)}else"removemarker"===action&&(sectionElement.removeClass("current"),replaceActionItem(actionItem,"i/marker","highlight","core","setmarker"),courseeditor.dispatch("legacySectionAction",action,sectionid),setSectionBadge(sectionElement[0],"iscurrent",!1,!0))};var replaceActivityHtmlWith=function(activityHTML){$("<div>"+activityHTML+"</div>").find(SELECTOR.ACTIVITYLI).each((function(){var id=$(this).attr("id");let focusedPath=function(id){const element=document.getElementById(id);if(element&&element.contains(document.activeElement))return element.querySelector(SELECTOR.ACTIONAREA).contains(document.activeElement)?"".concat(SELECTOR.ACTIONAREA,' [tabindex="0"]'):document.activeElement.id?"#".concat(document.activeElement.id):void 0}(id);if($(SELECTOR.ACTIVITYLI+"#"+id).replaceWith(activityHTML),initActionMenu(id),focusedPath){var _newItem$querySelecto;null===(_newItem$querySelecto=document.getElementById(id).querySelector(focusedPath))||void 0===_newItem$querySelecto||_newItem$querySelecto.focus()}}))},editSection=function(sectionElement,sectionid,target,courseformat){var action=target.attr("data-action"),sectionreturn=target.attr("data-sectionreturn")?target.attr("data-sectionreturn"):0;if(courseeditor.supportComponents&&componentActions.includes(action))return!1;var spinner=addSectionSpinner(sectionElement),promises=ajax.call([{methodname:"core_course_edit_section",args:{id:sectionid,action:action,sectionreturn:sectionreturn}}],!0),lightbox=addSectionLightbox(sectionElement);return $.when.apply($,promises).done((function(dataencoded){var data=$.parseJSON(dataencoded);removeSpinner(sectionElement,spinner),removeLightbox(lightbox),sectionElement.find(SELECTOR.SECTIONACTIONMENU).find(SELECTOR.TOGGLE).focus();var e=$.Event("coursesectionedited",{ajaxreturn:data,action:action});sectionElement.trigger(e),e.isDefaultPrevented()||defaultEditSectionHandler(sectionElement,target,data,courseformat,sectionid)})).fail((function(ex){removeSpinner(sectionElement,spinner),removeLightbox(lightbox);var e=$.Event("coursesectioneditfailed",{exception:ex,action:action});sectionElement.trigger(e),e.isDefaultPrevented()||notification.exception(ex)})),!0},setSectionBadge=function(sectionElement,badgetype,add,removeOther){const sectionbadges=sectionElement.querySelector(SELECTOR.SECTIONBADGES);if(!sectionbadges)return;const badge=sectionbadges.querySelector('[data-type="'+badgetype+'"]');badge&&(add?(removeOther&&document.querySelectorAll('[data-type="'+badgetype+'"]').forEach((b=>{b.classList.add("d-none")})),badge.classList.remove("d-none")):badge.classList.add("d-none"))};return Y.use("moodle-course-coursebase",(function(){M.course.coursebase.register_module({set_visibility_resource_ui:function(args){var mainelement=$(args.element.getDOMNode()),cmid=getModuleId(mainelement);if(cmid){var sectionreturn=mainelement.find("."+CSS_EDITINGMOVE).attr("data-sectionreturn");refreshModule(mainelement,cmid,sectionreturn)}},updateMovedCmState:params=>{const cm=courseeditor.state.cm.get(params.cmid);void 0!==cm&&courseeditor.dispatch("sectionState",[cm.sectionid]),courseeditor.dispatch("cmState",[params.cmid])},updateMovedSectionState:()=>{courseeditor.dispatch("courseState")}})})),courseeditor.addMutations({legacyActivityAction:function(statemanager,action,cmid,affectedids){const state=statemanager.state,cm=state.cm.get(cmid);if(void 0===cm)return;const section=state.section.get(cm.sectionid);if(void 0!==section){switch(courseeditor.dispatch("cmLock",[cm.id],!0),statemanager.setReadOnly(!1),cm.locked=!1,action){case"delete":section.cmlist=section.cmlist.reduce(((cmlist,current)=>(current!=cmid&&cmlist.push(current),cmlist)),[]),state.cm.delete(cmid);break;case"hide":case"show":case"duplicate":courseeditor.dispatch("cmState",affectedids)}statemanager.setReadOnly(!0)}},legacySectionAction:function(statemanager,action,sectionid){const state=statemanager.state,section=state.section.get(sectionid);if(void 0!==section){switch(statemanager.setReadOnly(!1),section.locked=!0,statemanager.setReadOnly(!0),statemanager.setReadOnly(!1),section.locked=!1,action){case"setmarker":state.section.forEach((current=>{current.id!=sectionid&&(current.current=!1)})),section.current=!0;break;case"removemarker":section.current=!1}statemanager.setReadOnly(!0)}}}),{initCoursePage:function(courseformat){formatname=courseformat,$("body").on("click keypress",SELECTOR.ACTIVITYLI+" "+SELECTOR.ACTIVITYACTION+"[data-action]",(function(e){if("keypress"!==e.type||13===e.keyCode){var actionItem=$(this),moduleElement=actionItem.closest(SELECTOR.ACTIVITYLI),action=actionItem.attr("data-action"),moduleId=getModuleId(moduleElement);switch(action){case"moveleft":case"moveright":case"delete":case"duplicate":case"hide":case"stealth":case"show":case"groupsseparate":case"groupsvisible":case"groupsnone":break;default:return}moduleId&&(e.preventDefault(),"delete"===action?confirmDeleteModule(moduleElement,(function(){editModule(moduleElement,moduleId,actionItem)})):editModule(moduleElement,moduleId,actionItem))}})),$("body").on("click keypress",SELECTOR.SECTIONLI+" "+SELECTOR.SECTIONACTIONMENU+"[data-sectionid] a[data-action]",(function(e){if("keypress"===e.type&&13!==e.keyCode)return;var actionItem=$(this),sectionElement=actionItem.closest(SELECTOR.SECTIONLI),sectionId=actionItem.closest(SELECTOR.SECTIONACTIONMENU).attr("data-sectionid");let isExecuted=!0;var message,onconfirm;actionItem.attr("data-confirm")?(message=actionItem.attr("data-confirm"),onconfirm=function(){isExecuted=editSection(sectionElement,sectionId,actionItem,courseformat)},str.get_strings([{key:"confirm"},{key:"yes"},{key:"no"}]).done((function(s){notification.confirm(s[0],message,s[1],s[2],onconfirm)}))):isExecuted=editSection(sectionElement,sectionId,actionItem,courseformat),isExecuted&&e.preventDefault()})),$("body").on("updated","".concat(SELECTOR.SECTIONLI," ").concat(SELECTOR.SECTIONITEM," [data-inplaceeditable]"),(function(e){if(e.ajaxreturn&&e.ajaxreturn.itemid){void 0!==courseeditor.state.section.get(e.ajaxreturn.itemid)&&courseeditor.dispatch("sectionState",[e.ajaxreturn.itemid])}})),$("body").on("updated","".concat(SELECTOR.ACTIVITYLI," [data-inplaceeditable]"),(function(e){e.ajaxreturn&&e.ajaxreturn.itemid&&courseeditor.dispatch("cmState",[e.ajaxreturn.itemid])})),courseeditor.supportComponents&&componentActions.includes("addSection")||str.get_string("numberweeks").done((function(strNumberSections){var trigger=$(SELECTOR.ADDSECTIONS),modalTitle=trigger.attr("data-add-sections"),newSections=trigger.attr("data-new-sections"),modalBody=$('<div><label for="add_section_numsections"></label> <input id="add_section_numsections" type="number" min="1" max="'+newSections+'" value="1"></div>');modalBody.find("label").html(strNumberSections),ModalFactory.create({title:modalTitle,type:ModalFactory.types.SAVE_CANCEL,body:modalBody.html()},trigger).done((function(modal){var numSections=$(modal.getBody()).find("#add_section_numsections"),addSections=function(){""+parseInt(numSections.val())===numSections.val()&&parseInt(numSections.val())>=1&&(document.location=trigger.attr("href")+"&numsections="+parseInt(numSections.val()))};modal.setSaveButtonText(modalTitle),modal.getRoot().on(ModalEvents.shown,(function(){numSections.focus().select().on("keydown",(function(e){e.keyCode===KeyCodes.enter&&addSections()}))})),modal.getRoot().on(ModalEvents.save,(function(e){e.preventDefault(),addSections()}))}))}))},replaceSectionActionItem:function(sectionelement,selector,image,stringname,stringcomponent,newaction){log.debug("replaceSectionActionItem() is deprecated and will be removed.");var actionitem=sectionelement.find(SELECTOR.SECTIONACTIONMENU+" "+selector);replaceActionItem(actionitem,image,stringname,stringcomponent,newaction)},refreshModule:refreshModule,refreshSection:function(element,sectionid,sectionreturn){void 0===sectionreturn&&(sectionreturn=courseeditor.sectionReturn);const sectionElement=$(element),promises=ajax.call([{methodname:"core_course_edit_section",args:{id:sectionid,action:"refresh",sectionreturn:sectionreturn}}],!0);var spinner=addSectionSpinner(sectionElement);return new Promise(((resolve,reject)=>{$.when.apply($,promises).done((dataencoded=>{removeSpinner(sectionElement,spinner);const data=$.parseJSON(dataencoded),newSectionElement=$(data.content);sectionElement.replaceWith(newSectionElement),$("".concat(SELECTOR.SECTIONLI,"#").concat(sectionid," ").concat(SELECTOR.ACTIVITYLI)).each(((index,activity)=>{initActionMenu(activity.data("id"))}));dispatchEvent(CourseEvents.sectionRefreshed,{ajaxreturn:data,action:"refresh",newSectionElement:newSectionElement.get(0)},newSectionElement).defaultPrevented||defaultEditSectionHandler(newSectionElement,$(SELECTOR.SECTIONLI+"#"+sectionid),data,formatname,sectionid),resolve(data)})).fail((ex=>{dispatchEvent("coursesectionrefreshfailed",{exception:ex,action:"refresh"},sectionElement).defaultPrevented||notification.exception(ex),reject()}))}))}}})); define("core_course/activitychooser",["exports","core_course/local/activitychooser/dialogue","core_course/local/activitychooser/repository","core_course/local/activitychooser/selectors","core/custom_interaction_events","core/templates","core/modal_factory","core/str","core/pending"],(function(_exports,ChooserDialogue,Repository,_selectors,_custom_interaction_events,Templates,ModalFactory,_str,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * A type of dialogue used as for choosing modules in a course. * * @module core_course/activitychooser * @copyright 2020 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,ChooserDialogue=_interopRequireWildcard(ChooserDialogue),Repository=_interopRequireWildcard(Repository),_selectors=_interopRequireDefault(_selectors),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),Templates=_interopRequireWildcard(Templates),ModalFactory=_interopRequireWildcard(ModalFactory),_pending=_interopRequireDefault(_pending);_exports.init=(courseId,chooserConfig)=>{const pendingPromise=new _pending.default;registerListenerEvents(courseId,chooserConfig),pendingPromise.resolve()};const registerListenerEvents=(courseId,chooserConfig)=>{const events=["click",_custom_interaction_events.default.events.activate,_custom_interaction_events.default.events.keyboardActivate],fetchModuleData=(()=>{let innerPromise=null;return()=>(innerPromise||(innerPromise=new Promise((resolve=>{resolve(Repository.activityModules(courseId))}))),innerPromise)})(),fetchFooterData=(()=>{let footerInnerPromise=null;return sectionId=>(footerInnerPromise||(footerInnerPromise=new Promise((resolve=>{resolve(Repository.fetchFooterData(courseId,sectionId))}))),footerInnerPromise)})();_custom_interaction_events.default.define(document,events),events.forEach((event=>{document.addEventListener(event,(async e=>{if(e.target.closest(_selectors.default.elements.sectionmodchooser)){let caller;const sectionDiv=e.target.closest(_selectors.default.elements.section),button=e.target.closest(_selectors.default.elements.sectionmodchooser);let bodyPromiseResolver;caller=null!==sectionDiv&§ionDiv.hasAttribute("data-sectionid")?sectionDiv:button;const bodyPromise=new Promise((resolve=>{bodyPromiseResolver=resolve})),footerData=await fetchFooterData(caller.dataset.sectionid),sectionModal=buildModal(bodyPromise,footerData),data=await fetchModuleData().catch((async e=>{const errorTemplateData={errormessage:e.message};bodyPromiseResolver(await Templates.render("core_course/local/activitychooser/error",errorTemplateData))}));if(!data)return;const builtModuleData=sectionIdMapper(data,caller.dataset.sectionid,caller.dataset.sectionreturnid);ChooserDialogue.displayChooser(sectionModal,builtModuleData,partiallyAppliedFavouriteManager(data,caller.dataset.sectionid),footerData),bodyPromiseResolver(await Templates.render("core_course/activitychooser",templateDataBuilder(builtModuleData,chooserConfig)))}}))}))},sectionIdMapper=(webServiceData,id,sectionreturnid)=>{const newData=JSON.parse(JSON.stringify(webServiceData));return newData.content_items.forEach((module=>{module.link+="§ion="+id+"&sr="+(null!=sectionreturnid?sectionreturnid:0)})),newData.content_items},templateDataBuilder=(data,chooserConfig)=>{let activities=[],resources=[],showAll=!0,showActivities=!1,showResources=!1;const tabMode=parseInt(chooserConfig.tabmode),favourites=data.filter((mod=>!0===mod.favourite)),recommended=data.filter((mod=>!0===mod.recommended));0!==tabMode&&2!==tabMode||1===tabMode||(activities=data.filter((mod=>0===mod.archetype)),resources=data.filter((mod=>1===mod.archetype)),showActivities=!0,showResources=!0,2===tabMode&&(showAll=!1));const favouritesFirst=!!favourites.length;return{default:data,showAll:showAll,activities:activities,showActivities:showActivities,activitiesFirst:!1===showAll&&!1===favouritesFirst,resources:resources,showResources:showResources,favourites:favourites,recommended:recommended,favouritesFirst:favouritesFirst,fallback:!0===showAll&&!1===favouritesFirst}},buildModal=(bodyPromise,footer)=>ModalFactory.create({type:ModalFactory.types.DEFAULT,title:(0,_str.get_string)("addresourceoractivity"),body:bodyPromise,footer:footer.customfootertemplate,large:!0,scrollable:!1,templateContext:{classes:"modchooser"}}).then((modal=>(modal.show(),modal))),partiallyAppliedFavouriteManager=(moduleData,sectionId)=>async(internal,favourite,modalBody)=>{const favouriteArea=modalBody.querySelector(_selectors.default.render.favourites),favouriteButtons=modalBody.querySelectorAll('[data-internal="'.concat(internal,'"] ').concat(_selectors.default.actions.optionActions.manageFavourite)),favouriteTabNav=modalBody.querySelector(_selectors.default.regions.favouriteTabNav),result=moduleData.content_items.find((_ref=>{let{name:name}=_ref;return name===internal})),newFaves={};if(result)if(favourite){result.favourite=!0,newFaves.content_items=moduleData.content_items.filter((mod=>!0===mod.favourite));const builtFaves=sectionIdMapper(newFaves,sectionId),{html:html,js:js}=await Templates.renderForPromise("core_course/local/activitychooser/favourites",{favourites:builtFaves});await Templates.replaceNodeContents(favouriteArea,html,js),Array.from(favouriteButtons).forEach((element=>{element.classList.remove("text-muted"),element.classList.add("text-primary"),element.dataset.favourited="true",element.setAttribute("aria-pressed",!0),element.firstElementChild.classList.remove("fa-star-o"),element.firstElementChild.classList.add("fa-star")})),favouriteTabNav.classList.remove("d-none")}else{result.favourite=!1;const nodeToRemove=favouriteArea.querySelector('[data-internal="'.concat(internal,'"]'));nodeToRemove.parentNode.removeChild(nodeToRemove),Array.from(favouriteButtons).forEach((element=>{element.classList.add("text-muted"),element.classList.remove("text-primary"),element.dataset.favourited="false",element.setAttribute("aria-pressed",!1),element.firstElementChild.classList.remove("fa-star"),element.firstElementChild.classList.add("fa-star-o")}));0===moduleData.content_items.filter((mod=>!0===mod.favourite)).length&&((favouriteTabNav,modalBody)=>{if(favouriteTabNav.tabIndex=-1,favouriteTabNav.classList.add("d-none"),favouriteTabNav.classList.contains("active")){favouriteTabNav.classList.remove("active"),favouriteTabNav.setAttribute("aria-selected","false"),modalBody.querySelector(_selectors.default.regions.favouriteTab).classList.remove("active");const defaultTabNav=modalBody.querySelector(_selectors.default.regions.defaultTabNav),activitiesTabNav=modalBody.querySelector(_selectors.default.regions.activityTabNav);!1===defaultTabNav.classList.contains("d-none")?(defaultTabNav.classList.add("active"),defaultTabNav.setAttribute("aria-selected","true"),defaultTabNav.tabIndex=0,defaultTabNav.focus(),modalBody.querySelector(_selectors.default.regions.defaultTab).classList.add("active")):(activitiesTabNav.classList.add("active"),activitiesTabNav.setAttribute("aria-selected","true"),activitiesTabNav.tabIndex=0,activitiesTabNav.focus(),modalBody.querySelector(_selectors.default.regions.activityTab).classList.add("active"))}})(favouriteTabNav,modalBody)}}})); define("core_courseformat/courseeditor",["exports","core_courseformat/local/courseeditor/mutations","core_courseformat/local/courseeditor/courseeditor","core_course/events"],(function(_exports,_mutations,_courseeditor,_events){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Generic reactive module used in the course editor. * * @module core_courseformat/courseeditor * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setViewFormat=_exports.getCurrentCourseEditor=_exports.getCourseEditor=void 0,_mutations=_interopRequireDefault(_mutations),_courseeditor=_interopRequireDefault(_courseeditor),_events=_interopRequireDefault(_events);const courseEditorMap=new Map,courseStateKeyMap=new Map;function dispatchStateChangedEvent(detail,target){void 0===target&&(target=document),target.dispatchEvent(new CustomEvent(_events.default.stateChanged,{bubbles:!0,detail:detail}))}_exports.setViewFormat=(courseId,setup)=>{courseId=parseInt(courseId),setup.editing||courseStateKeyMap.set(courseId,setup.statekey);getCourseEditor(courseId).setViewFormat(setup)};const getCourseEditor=courseId=>(courseId=parseInt(courseId),courseEditorMap.has(courseId)||(courseEditorMap.set(courseId,new _courseeditor.default({name:"CourseEditor".concat(courseId),eventName:_events.default.stateChanged,eventDispatch:dispatchStateChangedEvent,mutations:new _mutations.default})),courseEditorMap.get(courseId).loadCourse(courseId,courseStateKeyMap.get(courseId))),courseEditorMap.get(courseId));_exports.getCourseEditor=getCourseEditor;_exports.getCurrentCourseEditor=()=>getCourseEditor(M.cfg.courseId)})); define("core_courseformat/local/content/activity_header",["exports","core/reactive","core_courseformat/courseeditor","core_course/events"],(function(_exports,_reactive,_courseeditor,CourseEvents){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,CourseEvents=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * The activity header component. * * @module core_courseformat/local/content/activity_header * @class core_courseformat/local/content/activity_header * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(CourseEvents);const SELECTORS_ACTIVITY_HEADER="[data-for='page-activity-header']";class Component extends _reactive.BaseComponent{create(){this.name="activity_header"}static init(target,selectors){const elementselector=target||SELECTORS_ACTIVITY_HEADER;return new Component({element:document.querySelector(elementselector),reactive:(0,_courseeditor.getCurrentCourseEditor)(),selectors:selectors})}stateReady(){this.addEventListener(this.element,CourseEvents.manualCompletionToggled,this._completionHandler)}_completionHandler(_ref){let{detail:detail}=_ref;void 0!==detail&&this.reactive.dispatch("cmCompletion",[detail.cmid],detail.completed)}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/content/section/cmitem",["exports","core_courseformat/local/courseeditor/dndcmitem"],(function(_exports,_dndcmitem){var obj; /** * Course course module item component. * * This component is used to control specific course modules interactions like drag and drop. * * @module core_courseformat/local/content/section/cmitem * @class core_courseformat/local/content/section/cmitem * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndcmitem=(obj=_dndcmitem)&&obj.__esModule?obj:{default:obj};class _default extends _dndcmitem.default{create(){this.name="content_section_cmitem",this.selectors={DRAGICON:".editing_move"},this.classes={LOCKED:"editinprogress"},this.id=this.element.dataset.id}stateReady(){var _this$getElement;this.configDragDrop(this.id),null===(_this$getElement=this.getElement(this.selectors.DRAGICON))||void 0===_this$getElement||_this$getElement.classList.add(this.classes.DRAGICON)}getWatchers(){return[{watch:"cm[".concat(this.id,"]:deleted"),handler:this.unregister},{watch:"cm[".concat(this.id,"]:updated"),handler:this._refreshCm}]}_refreshCm(_ref){var _element$dragging,_element$locked;let{element:element}=_ref;this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.locked=element.locked}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/content/section/header",["exports","core_courseformat/local/courseeditor/dndsectionitem"],(function(_exports,_dndsectionitem){var obj; /** * Course section header component. * * This component is used to control specific course section interactions like drag and drop. * * @module core_courseformat/local/content/section/header * @class core_courseformat/local/content/section/header * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndsectionitem=(obj=_dndsectionitem)&&obj.__esModule?obj:{default:obj};class _default extends _dndsectionitem.default{create(descriptor){this.name="content_section_header",this.id=descriptor.id,this.section=descriptor.section,this.course=descriptor.course,this.fullregion=descriptor.fullregion}stateReady(state){this.configDragDrop(this.id,state,this.fullregion)}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/content/actions",["exports","core/reactive","core/modal_factory","core/modal_events","core/templates","core/prefetch","core/str","core/normalise","core_course/events","core/pending","core_courseformat/local/courseeditor/contenttree","jquery"],(function(_exports,_reactive,_modal_factory,_modal_events,_templates,_prefetch,_str,_normalise,CourseEvents,_pending,_contenttree,_jquery){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course state actions dispatcher. * * This module captures all data-dispatch links in the course content and dispatch the proper * state mutation, including any confirmation and modal required. * * @module core_courseformat/local/content/actions * @class core_courseformat/local/content/actions * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_templates=_interopRequireDefault(_templates),CourseEvents=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(CourseEvents),_pending=_interopRequireDefault(_pending),_contenttree=_interopRequireDefault(_contenttree),_jquery=_interopRequireDefault(_jquery),(0,_prefetch.prefetchStrings)("core",["movecoursesection","movecoursemodule","confirm","delete"]);const directMutations={sectionHide:"sectionHide",sectionShow:"sectionShow",cmHide:"cmHide",cmShow:"cmShow",cmStealth:"cmStealth",cmMoveRight:"cmMoveRight",cmMoveLeft:"cmMoveLeft"};class _default extends _reactive.BaseComponent{create(){this.name="content_actions",this.selectors={ACTIONLINK:"[data-action]",SECTIONLINK:"[data-for='section']",CMLINK:"[data-for='cm']",SECTIONNODE:"[data-for='sectionnode']",MODALTOGGLER:"[data-toggle='collapse']",ADDSECTION:"[data-action='addSection']",CONTENTTREE:"#destination-selector",ACTIONMENU:".action-menu",ACTIONMENUTOGGLER:'[data-toggle="dropdown"]'},this.classes={DISABLED:"text-body",ITALIC:"font-italic"}}static addActions(actions){for(const[action,mutationReference]of Object.entries(actions)){if("function"!=typeof mutationReference&&"string"!=typeof mutationReference)throw new Error("".concat(action," action must be a mutation name or a function"));directMutations[action]=mutationReference}}stateReady(state){this.addEventListener(this.element,"click",this._dispatchClick),this._checkSectionlist({state:state}),this.addEventListener(this.element,CourseEvents.sectionRefreshed,(()=>this._checkSectionlist({state:state})))}getWatchers(){return[{watch:"course.sectionlist:updated",handler:this._checkSectionlist}]}_dispatchClick(event){const target=event.target.closest(this.selectors.ACTIONLINK);if(!target)return;if(target.classList.contains(this.classes.DISABLED))return void event.preventDefault();const actionName=target.dataset.action,methodName=this._actionMethodName(actionName);if(void 0===this[methodName])return void 0!==directMutations[actionName]?"function"==typeof directMutations[actionName]?void directMutations[actionName](target,event):void this._requestMutationAction(target,event,directMutations[actionName]):void 0;this[methodName](target,event)}_actionMethodName(name){const requestName=name.charAt(0).toUpperCase()+name.slice(1);return"_request".concat(requestName)}_checkSectionlist(_ref){let{state:state}=_ref;this._setAddSectionLocked(state.course.sectionlist.length>state.course.maxsections)}async _requestMoveSection(target,event){const sectionId=target.dataset.id;if(!sectionId)return;const sectionInfo=this.reactive.get("section",sectionId);event.preventDefault();const pendingModalReady=new _pending.default("courseformat/actions:prepareMoveSectionModal"),editTools=this._getClosestActionMenuToogler(target),data=this.reactive.getExporter().course(this.reactive.state);data.sectionid=sectionInfo.id,data.sectiontitle=sectionInfo.title;const modalParams={title:(0,_str.get_string)("movecoursesection","core"),body:_templates.default.render("core_courseformat/local/content/movesection",data)},modal=await this._modalBodyRenderedPromise(modalParams),modalBody=(0,_normalise.getList)(modal.getBody())[0],currentElement=modalBody.querySelector("".concat(this.selectors.SECTIONLINK,"[data-id='").concat(sectionId,"']"));this._disableLink(currentElement);const generalSection=modalBody.querySelector("".concat(this.selectors.SECTIONLINK,"[data-number='0']"));this._disableLink(generalSection),new _contenttree.default(modalBody.querySelector(this.selectors.CONTENTTREE),{SECTION:this.selectors.SECTIONNODE,TOGGLER:this.selectors.MODALTOGGLER,COLLAPSE:this.selectors.MODALTOGGLER},!0),modalBody.addEventListener("click",(event=>{const target=event.target;target.matches("a")&&"section"==target.dataset.for&&void 0!==target.dataset.id&&(target.getAttribute("aria-disabled")||(event.preventDefault(),this.reactive.dispatch("sectionMove",[sectionId],target.dataset.id),this._destroyModal(modal,editTools)))})),pendingModalReady.resolve()}async _requestMoveCm(target,event){var _toggler$data;const cmId=target.dataset.id;if(!cmId)return;const cmInfo=this.reactive.get("cm",cmId);event.preventDefault();const pendingModalReady=new _pending.default("courseformat/actions:prepareMoveCmModal"),editTools=this._getClosestActionMenuToogler(target),exporter=this.reactive.getExporter(),data=exporter.course(this.reactive.state);data.cmid=cmInfo.id,data.cmname=cmInfo.name;const modalParams={title:(0,_str.get_string)("movecoursemodule","core"),body:_templates.default.render("core_courseformat/local/content/movecm",data)},modal=await this._modalBodyRenderedPromise(modalParams),modalBody=(0,_normalise.getList)(modal.getBody())[0];let currentElement=modalBody.querySelector("".concat(this.selectors.CMLINK,"[data-id='").concat(cmId,"']"));this._disableLink(currentElement),new _contenttree.default(modalBody.querySelector(this.selectors.CONTENTTREE),{SECTION:this.selectors.SECTIONNODE,TOGGLER:this.selectors.MODALTOGGLER,COLLAPSE:this.selectors.MODALTOGGLER,ENTER:this.selectors.SECTIONLINK});const sectionnode=currentElement.closest(this.selectors.SECTIONNODE),toggler=(0,_jquery.default)(sectionnode).find(this.selectors.MODALTOGGLER);let collapsibleId=null!==(_toggler$data=toggler.data("target"))&&void 0!==_toggler$data?_toggler$data:toggler.attr("href");collapsibleId&&(collapsibleId=collapsibleId.replace("#",""),(0,_jquery.default)("#".concat(collapsibleId)).collapse("toggle")),modalBody.addEventListener("click",(event=>{const target=event.target;if(!target.matches("a")||void 0===target.dataset.for||void 0===target.dataset.id)return;if(target.getAttribute("aria-disabled"))return;let targetSectionId,targetCmId;if(event.preventDefault(),"cm"==target.dataset.for){const dropData=exporter.cmDraggableData(this.reactive.state,target.dataset.id);targetSectionId=dropData.sectionid,targetCmId=dropData.nextcmid}else{const section=this.reactive.get("section",target.dataset.id);targetSectionId=target.dataset.id,targetCmId=null==section?void 0:section.cmlist[0]}this.reactive.dispatch("cmMove",[cmId],targetSectionId,targetCmId),this._destroyModal(modal,editTools)})),pendingModalReady.resolve()}async _requestAddSection(target,event){var _target$dataset$id;event.preventDefault(),this.reactive.dispatch("addSection",null!==(_target$dataset$id=target.dataset.id)&&void 0!==_target$dataset$id?_target$dataset$id:0)}async _requestDeleteSection(target,event){var _sectionInfo$cmlist;const sectionId=target.dataset.id;if(!sectionId)return;const sectionInfo=this.reactive.get("section",sectionId);event.preventDefault();if((null!==(_sectionInfo$cmlist=sectionInfo.cmlist)&&void 0!==_sectionInfo$cmlist?_sectionInfo$cmlist:[]).length||sectionInfo.hassummary||sectionInfo.rawtitle){const modalParams={title:(0,_str.get_string)("confirm","core"),body:(0,_str.get_string)("confirmdeletesection","moodle",sectionInfo.title),saveButtonText:(0,_str.get_string)("delete","core"),type:_modal_factory.default.types.SAVE_CANCEL},modal=await this._modalBodyRenderedPromise(modalParams);modal.getRoot().on(_modal_events.default.save,(e=>{e.preventDefault(),modal.destroy(),this.reactive.dispatch("sectionDelete",[sectionId])}))}else this.reactive.dispatch("sectionDelete",[sectionId])}async _requestMutationAction(target,event,mutationName){target.dataset.id&&(event.preventDefault(),this.reactive.dispatch(mutationName,[target.dataset.id]))}_setAddSectionLocked(locked){this.getElements(this.selectors.ADDSECTION).forEach((element=>{element.classList.toggle(this.classes.DISABLED,locked),element.classList.toggle(this.classes.ITALIC,locked),this.setElementLocked(element,locked)}))}_disableLink(element){element&&(element.style.pointerEvents="none",element.style.userSelect="none",element.classList.add(this.classes.DISABLED),element.classList.add(this.classes.ITALIC),element.setAttribute("aria-disabled",!0),element.addEventListener("click",(event=>event.preventDefault())))}_modalBodyRenderedPromise(modalParams){return new Promise(((resolve,reject)=>{_modal_factory.default.create(modalParams).then((modal=>{modal.setRemoveOnClose(!0),modal.getRoot().on(_modal_events.default.bodyRendered,(()=>{resolve(modal)})),void 0!==modalParams.saveButtonText&&modal.setSaveButtonText(modalParams.saveButtonText),modal.show()})).catch((()=>{reject("Cannot load modal content")}))}))}_destroyModal(modal,element){modal.hide();const pendingDestroy=new _pending.default("courseformat/actions:destroyModal");element&&element.focus(),setTimeout((()=>{modal.destroy(),pendingDestroy.resolve()}),500)}_getClosestActionMenuToogler(element){const actionMenu=element.closest(this.selectors.ACTIONMENU);if(actionMenu)return actionMenu.querySelector(this.selectors.ACTIONMENUTOGGLER)}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/content/section",["exports","core_courseformat/local/content/section/header","core_courseformat/local/courseeditor/dndsection","core/templates"],(function(_exports,_header,_dndsection,_templates){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course section format component. * * @module core_courseformat/local/content/section * @class core_courseformat/local/content/section * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_header=_interopRequireDefault(_header),_dndsection=_interopRequireDefault(_dndsection),_templates=_interopRequireDefault(_templates);class _default extends _dndsection.default{create(){this.name="content_section",this.selectors={SECTION_ITEM:"[data-for='section_title']",CM:'[data-for="cmitem"]',SECTIONINFO:'[data-for="sectioninfo"]',SECTIONBADGES:'[data-region="sectionbadges"]',SHOWSECTION:'[data-action="sectionShow"]',HIDESECTION:'[data-action="sectionHide"]',ACTIONTEXT:".menu-action-text",ICON:".icon"},this.classes={LOCKED:"editinprogress",HASDESCRIPTION:"description",HIDE:"d-none",HIDDEN:"hidden"},this.id=this.element.dataset.id}stateReady(state){if(this.configState(state),this.reactive.isEditing&&this.reactive.supportComponents){const sectionItem=this.getElement(this.selectors.SECTION_ITEM);if(sectionItem){const headerComponent=new _header.default({...this,element:sectionItem,fullregion:this.element});this.configDragDrop(headerComponent)}}}getWatchers(){return[{watch:"section[".concat(this.id,"]:updated"),handler:this._refreshSection}]}validateDropData(dropdata){return("section"!==(null==dropdata?void 0:dropdata.type)||0==this.reactive.sectionReturn)&&super.validateDropData(dropdata)}getLastCm(){const cms=this.getElements(this.selectors.CM);return cms&&0!==cms.length?cms[cms.length-1]:null}_refreshSection(_ref){var _element$dragging,_element$locked,_element$visible;let{element:element}=_ref;this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.element.classList.toggle(this.classes.HIDDEN,null!==(_element$visible=!element.visible)&&void 0!==_element$visible&&_element$visible),this.locked=element.locked;const sectioninfo=this.getElement(this.selectors.SECTIONINFO);sectioninfo&§ioninfo.classList.toggle(this.classes.HASDESCRIPTION,element.hasrestrictions),this._updateBadges(element),this._updateActionsMenu(element)}_updateBadges(section){const current=this.getElement("".concat(this.selectors.SECTIONBADGES," [data-type='iscurrent']"));null==current||current.classList.toggle(this.classes.HIDE,!section.current);const hiddenFromStudents=this.getElement("".concat(this.selectors.SECTIONBADGES," [data-type='hiddenfromstudents']"));null==hiddenFromStudents||hiddenFromStudents.classList.toggle(this.classes.HIDE,section.visible)}async _updateActionsMenu(section){var _affectedAction$datas,_affectedAction$datas2;let selector,newAction;section.visible?(selector=this.selectors.SHOWSECTION,newAction="sectionHide"):(selector=this.selectors.HIDESECTION,newAction="sectionShow");const affectedAction=this.getElement(selector);if(!affectedAction)return;affectedAction.dataset.action=newAction;const actionText=affectedAction.querySelector(this.selectors.ACTIONTEXT);if(null!==(_affectedAction$datas=affectedAction.dataset)&&void 0!==_affectedAction$datas&&_affectedAction$datas.swapname&&actionText){const oldText=null==actionText?void 0:actionText.innerText;actionText.innerText=affectedAction.dataset.swapname,affectedAction.dataset.swapname=oldText}const icon=affectedAction.querySelector(this.selectors.ICON);if(null!==(_affectedAction$datas2=affectedAction.dataset)&&void 0!==_affectedAction$datas2&&_affectedAction$datas2.swapicon&&icon){const newIcon=affectedAction.dataset.swapicon;if(newIcon){const pixHtml=await _templates.default.renderPix(newIcon,"core");_templates.default.replaceNode(icon,pixHtml,"")}}}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/contenttree",["exports","jquery","core/tree","core/normalise"],(function(_exports,_jquery,_tree,_normalise){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index keyboard navigation and aria-tree compatibility. * * Node tree and bootstrap collapsibles don't use the same HTML structure. However, * all keybindings and logic is compatible. This class translate the primitive opetations * to a bootstrap collapsible structure. * * @module core_courseformat/local/courseindex/keyboardnav * @class core_courseformat/local/courseindex/keyboardnav * @copyright 2021 Ferran Recio <ferran@moodle.com> * @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),_tree=_interopRequireDefault(_tree);class _default extends _tree.default{constructor(mainElement,selectors,preventcache){var _selectors$ENTER;super(mainElement),this.selectors={SECTION:selectors.SECTION,TOGGLER:selectors.TOGGLER,COLLAPSE:selectors.COLLAPSE,ENTER:null!==(_selectors$ENTER=selectors.ENTER)&&void 0!==_selectors$ENTER?_selectors$ENTER:selectors.TOGGLER},preventcache&&(this._getVisibleItems=this.getVisibleItems,this.getVisibleItems=()=>(this.refreshVisibleItemsCache(),this._getVisibleItems())),this.treeRoot.on("hidden.bs.collapse shown.bs.collapse",(()=>{this.refreshVisibleItemsCache()})),this.registerEnterCallback(this.enterCallback.bind(this))}getActiveItem(){const activeItem=this.treeRoot.data("activeItem");if(activeItem)return(0,_normalise.getList)(activeItem)[0]}enterCallback(jQueryItem){const item=(0,_normalise.getList)(jQueryItem)[0];if(this.isGroupItem(jQueryItem)){const enter=item.querySelector(this.selectors.ENTER);"#"!==enter.getAttribute("href")&&(window.location.href=enter.getAttribute("href")),enter.click()}else{const link=item.querySelector("a");"#"!==link.getAttribute("href")?window.location.href=link.getAttribute("href"):link.click()}}handleItemClick(event,jQueryItem){event.target.closest(this.selectors.COLLAPSE)?super.handleItemClick(event,jQueryItem):(jQueryItem.focus(),this.isGroupItem(jQueryItem)&&this.expandGroup(jQueryItem))}isGroupCollapsed(jQueryItem){return"false"===(0,_normalise.getList)(jQueryItem)[0].querySelector("[aria-expanded]").getAttribute("aria-expanded")}toggleGroup(item){var _toggler$data;const toggler=item.find(this.selectors.COLLAPSE);let collapsibleId=null!==(_toggler$data=toggler.data("target"))&&void 0!==_toggler$data?_toggler$data:toggler.attr("href");if(!collapsibleId)return;collapsibleId=collapsibleId.replace("#","");(0,_jquery.default)("#".concat(collapsibleId)).length&&(0,_jquery.default)("#".concat(collapsibleId)).collapse("toggle")}expandGroup(item){this.isGroupCollapsed(item)&&this.toggleGroup(item)}collapseGroup(item){this.isGroupCollapsed(item)||this.toggleGroup(item)}expandAllGroups(){(0,_normalise.getList)(this.treeRoot)[0].querySelectorAll(this.selectors.SECTION).forEach((item=>{this.expandGroup((0,_jquery.default)(item))}))}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/courseeditor",["exports","core/reactive","core/notification","core_courseformat/local/courseeditor/exporter","core/log","core/ajax","core/sessionstorage"],(function(_exports,_reactive,_notification,_exporter,_log,_ajax,Storage){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj} /** * Main course editor module. * * All formats can register new components on this object to create new reactive * UI components that watch the current course state. * * @module core_courseformat/local/courseeditor/courseeditor * @class core_courseformat/local/courseeditor/courseeditor * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_notification=_interopRequireDefault(_notification),_exporter=_interopRequireDefault(_exporter),_log=_interopRequireDefault(_log),_ajax=_interopRequireDefault(_ajax),Storage=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Storage);class _default extends _reactive.Reactive{constructor(){super(...arguments),_defineProperty(this,"stateKey",1),_defineProperty(this,"sectionReturn",0)}async loadCourse(courseId,serverStateKey){if(this.courseId)throw new Error("Cannot load ".concat(courseId,", course already loaded with id ").concat(this.courseId));let stateData;serverStateKey||(serverStateKey="invalidStateKey_".concat(Date.now())),this._editing=!1,this._supportscomponents=!1,this.courseId=courseId;const storeStateKey=Storage.get("course/".concat(courseId,"/stateKey"));try{this.isEditing||serverStateKey!=storeStateKey||(stateData=JSON.parse(Storage.get("course/".concat(courseId,"/staticState")))),stateData||(stateData=await this.getServerCourseState())}catch(error){return _log.default.error("EXCEPTION RAISED WHILE INIT COURSE EDITOR"),void _log.default.error(error)}if(this.setInitialState(stateData),this.isEditing)this.stateKey=null;else{const newState=JSON.stringify(stateData);var _stateData$course$sta,_stateData,_stateData$course;if(Storage.get("course/".concat(courseId,"/staticState"))!==newState||storeStateKey!==serverStateKey)Storage.set("course/".concat(courseId,"/staticState"),newState),Storage.set("course/".concat(courseId,"/stateKey"),null!==(_stateData$course$sta=null===(_stateData=stateData)||void 0===_stateData||null===(_stateData$course=_stateData.course)||void 0===_stateData$course?void 0:_stateData$course.statekey)&&void 0!==_stateData$course$sta?_stateData$course$sta:serverStateKey);this.stateKey=Storage.get("course/".concat(courseId,"/stateKey"))}}setViewFormat(setup){var _setup$editing,_setup$supportscompon;this._editing=null!==(_setup$editing=setup.editing)&&void 0!==_setup$editing&&_setup$editing,this._supportscomponents=null!==(_setup$supportscompon=setup.supportscomponents)&&void 0!==_setup$supportscompon&&_setup$supportscompon}async getServerCourseState(){const courseState=await _ajax.default.call([{methodname:"core_courseformat_get_state",args:{courseid:this.courseId}}])[0];return{course:{},section:[],cm:[],...JSON.parse(courseState)}}get isEditing(){var _this$_editing;return null!==(_this$_editing=this._editing)&&void 0!==_this$_editing&&_this$_editing}getExporter(){return new _exporter.default(this)}get supportComponents(){var _this$_supportscompon;return null!==(_this$_supportscompon=this._supportscomponents)&&void 0!==_this$_supportscompon&&_this$_supportscompon}getStorageValue(key){if(this.isEditing||!this.stateKey)return!1;const dataJson=Storage.get("course/".concat(this.courseId,"/").concat(key));if(!dataJson)return!1;try{const data=JSON.parse(dataJson);return(null==data?void 0:data.stateKey)===this.stateKey&&data.value}catch(error){return!1}}setStorageValue(key,value){if(this.isEditing)return!1;const data={stateKey:this.stateKey,value:value};return Storage.set("course/".concat(this.courseId,"/").concat(key),JSON.stringify(data))}async dispatch(){try{await super.dispatch(...arguments)}catch(error){_notification.default.exception(error),super.dispatch("unlockAll")}}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/dndcmitem",["exports","core/reactive"],(function(_exports,_reactive){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Course index cm component. * * This component is used to control specific course modules interactions like drag and drop * in both course index and course content. * * @module core_courseformat/local/courseeditor/dndcmitem * @class core_courseformat/local/courseeditor/dndcmitem * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class _default extends _reactive.BaseComponent{configDragDrop(cmid){this.id=cmid,this.reactive.isEditing&&this.reactive.supportComponents&&(this.dragdrop=new _reactive.DragDrop(this),this.classes=this.dragdrop.getClasses())}destroy(){void 0!==this.dragdrop&&this.dragdrop.unregister()}dragStart(dropdata){this.reactive.dispatch("cmDrag",[dropdata.id],!0)}dragEnd(dropdata){this.reactive.dispatch("cmDrag",[dropdata.id],!1)}getDraggableData(){return this.reactive.getExporter().cmDraggableData(this.reactive.state,this.id)}validateDropData(dropdata){return"cm"===(null==dropdata?void 0:dropdata.type)}showDropZone(dropdata){dropdata.nextcmid!=this.id&&dropdata.id!=this.id&&this.element.classList.add(this.classes.DROPUP)}hideDropZone(){this.element.classList.remove(this.classes.DROPUP)}drop(dropdata){dropdata.id!=this.id&&dropdata.nextcmid!=this.id&&this.reactive.dispatch("cmMove",[dropdata.id],null,this.id)}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/dndsection",["exports","core/reactive"],(function(_exports,_reactive){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Course index section component. * * This component is used to control specific course section interactions like drag and drop * in both course index and course content. * * @module core_courseformat/local/courseeditor/dndsection * @class core_courseformat/local/courseeditor/dndsection * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class _default extends _reactive.BaseComponent{configState(state){this.id=this.element.dataset.id,this.section=state.section.get(this.id),this.course=state.course}configDragDrop(sectionitem){this.reactive.isEditing&&this.reactive.supportComponents&&(this.sectionitem=sectionitem,this.dragdrop=new _reactive.DragDrop(this),this.classes=this.dragdrop.getClasses())}destroy(){void 0!==this.sectionitem&&this.sectionitem.unregister(),void 0!==this.dragdrop&&this.dragdrop.unregister()}getLastCm(){return null}dragStart(dropdata){this.reactive.dispatch("sectionDrag",[dropdata.id],!0)}dragEnd(dropdata){this.reactive.dispatch("sectionDrag",[dropdata.id],!1)}validateDropData(dropdata){if("cm"===(null==dropdata?void 0:dropdata.type))return!0;if("section"===(null==dropdata?void 0:dropdata.type)){const sectionzeroid=this.course.sectionlist[0];return(null==dropdata?void 0:dropdata.id)!=this.id&&(null==dropdata?void 0:dropdata.id)!=sectionzeroid&&this.id!=sectionzeroid}return!1}showDropZone(dropdata){var _this$getLastCm;"cm"==dropdata.type&&(null===(_this$getLastCm=this.getLastCm())||void 0===_this$getLastCm||_this$getLastCm.classList.add(this.classes.DROPDOWN));"section"==dropdata.type&&(this.section.number>dropdata.number?(this.element.classList.remove(this.classes.DROPUP),this.element.classList.add(this.classes.DROPDOWN)):(this.element.classList.add(this.classes.DROPUP),this.element.classList.remove(this.classes.DROPDOWN)))}hideDropZone(){var _this$getLastCm2;null===(_this$getLastCm2=this.getLastCm())||void 0===_this$getLastCm2||_this$getLastCm2.classList.remove(this.classes.DROPDOWN),this.element.classList.remove(this.classes.DROPUP),this.element.classList.remove(this.classes.DROPDOWN)}drop(dropdata){"cm"==dropdata.type&&this.reactive.dispatch("cmMove",[dropdata.id],this.id),"section"==dropdata.type&&this.reactive.dispatch("sectionMove",[dropdata.id],this.id)}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/dndsectionitem",["exports","core/reactive"],(function(_exports,_reactive){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Course index section title draggable component. * * This component is used to control specific course section interactions like drag and drop * in both course index and course content. * * @module core_courseformat/local/courseeditor/dndsectionitem * @class core_courseformat/local/courseeditor/dndsectionitem * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class _default extends _reactive.BaseComponent{configDragDrop(sectionid,state,fullregion){this.id=sectionid,void 0===this.section&&(this.section=state.section.get(this.id)),void 0===this.course&&(this.course=state.course),this.section.number>0&&(this.getDraggableData=this._getDraggableData),this.fullregion=fullregion,this.reactive.isEditing&&this.reactive.supportComponents&&(this.dragdrop=new _reactive.DragDrop(this),this.classes=this.dragdrop.getClasses())}destroy(){void 0!==this.dragdrop&&this.dragdrop.unregister()}dragStart(dropdata){this.reactive.dispatch("sectionDrag",[dropdata.id],!0)}dragEnd(dropdata){this.reactive.dispatch("sectionDrag",[dropdata.id],!1)}_getDraggableData(){return this.reactive.getExporter().sectionDraggableData(this.reactive.state,this.id)}validateDropData(dropdata){if("cm"===(null==dropdata?void 0:dropdata.type)){var _this$section;const firstcmid=null===(_this$section=this.section)||void 0===_this$section?void 0:_this$section.cmlist[0];return dropdata.id!==firstcmid}return!1}showDropZone(){this.element.classList.add(this.classes.DROPZONE)}hideDropZone(){this.element.classList.remove(this.classes.DROPZONE)}drop(dropdata){var _this$section2;"cm"==dropdata.type&&this.reactive.dispatch("cmMove",[dropdata.id],this.id,null===(_this$section2=this.section)||void 0===_this$section2?void 0:_this$section2.cmlist[0])}}return _exports.default=_default,_exports.default})); define("core_courseformat/local/courseeditor/exporter",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default= /** * Module to export parts of the state and transform them to be used in templates * and as draggable data. * * @module core_courseformat/local/courseeditor/exporter * @class core_courseformat/local/courseeditor/exporter * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class{constructor(reactive){this.reactive=reactive,this.COMPLETIONS=["incomplete","complete","complete","fail"]}course(state){var _state$course$highlig,_state$course$section;const data={sections:[],editmode:this.reactive.isEditing,highlighted:null!==(_state$course$highlig=state.course.highlighted)&&void 0!==_state$course$highlig?_state$course$highlig:""};return(null!==(_state$course$section=state.course.sectionlist)&&void 0!==_state$course$section?_state$course$section:[]).forEach((sectionid=>{var _state$section$get;const sectioninfo=null!==(_state$section$get=state.section.get(sectionid))&&void 0!==_state$section$get?_state$section$get:{},section=this.section(state,sectioninfo);data.sections.push(section)})),data.hassections=0!=data.sections.length,data}section(state,sectioninfo){var _state$course$highlig2,_sectioninfo$cmlist;const section={...sectioninfo,highlighted:null!==(_state$course$highlig2=state.course.highlighted)&&void 0!==_state$course$highlig2?_state$course$highlig2:"",cms:[]};return(null!==(_sectioninfo$cmlist=sectioninfo.cmlist)&&void 0!==_sectioninfo$cmlist?_sectioninfo$cmlist:[]).forEach((cmid=>{const cminfo=state.cm.get(cmid),cm=this.cm(state,cminfo);section.cms.push(cm)})),section.hascms=0!=section.cms.length,section}cm(state,cminfo){return{...cminfo,isactive:!1}}cmDraggableData(state,cmid){const cminfo=state.cm.get(cmid);if(!cminfo)return null;let nextcmid;const section=state.section.get(cminfo.sectionid),currentindex=null==section?void 0:section.cmlist.indexOf(cminfo.id);return void 0!==currentindex&&(nextcmid=null==section?void 0:section.cmlist[currentindex+1]),{type:"cm",id:cminfo.id,name:cminfo.name,sectionid:cminfo.sectionid,nextcmid:nextcmid}}sectionDraggableData(state,sectionid){const sectioninfo=state.section.get(sectionid);return sectioninfo?{type:"section",id:sectioninfo.id,name:sectioninfo.name,number:sectioninfo.number}:null}cmCompletion(state,cminfo){const data={statename:"",state:"NaN"};if(void 0!==cminfo.completionstate){var _this$COMPLETIONS$cmi;data.state=cminfo.completionstate,data.hasstate=!0;const statename=null!==(_this$COMPLETIONS$cmi=this.COMPLETIONS[cminfo.completionstate])&&void 0!==_this$COMPLETIONS$cmi?_this$COMPLETIONS$cmi:"NaN";data["is".concat(statename)]=!0}return data}allItemsArray(state){var _state$course$section2;const items=[];return(null!==(_state$course$section2=state.course.sectionlist)&&void 0!==_state$course$section2?_state$course$section2:[]).forEach((sectionid=>{var _sectioninfo$cmlist2;const sectioninfo=state.section.get(sectionid);items.push({type:"section",id:sectioninfo.id,url:sectioninfo.sectionurl});(null!==(_sectioninfo$cmlist2=sectioninfo.cmlist)&&void 0!==_sectioninfo$cmlist2?_sectioninfo$cmlist2:[]).forEach((cmid=>{const cminfo=state.cm.get(cmid);items.push({type:"cm",id:cminfo.id,url:cminfo.url})}))})),items}},_exports.default})); define("core_courseformat/local/courseeditor/mutations",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Default mutation manager * * @module core_courseformat/local/courseeditor/mutations * @class core_courseformat/local/courseeditor/mutations * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};return _exports.default=class{async _callEditWebservice(action,courseId,ids,targetSectionId,targetCmId){const args={action:action,courseid:courseId,ids:ids};targetSectionId&&(args.targetsectionid=targetSectionId),targetCmId&&(args.targetcmid=targetCmId);let ajaxresult=await _ajax.default.call([{methodname:"core_courseformat_update_course",args:args}])[0];return JSON.parse(ajaxresult)}async _sectionBasicAction(stateManager,action,sectionIds,targetSectionId,targetCmId){const course=stateManager.get("course");this.sectionLock(stateManager,sectionIds,!0);const updates=await this._callEditWebservice(action,course.id,sectionIds,targetSectionId,targetCmId);stateManager.processUpdates(updates),this.sectionLock(stateManager,sectionIds,!1)}async _cmBasicAction(stateManager,action,cmIds,targetSectionId,targetCmId){const course=stateManager.get("course");this.cmLock(stateManager,cmIds,!0);const updates=await this._callEditWebservice(action,course.id,cmIds,targetSectionId,targetCmId);stateManager.processUpdates(updates),this.cmLock(stateManager,cmIds,!1)}init(stateManager){stateManager.addUpdateTypes({prepareFields:this._prepareFields})}_prepareFields(stateManager,updateName,fields){return fields.locked=!1,fields}async sectionHide(stateManager,sectionIds){await this._sectionBasicAction(stateManager,"section_hide",sectionIds)}async sectionShow(stateManager,sectionIds){await this._sectionBasicAction(stateManager,"section_show",sectionIds)}async cmShow(stateManager,cmIds){await this._cmBasicAction(stateManager,"cm_show",cmIds)}async cmHide(stateManager,cmIds){await this._cmBasicAction(stateManager,"cm_hide",cmIds)}async cmStealth(stateManager,cmIds){await this._cmBasicAction(stateManager,"cm_stealth",cmIds)}async cmMove(stateManager,cmids,targetSectionId,targetCmId){if(!targetSectionId&&!targetCmId)throw new Error("Mutation cmMove requires targetSectionId or targetCmId");const course=stateManager.get("course");this.cmLock(stateManager,cmids,!0);const updates=await this._callEditWebservice("cm_move",course.id,cmids,targetSectionId,targetCmId);stateManager.processUpdates(updates),this.cmLock(stateManager,cmids,!1)}async sectionMove(stateManager,sectionIds,targetSectionId){if(!targetSectionId)throw new Error("Mutation sectionMove requires targetSectionId");const course=stateManager.get("course");this.sectionLock(stateManager,sectionIds,!0);const updates=await this._callEditWebservice("section_move",course.id,sectionIds,targetSectionId);stateManager.processUpdates(updates),this.sectionLock(stateManager,sectionIds,!1)}async addSection(stateManager,targetSectionId){targetSectionId||(targetSectionId=0);const course=stateManager.get("course"),updates=await this._callEditWebservice("section_add",course.id,[],targetSectionId);stateManager.processUpdates(updates)}async sectionDelete(stateManager,sectionIds){const course=stateManager.get("course"),updates=await this._callEditWebservice("section_delete",course.id,sectionIds);stateManager.processUpdates(updates)}cmDrag(stateManager,cmIds,dragValue){this.setPageItem(stateManager),this._setElementsValue(stateManager,"cm",cmIds,"dragging",dragValue)}sectionDrag(stateManager,sectionIds,dragValue){this.setPageItem(stateManager),this._setElementsValue(stateManager,"section",sectionIds,"dragging",dragValue)}cmCompletion(stateManager,cmIds,complete){const newValue=complete?1:0;this._setElementsValue(stateManager,"cm",cmIds,"completionstate",newValue)}async cmMoveRight(stateManager,cmIds){await this._cmBasicAction(stateManager,"cm_moveright",cmIds)}async cmMoveLeft(stateManager,cmIds){await this._cmBasicAction(stateManager,"cm_moveleft",cmIds)}cmLock(stateManager,cmIds,lockValue){this._setElementsValue(stateManager,"cm",cmIds,"locked",lockValue)}sectionLock(stateManager,sectionIds,lockValue){this._setElementsValue(stateManager,"section",sectionIds,"locked",lockValue)}_setElementsValue(stateManager,name,ids,fieldName,newValue){stateManager.setReadOnly(!1),ids.forEach((id=>{const element=stateManager.get(name,id);element&&(element[fieldName]=newValue)})),stateManager.setReadOnly(!0)}setPageItem(stateManager,type,id,isStatic){let newPageItem;if(void 0!==type&&(newPageItem=stateManager.get(type,id),!newPageItem))return;stateManager.setReadOnly(!1);const course=stateManager.get("course");course.pageItem=null,newPageItem&&(course.pageItem={id:id,type:type,sectionId:"section"==type?newPageItem.id:newPageItem.sectionid,isStatic:isStatic}),stateManager.setReadOnly(!0)}unlockAll(stateManager){const state=stateManager.state;stateManager.setReadOnly(!1),state.section.forEach((section=>{section.locked=!1})),state.cm.forEach((cm=>{cm.locked=!1})),stateManager.setReadOnly(!0)}async sectionIndexCollapsed(stateManager,sectionIds,collapsed){const collapsedIds=this._updateStateSectionPreference(stateManager,"indexcollapsed",sectionIds,collapsed);if(!collapsedIds)return;const course=stateManager.get("course");await this._callEditWebservice("section_index_collapsed",course.id,collapsedIds)}async sectionContentCollapsed(stateManager,sectionIds,collapsed){const collapsedIds=this._updateStateSectionPreference(stateManager,"contentcollapsed",sectionIds,collapsed);if(!collapsedIds)return;const course=stateManager.get("course");await this._callEditWebservice("section_content_collapsed",course.id,collapsedIds)}_updateStateSectionPreference(stateManager,preferenceName,sectionIds,preferenceValue){stateManager.setReadOnly(!1);const affectedSections=new Set;if(sectionIds.forEach((sectionId=>{const section=stateManager.get("section",sectionId);if(void 0===section)return null;const newValue=null!=preferenceValue?preferenceValue:section[preferenceName];section[preferenceName]!=newValue&&(section[preferenceName]=newValue,affectedSections.add(section.id))})),stateManager.setReadOnly(!0),0==affectedSections.size)return null;const collapsedSectionIds=[];return stateManager.state.section.forEach((section=>{section[preferenceName]&&collapsedSectionIds.push(section.id)})),collapsedSectionIds}async cmState(stateManager,cmids){this.cmLock(stateManager,cmids,!0);const course=stateManager.get("course"),updates=await this._callEditWebservice("cm_state",course.id,cmids);stateManager.processUpdates(updates),this.cmLock(stateManager,cmids,!1)}async sectionState(stateManager,sectionIds){this.sectionLock(stateManager,sectionIds,!0);const course=stateManager.get("course"),updates=await this._callEditWebservice("section_state",course.id,sectionIds);stateManager.processUpdates(updates),this.sectionLock(stateManager,sectionIds,!1)}async courseState(stateManager){const course=stateManager.get("course"),updates=await this._callEditWebservice("course_state",course.id);stateManager.processUpdates(updates)}},_exports.default})); define("core_courseformat/local/courseindex/cm",["exports","core_courseformat/local/courseeditor/dndcmitem","core/templates","core/prefetch","core/config"],(function(_exports,_dndcmitem,_templates,_prefetch,_config){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index cm component. * * This component is used to control specific course modules interactions like drag and drop. * * @module core_courseformat/local/courseindex/cm * @class core_courseformat/local/courseindex/cm * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndcmitem=_interopRequireDefault(_dndcmitem),_templates=_interopRequireDefault(_templates),_prefetch=_interopRequireDefault(_prefetch),_config=_interopRequireDefault(_config);_prefetch.default.prefetchTemplate("core_courseformat/local/courseindex/cmcompletion");class Component extends _dndcmitem.default{create(){this.name="courseindex_cm",this.selectors={CM_NAME:"[data-for='cm_name']",CM_COMPLETION:"[data-for='cm_completion']"},this.classes={CMHIDDEN:"dimmed",LOCKED:"editinprogress",RESTRICTIONS:"restrictions",PAGEITEM:"pageitem",INDENTED:"indented"},this.id=this.element.dataset.id}static init(target,selectors){return new Component({element:document.getElementById(target),selectors:selectors})}stateReady(state){this.configDragDrop(this.id);const cm=state.cm.get(this.id),course=state.course;this._refreshCompletion({state:state,element:cm});const anchor=new URL(window.location.href).hash.replace("#","");(window.location.href==cm.url||window.location.href.includes(course.baseurl)&&anchor==cm.anchor)&&(this.reactive.dispatch("setPageItem","cm",this.id),this.element.scrollIntoView({block:"center"})),_config.default.contextid!=_config.default.courseContextId&&_config.default.contextInstanceId==this.id&&(this.reactive.dispatch("setPageItem","cm",this.id,!0),this.element.scrollIntoView({block:"center"})),cm.uservisible||this.addEventListener(this.getElement(this.selectors.CM_NAME),"click",this._activityAnchor)}getWatchers(){return[{watch:"cm[".concat(this.id,"]:deleted"),handler:this.remove},{watch:"cm[".concat(this.id,"]:updated"),handler:this._refreshCm},{watch:"cm[".concat(this.id,"].completionstate:updated"),handler:this._refreshCompletion},{watch:"course.pageItem:updated",handler:this._refreshPageItem}]}_refreshCm(_ref){var _element$dragging,_element$locked,_element$hascmrestric;let{element:element}=_ref;this.element.classList.toggle(this.classes.CMHIDDEN,!element.visible),this.getElement(this.selectors.CM_NAME).innerHTML=element.name,this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.element.classList.toggle(this.classes.RESTRICTIONS,null!==(_element$hascmrestric=element.hascmrestrictions)&&void 0!==_element$hascmrestric&&_element$hascmrestric),this.element.classList.toggle(this.classes.INDENTED,element.indent),this.locked=element.locked}_refreshPageItem(_ref2){let{element:element}=_ref2;if(!element.pageItem)return;const isPageId="cm"==element.pageItem.type&&element.pageItem.id==this.id;this.element.classList.toggle(this.classes.PAGEITEM,isPageId),isPageId&&!this.reactive.isEditing&&this.element.scrollIntoView({block:"nearest"})}async _refreshCompletion(_ref3){let{state:state,element:element}=_ref3;if(this.reactive.isEditing||!element.istrackeduser)return;const completionElement=this.getElement(this.selectors.CM_COMPLETION);if(completionElement.dataset.value==element.completionstate)return;const data=this.reactive.getExporter().cmCompletion(state,element);try{const{html:html,js:js}=await _templates.default.renderForPromise("core_courseformat/local/courseindex/cmcompletion",data);_templates.default.replaceNode(completionElement,html,js)}catch(error){throw error}}_activityAnchor(event){const cm=this.reactive.get("cm",this.id);if(document.getElementById(cm.anchor))return void setTimeout((()=>{this.reactive.dispatch("setPageItem","cm",cm.id)}),50);const course=this.reactive.get("course"),section=this.reactive.get("section",cm.sectionid);if(!section)return;const url="".concat(course.baseurl,"§ion=").concat(section.number,"#").concat(cm.anchor);event.preventDefault(),window.location=url}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/courseindex/courseindex",["exports","core/reactive","core_courseformat/courseeditor","jquery","core_courseformat/local/courseeditor/contenttree"],(function(_exports,_reactive,_courseeditor,_jquery,_contenttree){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index main component. * * @module core_courseformat/local/courseindex/courseindex * @class core_courseformat/local/courseindex/courseindex * @copyright 2021 Ferran Recio <ferran@moodle.com> * @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),_contenttree=_interopRequireDefault(_contenttree);class Component extends _reactive.BaseComponent{create(){this.name="courseindex",this.selectors={SECTION:"[data-for='section']",SECTION_CMLIST:"[data-for='cmlist']",CM:"[data-for='cm']",TOGGLER:'[data-action="togglecourseindexsection"]',COLLAPSE:'[data-toggle="collapse"]',DRAWER:".drawer"},this.classes={SECTIONHIDDEN:"dimmed",CMHIDDEN:"dimmed",SECTIONCURRENT:"current",COLLAPSED:"collapsed",SHOW:"show"},this.sections={},this.cms={}}static init(target,selectors){return new Component({element:document.getElementById(target),reactive:(0,_courseeditor.getCurrentCourseEditor)(),selectors:selectors})}stateReady(state){this.addEventListener(this.element,"click",this._sectionTogglers);this.getElements(this.selectors.SECTION).forEach((section=>{this.sections[section.dataset.id]=section}));this.getElements(this.selectors.CM).forEach((cm=>{this.cms[cm.dataset.id]=cm})),this._refreshPageItem({element:state.course,state:state}),this.contentTree=new _contenttree.default(this.element,this.selectors,this.reactive.isEditing)}getWatchers(){return[{watch:"section.indexcollapsed:updated",handler:this._refreshSectionCollapsed},{watch:"cm:created",handler:this._createCm},{watch:"cm:deleted",handler:this._deleteCm},{watch:"section:created",handler:this._createSection},{watch:"section:deleted",handler:this._deleteSection},{watch:"course.pageItem:created",handler:this._refreshPageItem},{watch:"course.pageItem:updated",handler:this._refreshPageItem},{watch:"course.sectionlist:updated",handler:this._refreshCourseSectionlist},{watch:"section.cmlist:updated",handler:this._refreshSectionCmlist}]}_sectionTogglers(event){const sectionlink=event.target.closest(this.selectors.TOGGLER),isChevron=event.target.closest(this.selectors.COLLAPSE);if(sectionlink||isChevron){var _toggler$classList$co;const section=event.target.closest(this.selectors.SECTION),toggler=section.querySelector(this.selectors.COLLAPSE),isCollapsed=null!==(_toggler$classList$co=null==toggler?void 0:toggler.classList.contains(this.classes.COLLAPSED))&&void 0!==_toggler$classList$co&&_toggler$classList$co;if(isChevron||isCollapsed){const sectionId=section.getAttribute("data-id");this.reactive.dispatch("sectionIndexCollapsed",[sectionId],!isCollapsed)}}}_refreshSectionCollapsed(_ref){var _toggler$classList$co2;let{element:element}=_ref;const target=this.getElement(this.selectors.SECTION,element.id);if(!target)throw new Error("Unkown section with ID ".concat(element.id));const toggler=target.querySelector(this.selectors.COLLAPSE),isCollapsed=null!==(_toggler$classList$co2=null==toggler?void 0:toggler.classList.contains(this.classes.COLLAPSED))&&void 0!==_toggler$classList$co2&&_toggler$classList$co2;element.indexcollapsed!==isCollapsed&&this._expandSectionNode(element)}_expandSectionNode(element,forceValue){var _toggler$dataset$targ;const toggler=this.getElement(this.selectors.SECTION,element.id).querySelector(this.selectors.COLLAPSE);let collapsibleId=null!==(_toggler$dataset$targ=toggler.dataset.target)&&void 0!==_toggler$dataset$targ?_toggler$dataset$targ:toggler.getAttribute("href");if(!collapsibleId)return;collapsibleId=collapsibleId.replace("#","");const collapsible=document.getElementById(collapsibleId);if(!collapsible)return;void 0===forceValue&&(forceValue=!element.indexcollapsed);const togglerValue=forceValue?"show":"hide";(0,_jquery.default)(collapsible).collapse(togglerValue)}_refreshPageItem(_ref2){var _element$pageItem;let{element:element,state:state}=_ref2;if(null==element||null===(_element$pageItem=element.pageItem)||void 0===_element$pageItem||!_element$pageItem.isStatic||"cm"!=element.pageItem.type)return;const section=state.section.get(element.pageItem.sectionId);section.indexcollapsed&&(this._expandSectionNode(section,!0),setTimeout((()=>{var _this$cms$element$pag;return null===(_this$cms$element$pag=this.cms[element.pageItem.id])||void 0===_this$cms$element$pag?void 0:_this$cms$element$pag.scrollIntoView({block:"nearest"})}),250))}async _createCm(_ref3){let{state:state,element:element}=_ref3;const fakeelement=document.createElement("li");fakeelement.classList.add("bg-pulse-grey","w-100"),fakeelement.innerHTML=" ",this.cms[element.id]=fakeelement,this._refreshSectionCmlist({state:state,element:state.section.get(element.sectionid)});const data=this.reactive.getExporter().cm(state,element),newelement=(await this.renderComponent(fakeelement,"core_courseformat/local/courseindex/cm",data)).getElement();this.cms[element.id]=newelement,fakeelement.parentNode.replaceChild(newelement,fakeelement)}async _createSection(_ref4){let{state:state,element:element}=_ref4;const fakeelement=document.createElement("div");fakeelement.classList.add("bg-pulse-grey","w-100"),fakeelement.innerHTML=" ",this.sections[element.id]=fakeelement,this._refreshCourseSectionlist({state:state,element:state.course});const data=this.reactive.getExporter().section(state,element),newelement=(await this.renderComponent(fakeelement,"core_courseformat/local/courseindex/section",data)).getElement();this.sections[element.id]=newelement,fakeelement.parentNode.replaceChild(newelement,fakeelement)}_refreshSectionCmlist(_ref5){var _element$cmlist;let{element:element}=_ref5;const cmlist=null!==(_element$cmlist=element.cmlist)&&void 0!==_element$cmlist?_element$cmlist:[],listparent=this.getElement(this.selectors.SECTION_CMLIST,element.id);this._fixOrder(listparent,cmlist,this.cms)}_refreshCourseSectionlist(_ref6){var _element$sectionlist;let{element:element}=_ref6;const sectionlist=null!==(_element$sectionlist=element.sectionlist)&&void 0!==_element$sectionlist?_element$sectionlist:[];this._fixOrder(this.element,sectionlist,this.sections)}_fixOrder(container,neworder,allitems){if(!neworder.length)return container.classList.add("hidden"),void(container.innerHTML="");for(container.classList.remove("hidden"),neworder.forEach(((itemid,index)=>{const item=allitems[itemid],currentitem=container.children[index];void 0!==currentitem?currentitem!==item&&container.insertBefore(item,currentitem):container.append(item)}));container.children.length>neworder.length;)container.removeChild(container.lastChild)}_deleteCm(_ref7){let{element:element}=_ref7;delete this.cms[element.id]}_deleteSection(_ref8){let{element:element}=_ref8;delete this.sections[element.id]}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/courseindex/drawer",["exports","core/reactive","core_courseformat/courseeditor"],(function(_exports,_reactive,_courseeditor){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Course index drawer wrap. * * This component is mostly used to ensure all subcomponents find a parent * compoment with a reactive instance defined. * * @module core_courseformat/local/courseindex/drawer * @class core_courseformat/local/courseindex/drawer * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class Component extends _reactive.BaseComponent{create(){this.name="courseindex-drawer"}static init(target,selectors){return new Component({element:document.getElementById(target),reactive:(0,_courseeditor.getCurrentCourseEditor)(),selectors:selectors})}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/courseindex/placeholder",["exports","core/reactive","core/templates","core_courseformat/courseeditor","core/pending"],(function(_exports,_reactive,_templates,_courseeditor,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index placeholder replacer. * * @module core_courseformat/local/courseindex/placeholder * @class core_courseformat/local/courseindex/placeholder * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=_interopRequireDefault(_templates),_pending=_interopRequireDefault(_pending);class Component extends _reactive.BaseComponent{static init(target,selectors){return new Component({element:document.getElementById(target),reactive:(0,_courseeditor.getCurrentCourseEditor)(),selectors:selectors})}create(){this.pendingContent=new _pending.default("core_courseformat/placeholder:loadcourseindex")}async stateReady(state){this.loadStaticContent()||await this.loadTemplateContent(state)}loadStaticContent(){const index=this.reactive.getStorageValue("courseIndex");return!(!index.html||!index.js)&&(_templates.default.replaceNode(this.element,index.html,index.js),this.pendingContent.resolve(),!0)}async loadTemplateContent(state){const data=this.reactive.getExporter().course(state);try{const{html:html,js:js}=await _templates.default.renderForPromise("core_courseformat/local/courseindex/courseindex",data);_templates.default.replaceNode(this.element,html,js),this.pendingContent.resolve(),this.reactive.setStorageValue("courseIndex",{html:html,js:js})}catch(error){throw this.pendingContent.resolve(error),error}}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/courseindex/section",["exports","core_courseformat/local/courseindex/sectiontitle","core_courseformat/local/courseeditor/dndsection"],(function(_exports,_sectiontitle,_dndsection){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index section component. * * This component is used to control specific course section interactions like drag and drop. * * @module core_courseformat/local/courseindex/section * @class core_courseformat/local/courseindex/section * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_sectiontitle=_interopRequireDefault(_sectiontitle),_dndsection=_interopRequireDefault(_dndsection);class Component extends _dndsection.default{create(){this.name="courseindex_section",this.selectors={SECTION_ITEM:"[data-for='section_item']",SECTION_TITLE:"[data-for='section_title']",CM_LAST:'[data-for="cm"]:last-child'},this.classes={SECTIONHIDDEN:"dimmed",SECTIONCURRENT:"current",LOCKED:"editinprogress",RESTRICTIONS:"restrictions",PAGEITEM:"pageitem"},this.id=this.element.dataset.id,this.isPageItem=!1}static init(target,selectors){return new Component({element:document.getElementById(target),selectors:selectors})}stateReady(state){this.configState(state);const sectionItem=this.getElement(this.selectors.SECTION_ITEM);if(this.reactive.isEditing&&this.reactive.supportComponents){const titleitem=new _sectiontitle.default({...this,element:sectionItem,fullregion:this.element});this.configDragDrop(titleitem)}const section=state.section.get(this.id);window.location.href==section.sectionurl.replace(/&/g,"&")&&(this.reactive.dispatch("setPageItem","section",this.id),sectionItem.scrollIntoView())}getWatchers(){return[{watch:"section[".concat(this.id,"]:deleted"),handler:this.remove},{watch:"section[".concat(this.id,"]:updated"),handler:this._refreshSection},{watch:"course.pageItem:updated",handler:this._refreshPageItem}]}getLastCm(){return this.getElement(this.selectors.CM_LAST)}_refreshSection(_ref){var _element$hasrestricti,_element$dragging,_element$locked;let{element:element}=_ref;const sectionItem=this.getElement(this.selectors.SECTION_ITEM);sectionItem.classList.toggle(this.classes.SECTIONHIDDEN,!element.visible),sectionItem.classList.toggle(this.classes.RESTRICTIONS,null!==(_element$hasrestricti=element.hasrestrictions)&&void 0!==_element$hasrestricti&&_element$hasrestricti),this.element.classList.toggle(this.classes.SECTIONCURRENT,element.current),this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.locked=element.locked,this.getElement(this.selectors.SECTION_TITLE).innerHTML=element.title}_refreshPageItem(_ref2){var _element$pageItem,_this$pageItem;let{element:element,state:state}=_ref2;if(!element.pageItem)return;if(element.pageItem.sectionId!==this.id&&this.isPageItem)return this.pageItem=!1,void this.getElement(this.selectors.SECTION_ITEM).classList.remove(this.classes.PAGEITEM);var _element$pageItem2;!state.section.get(this.id).indexcollapsed||null!==(_element$pageItem=element.pageItem)&&void 0!==_element$pageItem&&_element$pageItem.isStatic?this.pageItem="section"==element.pageItem.type&&element.pageItem.id==this.id:this.pageItem=(null===(_element$pageItem2=element.pageItem)||void 0===_element$pageItem2?void 0:_element$pageItem2.sectionId)==this.id;this.getElement(this.selectors.SECTION_ITEM).classList.toggle(this.classes.PAGEITEM,null!==(_this$pageItem=this.pageItem)&&void 0!==_this$pageItem&&_this$pageItem),this.pageItem&&!this.reactive.isEditing&&this.element.scrollIntoView({block:"nearest"})}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/courseindex/sectiontitle",["exports","core_courseformat/local/courseeditor/dndsectionitem"],(function(_exports,_dndsectionitem){var obj; /** * Course index section title component. * * This component is used to control specific course section interactions like drag and drop. * * @module core_courseformat/local/courseindex/sectiontitle * @class core_courseformat/local/courseindex/sectiontitle * @copyright 2021 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndsectionitem=(obj=_dndsectionitem)&&obj.__esModule?obj:{default:obj};class Component extends _dndsectionitem.default{create(descriptor){this.name="courseindex_sectiontitle",this.id=descriptor.id,this.section=descriptor.section,this.course=descriptor.course,this.fullregion=descriptor.fullregion,this.section.number>0&&(this.getDraggableData=this._getDraggableData)}static init(target,selectors){return new Component({element:document.getElementById(target),selectors:selectors})}stateReady(state){this.configDragDrop(this.id,state,this.fullregion)}}return _exports.default=Component,_exports.default})); define("core_courseformat/local/content",["exports","core/reactive","core_courseformat/courseeditor","core/inplace_editable","core_courseformat/local/content/section","core_courseformat/local/content/section/cmitem","core_course/actions","core_courseformat/local/content/actions","core_course/events","jquery"],(function(_exports,_reactive,_courseeditor,_inplace_editable,_section,_cmitem,_actions,_actions2,CourseEvents,_jquery){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Course index main component. * * @module core_courseformat/local/content * @class core_courseformat/local/content * @copyright 2020 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_inplace_editable=_interopRequireDefault(_inplace_editable),_section=_interopRequireDefault(_section),_cmitem=_interopRequireDefault(_cmitem),_actions=_interopRequireDefault(_actions),_actions2=_interopRequireDefault(_actions2),CourseEvents=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(CourseEvents),_jquery=_interopRequireDefault(_jquery);class Component extends _reactive.BaseComponent{create(descriptor){var _descriptor$sectionRe;this.name="course_format",this.selectors={SECTION:"[data-for='section']",SECTION_ITEM:"[data-for='section_title']",SECTION_CMLIST:"[data-for='cmlist']",COURSE_SECTIONLIST:"[data-for='course_sectionlist']",CM:"[data-for='cmitem']",PAGE:"#page",TOGGLER:'[data-action="togglecoursecontentsection"]',COLLAPSE:'[data-toggle="collapse"]',TOGGLEALL:'[data-toggle="toggleall"]',ACTIVITYTAG:"li",SECTIONTAG:"li"},this.classes={COLLAPSED:"collapsed",ACTIVITY:"activity",STATEDREADY:"stateready",SECTION:"section"},this.dettachedCms={},this.dettachedSections={},this.sections={},this.cms={},this.sectionReturn=null!==(_descriptor$sectionRe=descriptor.sectionReturn)&&void 0!==_descriptor$sectionRe?_descriptor$sectionRe:0}static init(target,selectors,sectionReturn){return new Component({element:document.getElementById(target),reactive:(0,_courseeditor.getCurrentCourseEditor)(),selectors:selectors,sectionReturn:sectionReturn})}stateReady(state){this._indexContents(),this.addEventListener(this.element,"click",this._sectionTogglers);const toogleAll=this.getElement(this.selectors.TOGGLEALL);if(toogleAll){const collapseElementIds=[...this.getElements(this.selectors.COLLAPSE)].map((element=>element.id));toogleAll.setAttribute("aria-controls",collapseElementIds.join(" ")),this.addEventListener(toogleAll,"click",this._allSectionToggler),this.addEventListener(toogleAll,"keydown",(e=>{" "===e.key&&this._allSectionToggler(e)})),this._refreshAllSectionsToggler(state)}this.reactive.supportComponents&&(this.reactive.isEditing&&new _actions2.default(this),this.element.classList.add(this.classes.STATEDREADY)),this.addEventListener(this.element,CourseEvents.manualCompletionToggled,this._completionHandler),this.addEventListener(document.querySelector(this.selectors.PAGE),"scroll",this._scrollHandler)}_sectionTogglers(event){const sectionlink=event.target.closest(this.selectors.TOGGLER),closestCollapse=event.target.closest(this.selectors.COLLAPSE),isChevron=null==closestCollapse?void 0:closestCollapse.closest(this.selectors.SECTION_ITEM);if(sectionlink||isChevron){var _toggler$classList$co;const section=event.target.closest(this.selectors.SECTION),toggler=section.querySelector(this.selectors.COLLAPSE),isCollapsed=null!==(_toggler$classList$co=null==toggler?void 0:toggler.classList.contains(this.classes.COLLAPSED))&&void 0!==_toggler$classList$co&&_toggler$classList$co;if(isChevron||isCollapsed){const sectionId=section.getAttribute("data-id");this.reactive.dispatch("sectionContentCollapsed",[sectionId],!isCollapsed)}}}_allSectionToggler(event){var _course$sectionlist;event.preventDefault();const isAllCollapsed=event.target.closest(this.selectors.TOGGLEALL).classList.contains(this.classes.COLLAPSED),course=this.reactive.get("course");this.reactive.dispatch("sectionContentCollapsed",null!==(_course$sectionlist=course.sectionlist)&&void 0!==_course$sectionlist?_course$sectionlist:[],!isAllCollapsed)}getWatchers(){return this.reactive.sectionReturn=this.sectionReturn,this.reactive.supportComponents?[{watch:"cm.visible:updated",handler:this._reloadCm},{watch:"cm.stealth:updated",handler:this._reloadCm},{watch:"cm.indent:updated",handler:this._reloadCm},{watch:"section.number:updated",handler:this._refreshSectionNumber},{watch:"section.contentcollapsed:updated",handler:this._refreshSectionCollapsed},{watch:"transaction:start",handler:this._startProcessing},{watch:"course.sectionlist:updated",handler:this._refreshCourseSectionlist},{watch:"section.cmlist:updated",handler:this._refreshSectionCmlist},{watch:"state:updated",handler:this._indexContents},{watch:"cm.visible:updated",handler:this._reloadCm},{watch:"cm.sectionid:updated",handler:this._reloadCm}]:[]}_refreshSectionCollapsed(_ref){var _toggler$classList$co2;let{state:state,element:element}=_ref;const target=this.getElement(this.selectors.SECTION,element.id);if(!target)throw new Error("Unknown section with ID ".concat(element.id));const toggler=target.querySelector(this.selectors.COLLAPSE),isCollapsed=null!==(_toggler$classList$co2=null==toggler?void 0:toggler.classList.contains(this.classes.COLLAPSED))&&void 0!==_toggler$classList$co2&&_toggler$classList$co2;if(element.contentcollapsed!==isCollapsed){var _toggler$dataset$targ;let collapsibleId=null!==(_toggler$dataset$targ=toggler.dataset.target)&&void 0!==_toggler$dataset$targ?_toggler$dataset$targ:toggler.getAttribute("href");if(!collapsibleId)return;collapsibleId=collapsibleId.replace("#","");const collapsible=document.getElementById(collapsibleId);if(!collapsible)return;(0,_jquery.default)(collapsible).collapse(element.contentcollapsed?"hide":"show")}this._refreshAllSectionsToggler(state)}_refreshAllSectionsToggler(state){const target=this.getElement(this.selectors.TOGGLEALL);if(!target)return;let allcollapsed=!0,allexpanded=!0;state.section.forEach((section=>{allcollapsed=allcollapsed&§ion.contentcollapsed,allexpanded=allexpanded&&!section.contentcollapsed})),allcollapsed&&(target.classList.add(this.classes.COLLAPSED),target.setAttribute("aria-expanded",!1)),allexpanded&&(target.classList.remove(this.classes.COLLAPSED),target.setAttribute("aria-expanded",!0))}_startProcessing(){this.dettachedCms={},this.dettachedSections={}}_completionHandler(_ref2){let{detail:detail}=_ref2;void 0!==detail&&this.reactive.dispatch("cmCompletion",[detail.cmid],detail.completed)}_scrollHandler(){const pageOffset=document.querySelector(this.selectors.PAGE).scrollTop,items=this.reactive.getExporter().allItemsArray(this.reactive.state);let pageItem=null;items.every((item=>{const index="section"===item.type?this.sections:this.cms;if(void 0===index[item.id])return!0;const element=index[item.id].element;return"cm"!==item.type||item.url||this.reactive.isEditing?(pageItem=item,pageOffset>=element.offsetTop):pageOffset>=element.offsetTop})),pageItem&&this.reactive.dispatch("setPageItem",pageItem.type,pageItem.id)}_refreshSectionNumber(_ref3){let{element:element}=_ref3;const target=this.getElement(this.selectors.SECTION,element.id);if(!target)return;target.id="section-".concat(element.number),target.dataset.sectionid=element.number,target.dataset.number=element.number;const inplace=_inplace_editable.default.getInplaceEditable(target.querySelector(this.selectors.SECTION_ITEM));if(inplace){const currentvalue=inplace.getValue(),currentitemid=inplace.getItemId();""===inplace.getValue()&&(currentitemid!=element.id||currentvalue==element.rawtitle&&""!=element.rawtitle||inplace.setValue(element.rawtitle))}}_refreshSectionCmlist(_ref4){var _element$cmlist;let{element:element}=_ref4;const cmlist=null!==(_element$cmlist=element.cmlist)&&void 0!==_element$cmlist?_element$cmlist:[],section=this.getElement(this.selectors.SECTION,element.id),listparent=null==section?void 0:section.querySelector(this.selectors.SECTION_CMLIST),createCm=this._createCmItem.bind(this);listparent&&this._fixOrder(listparent,cmlist,this.selectors.CM,this.dettachedCms,createCm)}_refreshCourseSectionlist(_ref5){var _element$sectionlist;let{element:element}=_ref5;if(0!=this.reactive.sectionReturn)return;const sectionlist=null!==(_element$sectionlist=element.sectionlist)&&void 0!==_element$sectionlist?_element$sectionlist:[],listparent=this.getElement(this.selectors.COURSE_SECTIONLIST),createSection=this._createSectionItem.bind(this);listparent&&this._fixOrder(listparent,sectionlist,this.selectors.SECTION,this.dettachedSections,createSection)}_indexContents(){this._scanIndex(this.selectors.SECTION,this.sections,(item=>new _section.default(item))),this._scanIndex(this.selectors.CM,this.cms,(item=>new _cmitem.default(item)))}_scanIndex(selector,index,creationhandler){this.getElements("".concat(selector,":not([data-indexed])")).forEach((item=>{var _item$dataset;null!=item&&null!==(_item$dataset=item.dataset)&&void 0!==_item$dataset&&_item$dataset.id&&(void 0!==index[item.dataset.id]&&index[item.dataset.id].unregister(),index[item.dataset.id]=creationhandler({...this,element:item}),item.dataset.indexed=!0)}))}_reloadCm(_ref6){let{element:element}=_ref6;const cmitem=this.getElement(this.selectors.CM,element.id);if(cmitem){_actions.default.refreshModule(cmitem,element.id).then((()=>{this._indexContents()})).catch()}}_reloadSection(_ref7){let{element:element}=_ref7;const sectionitem=this.getElement(this.selectors.SECTION,element.id);if(sectionitem){_actions.default.refreshSection(sectionitem,element.id).then((()=>{this._indexContents()})).catch()}}_createCmItem(container,cmid){const newItem=document.createElement(this.selectors.ACTIVITYTAG);return newItem.dataset.for="cmitem",newItem.dataset.id=cmid,newItem.id="module-".concat(cmid),newItem.classList.add(this.classes.ACTIVITY),container.append(newItem),this._reloadCm({element:this.reactive.get("cm",cmid)}),newItem}_createSectionItem(container,sectionid){const section=this.reactive.get("section",sectionid),newItem=document.createElement(this.selectors.SECTIONTAG);return newItem.dataset.for="section",newItem.dataset.id=sectionid,newItem.dataset.number=section.number,newItem.id="section-".concat(sectionid),newItem.classList.add(this.classes.SECTION),container.append(newItem),this._reloadSection({element:section}),newItem}async _fixOrder(container,neworder,selector,dettachedelements,createMethod){if(void 0===container)return;if(!neworder.length)return container.classList.add("hidden"),void(container.innerHTML="");let dndFakeActivity;for(container.classList.remove("hidden"),neworder.forEach(((itemid,index)=>{var _ref8,_this$getElement;let item=null!==(_ref8=null!==(_this$getElement=this.getElement(selector,itemid))&&void 0!==_this$getElement?_this$getElement:dettachedelements[itemid])&&void 0!==_ref8?_ref8:createMethod(container,itemid);if(void 0===item)return;const currentitem=container.children[index];void 0!==currentitem?currentitem!==item&&container.insertBefore(item,currentitem):container.append(item)}));container.children.length>neworder.length;){var _lastchild$classList;const lastchild=container.lastChild;var _lastchild$dataset$id,_lastchild$dataset;if(null!=lastchild&&null!==(_lastchild$classList=lastchild.classList)&&void 0!==_lastchild$classList&&_lastchild$classList.contains("dndupload-preview"))dndFakeActivity=lastchild;else dettachedelements[null!==(_lastchild$dataset$id=null==lastchild||null===(_lastchild$dataset=lastchild.dataset)||void 0===_lastchild$dataset?void 0:_lastchild$dataset.id)&&void 0!==_lastchild$dataset$id?_lastchild$dataset$id:0]=lastchild;container.removeChild(lastchild)}dndFakeActivity&&container.append(dndFakeActivity)}}return _exports.default=Component,_exports.default})); define("core_customfield/form",["exports","core/inplace_editable","core/ajax","core/str","core_form/modalform","core/notification","core/pending","core/sortable_list","core/templates","jquery"],(function(_exports,_inplace_editable,_ajax,_str,_modalform,_notification,_pending,_sortable_list,_templates,_jquery){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Custom Field interaction management for Moodle. * * @module core_customfield/form * @copyright 2018 Toni Barbera * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_sortable_list=_interopRequireDefault(_sortable_list),_templates=_interopRequireDefault(_templates),_jquery=_interopRequireDefault(_jquery);const confirmDelete=(id,type,component,area,itemid)=>{const pendingPromise=new _pending.default("core_customfield/form:confirmDelete");(0,_str.get_strings)([{key:"confirm"},{key:"confirmdelete"+type,component:"core_customfield"},{key:"yes"},{key:"no"}]).then((strings=>_notification.default.confirm(strings[0],strings[1],strings[2],strings[3],(function(){const pendingDeletePromise=new _pending.default("core_customfield/form:confirmDelete");(0,_ajax.call)([{methodname:"field"===type?"core_customfield_delete_field":"core_customfield_delete_category",args:{id:id}},{methodname:"core_customfield_reload_template",args:{component:component,area:area,itemid:itemid}}])[1].then((response=>_templates.default.render("core_customfield/list",response))).then(((html,js)=>_templates.default.replaceNode((0,_jquery.default)('[data-region="list-page"]'),html,js))).then(pendingDeletePromise.resolve).catch(_notification.default.exception)})))).then(pendingPromise.resolve).catch(_notification.default.exception)},getCategoryNameFor=nodeElement=>nodeElement.closest("[data-category-id]").find("[data-inplaceeditable][data-itemtype=category][data-component=core_customfield]").attr("data-value");_exports.init=()=>{const rootNode=document.querySelector("#customfield_catlist"),component=rootNode.dataset.component,area=rootNode.dataset.area,itemid=rootNode.dataset.itemid;rootNode.addEventListener("click",(e=>{const roleHolder=e.target.closest("[data-role]");if(roleHolder)return"deletefield"===roleHolder.dataset.role?(e.preventDefault(),void confirmDelete(roleHolder.dataset.id,"field",component,area,itemid)):"deletecategory"===roleHolder.dataset.role?(e.preventDefault(),void confirmDelete(roleHolder.dataset.id,"category",component,area,itemid)):"addnewcategory"===roleHolder.dataset.role?(e.preventDefault(),void((component,area,itemid)=>{const pendingPromise=new _pending.default("core_customfield/form:createNewCategory");(0,_ajax.call)([{methodname:"core_customfield_create_category",args:{component:component,area:area,itemid:itemid}},{methodname:"core_customfield_reload_template",args:{component:component,area:area,itemid:itemid}}])[1].then((response=>_templates.default.render("core_customfield/list",response))).then(((html,js)=>_templates.default.replaceNode((0,_jquery.default)('[data-region="list-page"]'),html,js))).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)})(component,area,itemid)):"addfield"===roleHolder.dataset.role?(e.preventDefault(),void((element,component,area,itemid)=>{const pendingPromise=new _pending.default("core_customfield/form:createNewField"),returnFocus=element.closest(".action-menu").querySelector(".dropdown-toggle"),form=new _modalform.default({formClass:"core_customfield\\field_config_form",args:{categoryid:element.getAttribute("data-categoryid"),type:element.getAttribute("data-type")},modalConfig:{title:(0,_str.get_string)("addingnewcustomfield","core_customfield",element.getAttribute("data-typename"))},returnFocus:returnFocus});form.addEventListener(form.events.FORM_SUBMITTED,(()=>{const pendingCreatedPromise=new _pending.default("core_customfield/form:createdNewField");(0,_ajax.call)([{methodname:"core_customfield_reload_template",args:{component:component,area:area,itemid:itemid}}])[0].then((response=>_templates.default.render("core_customfield/list",response))).then(((html,js)=>_templates.default.replaceNode((0,_jquery.default)('[data-region="list-page"]'),html,js))).then((()=>pendingCreatedPromise.resolve())).catch((()=>window.location.reload()))})),form.show(),pendingPromise.resolve()})(roleHolder,component,area,itemid)):"editfield"===roleHolder.dataset.role?(e.preventDefault(),void((element,component,area,itemid)=>{const pendingPromise=new _pending.default("core_customfield/form:editField"),form=new _modalform.default({formClass:"core_customfield\\field_config_form",args:{id:element.getAttribute("data-id")},modalConfig:{title:(0,_str.get_string)("editingfield","core_customfield",element.getAttribute("data-name"))},returnFocus:element});form.addEventListener(form.events.FORM_SUBMITTED,(()=>{const pendingCreatedPromise=new _pending.default("core_customfield/form:createdNewField");(0,_ajax.call)([{methodname:"core_customfield_reload_template",args:{component:component,area:area,itemid:itemid}}])[0].then((response=>_templates.default.render("core_customfield/list",response))).then(((html,js)=>_templates.default.replaceNode((0,_jquery.default)('[data-region="list-page"]'),html,js))).then((()=>pendingCreatedPromise.resolve())).catch((()=>window.location.reload()))})),form.show(),pendingPromise.resolve()})(roleHolder,component,area,itemid)):void 0})),(rootNode=>{new _sortable_list.default("#customfield_catlist .categorieslist",{moveHandlerSelector:".movecategory [data-drag-type=move]"}).getElementName=nodeElement=>Promise.resolve(getCategoryNameFor(nodeElement)),(0,_jquery.default)("[data-category-id]").on(_sortable_list.default.EVENTS.DROP,((evt,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_customfield/form:categoryid:on:sortablelist-drop");(0,_ajax.call)([{methodname:"core_customfield_move_category",args:{id:info.element.data("category-id"),beforeid:info.targetNextElement.data("category-id")}}])[0].then(pendingPromise.resolve).catch(_notification.default.exception)}evt.stopPropagation()})),new _sortable_list.default("#customfield_catlist .fieldslist tbody",{moveHandlerSelector:".movefield [data-drag-type=move]"}).getDestinationName=(parentElement,afterElement)=>afterElement.length?afterElement.attr("data-field-name")?(0,_str.get_string)("afterfield","customfield",afterElement.attr("data-field-name")):Promise.resolve(""):(0,_str.get_string)("totopofcategory","customfield",getCategoryNameFor(parentElement)),(0,_jquery.default)("[data-field-name]").on(_sortable_list.default.EVENTS.DROP,((evt,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_customfield/form:fieldname:on:sortablelist-drop");(0,_ajax.call)([{methodname:"core_customfield_move_field",args:{id:info.element.data("field-id"),beforeid:info.targetNextElement.data("field-id"),categoryid:Number(info.targetList.closest("[data-category-id]").attr("data-category-id"))}}])[0].then(pendingPromise.resolve).catch(_notification.default.exception)}evt.stopPropagation()})),(0,_jquery.default)("[data-field-name]").on(_sortable_list.default.EVENTS.DRAG,(evt=>{var pendingPromise=new _pending.default("core_customfield/form:fieldname:on:sortablelist-drag");evt.stopPropagation(),_templates.default.render("core_customfield/nofields",{}).then((html=>{rootNode.querySelectorAll(".categorieslist > *").forEach((category=>{const fields=category.querySelectorAll(".field:not(.sortable-list-is-dragged)"),noFields=category.querySelector(".nofields");fields.length||noFields?fields.length&&noFields&&noFields.remove():category.querySelector("tbody").innerHTML=html}))})).then(pendingPromise.resolve).catch(_notification.default.exception)})),(0,_jquery.default)("[data-category-id], [data-field-name]").on(_sortable_list.default.EVENTS.DRAGSTART,((evt,info)=>{setTimeout((()=>{(0,_jquery.default)(".sortable-list-is-dragged").width(info.element.width())}),501)}))})(rootNode)}})); define("core_editor/events",["exports","core/event_dispatcher","jquery","core/yui"],(function(_exports,_event_dispatcher,_jquery,_yui){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript events for the `core_editor` subsystem. * * @module core_editor/events * @copyright 2021 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyEditorContentRestored=_exports.eventTypes=void 0,_jquery=_interopRequireDefault(_jquery),_yui=_interopRequireDefault(_yui);const eventTypes={editorContentRestored:"core_editor/contentRestored"};_exports.eventTypes=eventTypes;_exports.notifyEditorContentRestored=editor=>(editor||window.console.warn("The HTMLElement representing the editor that was modified should be provided to notifyEditorContentRestored."),(0,_event_dispatcher.dispatchEvent)(eventTypes.editorContentRestored,{},editor||document));let legacyEventsRegistered=!1;legacyEventsRegistered||(_yui.default.use("event","moodle-core-event",(()=>{document.addEventListener(eventTypes.editorContentRestored,(()=>{(0,_jquery.default)(document).trigger(M.core.event.EDITOR_CONTENT_RESTORED),_yui.default.fire(M.core.event.EDITOR_CONTENT_RESTORED)}))})),legacyEventsRegistered=!0)})); define("core_filters/events",["exports","core/event_dispatcher","core/normalise","jquery"],(function(_exports,_event_dispatcher,_normalise,_jquery){var obj; /** * Javascript events for the `core_filters` subsystem. * * @module core_filters/events * @copyright 2021 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 * * @example <caption>Example of listening to a filter event.</caption> * import {eventTypes as filterEventTypes} from 'core_filters/events'; * * document.addEventListener(filterEventTypes.filterContentUpdated, e => { * window.console.log(e.detail.nodes); // A list of the HTMLElements whose content was updated * }); */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyFilterContentUpdated=_exports.eventTypes=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};const eventTypes={filterContentUpdated:"core_filters/contentUpdated"};_exports.eventTypes=eventTypes;_exports.notifyFilterContentUpdated=nodes=>(nodes=(0,_normalise.getList)(nodes),(0,_event_dispatcher.dispatchEvent)(eventTypes.filterContentUpdated,{nodes:nodes}));let legacyEventsRegistered=!1;legacyEventsRegistered||(Y.use("event","moodle-core-event",(()=>{document.addEventListener(eventTypes.filterContentUpdated,(e=>{(0,_jquery.default)(document).trigger(M.core.event.FILTER_CONTENT_UPDATED,[(0,_jquery.default)(e.detail.nodes)]),Y.fire(M.core.event.FILTER_CONTENT_UPDATED,{nodes:new Y.NodeList(e.detail.nodes)})}))})),legacyEventsRegistered=!0)})); /** * Functionality for the form element defaultcustom * * @module core_form/defaultcustom * @copyright 2017 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.3 */ define("core_form/defaultcustom",["jquery"],(function($){$("body").on("change","input[data-defaultcustom=true]",(function(event){var element=$(event.target),defaultvalue=JSON.parse(element.attr("data-defaultvalue")),customvalue=JSON.parse(element.attr("data-customvalue")),type=element.attr("data-type"),form=element.closest("form"),elementName=element.attr("name").replace(/\[customize\]$/,"[value]"),newvalue=element.prop("checked")?customvalue:defaultvalue;"text"===type?form.find('[name="'+elementName+'"]').val(newvalue):"date_selector"===type?(form.find('[name="'+elementName+'[day]"]').val(newvalue.day),form.find('[name="'+elementName+'[month]"]').val(newvalue.month),form.find('[name="'+elementName+'[year]"]').val(newvalue.year)):"date_time_selector"===type&&(form.find('[name="'+elementName+'[day]"]').val(newvalue.day),form.find('[name="'+elementName+'[month]"]').val(newvalue.month),form.find('[name="'+elementName+'[year]"]').val(newvalue.year),form.find('[name="'+elementName+'[hour]"]').val(newvalue.hour),form.find('[name="'+elementName+'[minute]"]').val(newvalue.minute))}))})); define("core_form/encryptedpassword",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.EncryptedPassword=void 0; /** * Encrypted password functionality. * * @module core_form/encryptedpassword * @copyright 2019 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const EncryptedPassword=function(elementId){const wrapper=document.querySelector('div[data-encryptedpasswordid="'+elementId+'"]');this.spanOrLink=wrapper.querySelector("span, a"),this.input=wrapper.querySelector("input"),this.editButtonOrLink=wrapper.querySelector("button[data-editbutton], a"),this.cancelButton=wrapper.querySelector("button[data-cancelbutton]");var editHandler=e=>{e.stopImmediatePropagation(),e.preventDefault(),this.startEditing(!0)};this.editButtonOrLink.addEventListener("click",editHandler),"A"===this.editButtonOrLink.nodeName&&wrapper.parentElement.previousElementSibling.querySelector("label").addEventListener("click",editHandler),this.cancelButton.addEventListener("click",(e=>{e.stopImmediatePropagation(),e.preventDefault(),this.cancelEditing()})),"y"===wrapper.dataset.novalue&&(this.startEditing(!1),this.cancelButton.style.display="none")};_exports.EncryptedPassword=EncryptedPassword,EncryptedPassword.prototype.startEditing=function(moveFocus){this.input.style.display="inline",this.input.disabled=!1,this.spanOrLink.style.display="none",this.editButtonOrLink.style.display="none",this.cancelButton.style.display="inline";const id=this.editButtonOrLink.id;this.editButtonOrLink.removeAttribute("id"),this.input.id=id,moveFocus&&this.input.focus()},EncryptedPassword.prototype.cancelEditing=function(){this.input.style.display="none",this.input.value="",this.input.disabled=!0,this.spanOrLink.style.display="inline",this.editButtonOrLink.style.display="inline",this.cancelButton.style.display="none";const id=this.input.id;this.input.removeAttribute("id"),this.editButtonOrLink.id=id}})); /** * This module allows to enhance the form elements MoodleQuickForm_filetypes * * @module core_form/filetypes * @copyright 2017 David Mudrak <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.3 */ define("core_form/filetypes",["jquery","core/log","core/str","core/modal_factory","core/modal_events","core/ajax","core/templates","core/tree"],(function($,Log,Str,ModalFactory,ModalEvents,Ajax,Templates,Tree){var FileTypes=function(elementId,elementLabel,onlyTypes,allowAll){this.elementId=elementId,this.elementLabel=elementLabel,this.onlyTypes=onlyTypes,this.allowAll=allowAll,this.inputField=$("#"+elementId),this.wrapperBrowserTrigger=$('[data-filetypesbrowser="'+elementId+'"]'),this.wrapperDescriptions=$('[data-filetypesdescriptions="'+elementId+'"]'),this.wrapperBrowserTrigger.length&&(this.inputField.length&&this.wrapperDescriptions.length?this.prepareBrowserTrigger().then(function(){return this.prepareBrowserModal()}.bind(this)).then(function(){return this.prepareBrowserTree()}.bind(this)):Log.error("core_form/filetypes: Unexpected DOM structure, unable to enhance filetypes field "+elementId))};return FileTypes.prototype.prepareBrowserTrigger=function(){return Templates.render("core_form/filetypes-trigger",{}).then(function(html){this.wrapperBrowserTrigger.html(html),this.browserTrigger=this.wrapperBrowserTrigger.find('[data-filetypeswidget="browsertrigger"]')}.bind(this))},FileTypes.prototype.prepareBrowserModal=function(){return ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:this.elementLabel}).then(function(modal){this.browserModal=modal}.bind(this)).then(function(){this.browserModal.getRoot().on(ModalEvents.hidden,function(){this.browserTrigger.focus()}.bind(this)),this.browserModal.getRoot().on(ModalEvents.save,function(){this.saveBrowserModal()}.bind(this))}.bind(this))},FileTypes.prototype.prepareBrowserTree=function(){return this.browserTrigger.on("click",function(e){if(e.preventDefault(),!this.inputField.is("[disabled]")){var bodyContent=this.loadBrowserModalBody();bodyContent.then(function(){this.browserTree=new Tree(this.browserModal.getBody()),this.browserTree.handleKeyDown=function(item,e){e.keyCode==this.browserTree.keys.enter||e.keyCode==this.browserTree.keys.space?(e.preventDefault(),e.stopPropagation(),this.toggleCheckbox(item.attr("data-filetypesbrowserkey"))):Tree.prototype.handleKeyDown.call(this.browserTree,item,e)}.bind(this),this.allowAll&&(this.hideOrShowItemsDependingOnAllowAll(this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="*"]').first()),this.browserModal.getRoot().on("change",'input[type="checkbox"][data-filetypesbrowserkey="*"]',function(e){this.hideOrShowItemsDependingOnAllowAll($(e.currentTarget))}.bind(this))),this.browserModal.getRoot().on("change",'input[type="checkbox"][data-filetypesbrowserkey]',function(e){var checkbox=$(e.currentTarget),key=checkbox.attr("data-filetypesbrowserkey");this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="'+key+'"]').prop("checked",checkbox.prop("checked"))}.bind(this))}.bind(this)).then(function(){this.browserModal.show()}.bind(this)),this.browserModal.setBody(bodyContent)}}.bind(this)),$.when()},FileTypes.prototype.loadBrowserModalBody=function(){var args={onlytypes:this.onlyTypes.join(),allowall:this.allowAll,current:this.inputField.val()};return Ajax.call([{methodname:"core_form_get_filetypes_browser_data",args:args}])[0].then(function(browserData){return Templates.render("core_form/filetypes-browser",{elementid:this.elementId,groups:browserData.groups})}.bind(this))},FileTypes.prototype.toggleCheckbox=function(key){var checkbox=this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="'+key+'"]').first();checkbox.prop("checked",!checkbox.prop("checked"))},FileTypes.prototype.saveBrowserModal=function(){if(this.allowAll){var allcheckbox=this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="*"]');if(allcheckbox.length&&allcheckbox.prop("checked"))return this.inputField.val("*"),void this.updateDescriptions(["*"])}var newvalue=[];this.browserModal.getRoot().find('input[type="checkbox"]').each((function(){var checkbox=$(this),key=checkbox.attr("data-filetypesbrowserkey");checkbox.prop("checked")&&newvalue.push(key)})),newvalue=newvalue.filter((function(x,i,a){return a.indexOf(x)==i})),this.inputField.val(newvalue.join(" ")),this.updateDescriptions(newvalue)},FileTypes.prototype.updateDescriptions=function(keys){var descriptions=[];keys.forEach(function(key){descriptions.push({description:this.browserModal.getRoot().find('[data-filetypesname="'+key+'"]').first().text().trim(),extensions:this.browserModal.getRoot().find('[data-filetypesextensions="'+key+'"]').first().text().trim()})}.bind(this));var templatedata={hasdescriptions:descriptions.length>0,descriptions:descriptions};return Templates.render("core_form/filetypes-descriptions",templatedata).then(function(html){this.wrapperDescriptions.html(html)}.bind(this))},FileTypes.prototype.hideOrShowItemsDependingOnAllowAll=function(allcheckbox){var others=this.browserModal.getRoot().find('[role="treeitem"][data-filetypesbrowserkey!="*"]');allcheckbox.prop("checked")?others.hide():others.show()},{init:function(elementId,elementLabel,onlyTypes,allowAll){new FileTypes(elementId,elementLabel,onlyTypes,allowAll)}}})); define("core_form/modalform",["exports","core/ajax","core_form/changechecker","core_form/events","core/fragment","core/modal_events","core/modal_factory","core/notification","core/pending","./util"],(function(_exports,_ajax,FormChangeChecker,FormEvents,_fragment,_modal_events,_modal_factory,_notification,_pending,_util){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_ajax=_interopRequireDefault(_ajax),FormChangeChecker=_interopRequireWildcard(FormChangeChecker),FormEvents=_interopRequireWildcard(FormEvents),_fragment=_interopRequireDefault(_fragment),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);return _exports.default=class{constructor(config){var obj,key,value;value={FORM_SUBMITTED:"core_form_modalform_formsubmitted",FORM_CANCELLED:"core_form_modalform_formcancelled",CLIENT_VALIDATION_ERROR:"core_form_modalform_clientvalidationerror",SERVER_VALIDATION_ERROR:"core_form_modalform_validationerror",ERROR:"core_form_modalform_error",NOSUBMIT_BUTTON_PRESSED:"core_form_modalform_nosubmitbutton",SUBMIT_BUTTON_PRESSED:"core_form_modalform_submitbutton",CANCEL_BUTTON_PRESSED:"core_form_modalform_cancelbutton",LOADED:"core_form_modalform_loaded"},(key="events")in(obj=this)?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,this.modal=null,this.config=config,this.config.modalConfig={removeOnClose:!0,type:_modal_factory.default.types.SAVE_CANCEL,large:!0,...this.config.modalConfig||{}},this.config.args=this.config.args||{},this.futureListeners=[]}show(){const pendingPromise=new _pending.default("core_form/modalform:init");return _modal_factory.default.create(this.config.modalConfig).then((modal=>{this.modal=modal;const formParams=(0,_util.serialize)(this.config.args||{}),bodyContent=this.getBody(formParams);return this.modal.setBodyContent(bodyContent),bodyContent.catch(_notification.default.exception),this.modal.getRoot().on(_modal_events.default.hidden,(()=>{this.notifyResetFormChanges(),this.modal.destroy(),this.config.returnFocus&&this.config.returnFocus.focus()})),this.modal.getModal().addClass("modal-form-dialogue"),this.modal.getRoot().on("click","form input[type=submit][data-no-submit]",(e=>{e.preventDefault();this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED,e.target).defaultPrevented||this.processNoSubmitButton(e.target)})),this.modal.getRoot().on("submit","form",(e=>{e.preventDefault();this.trigger(this.events.SUBMIT_BUTTON_PRESSED).defaultPrevented||this.submitFormAjax()})),void 0!==this.config.saveButtonText&&void 0!==this.modal.setSaveButtonText&&this.modal.setSaveButtonText(this.config.saveButtonText),void 0!==this.config.saveButtonClasses&&this.setSaveButtonClasses(this.config.saveButtonClasses),this.modal.getRoot().on(_modal_events.default.save,(e=>{e.preventDefault(),this.modal.getRoot().find("form").submit()})),this.modal.getRoot().on(_modal_events.default.cancel,(e=>{this.trigger(this.events.CANCEL_BUTTON_PRESSED).defaultPrevented&&e.preventDefault()})),this.futureListeners.forEach((args=>this.modal.getRoot()[0].addEventListener(...args))),this.futureListeners=[],this.trigger(this.events.LOADED,null,!1),this.modal.show()})).then(pendingPromise.resolve)}trigger(eventName){const e=new CustomEvent(eventName,{detail:arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,cancelable:!(arguments.length>2&&void 0!==arguments[2])||arguments[2]});return this.modal.getRoot()[0].dispatchEvent(e),e}addEventListener(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];this.modal?this.modal.getRoot()[0].addEventListener(...args):this.futureListeners.push(args)}getBody(formDataString){const params={formdata:formDataString,form:this.config.formClass},pendingPromise=new _pending.default("core_form/modalform:form_body");return _ajax.default.call([{methodname:"core_form_dynamic_form",args:params}])[0].then((response=>(pendingPromise.resolve(),{html:response.html,js:_fragment.default.processCollectedJavascript(response.javascript)})))}onSubmitError(exception){this.trigger(this.events.ERROR,exception).defaultPrevented||_notification.default.exception(exception)}notifyResetFormChanges(){const form=this.getFormNode();form&&(FormEvents.notifyFormSubmittedByJavascript(form,!0),FormChangeChecker.resetFormDirtyState(form))}getFormNode(){return this.modal.getRoot().find("form")[0]}processNoSubmitButton(button){const form=this.getFormNode();if(!form)return;FormEvents.notifyFormSubmittedByJavascript(form,!0);let formData=this.modal.getRoot().find("form").serialize();formData=formData+"&"+encodeURIComponent(button.getAttribute("name"))+"="+encodeURIComponent(button.getAttribute("value"));const bodyContent=this.getBody(formData);this.modal.setBodyContent(bodyContent),bodyContent.catch(_notification.default.exception)}validateElements(){FormEvents.notifyFormSubmittedByJavascript(this.getFormNode());const invalid=this.modal.getRoot().find('[aria-invalid="true"], .error');return!invalid.length||(invalid.first().focus(),!1)}disableButtons(){this.modal.getFooter().find("[data-action]").attr("disabled",!0)}enableButtons(){this.modal.getFooter().find("[data-action]").removeAttr("disabled")}async submitFormAjax(){if(!this.validateElements())return void this.trigger(this.events.CLIENT_VALIDATION_ERROR,null,!1);this.disableButtons();const form=this.modal.getRoot().find("form"),formData=form.serialize();_ajax.default.call([{methodname:"core_form_dynamic_form",args:{formdata:formData,form:this.config.formClass}}])[0].then((response=>{if(response.submitted){const data=JSON.parse(response.data);FormChangeChecker.markFormSubmitted(form[0]);this.trigger(this.events.FORM_SUBMITTED,data).defaultPrevented||this.modal.hide()}else{const promise=new Promise((resolve=>resolve({html:response.html,js:_fragment.default.processCollectedJavascript(response.javascript)})));this.modal.setBodyContent(promise),this.enableButtons(),this.trigger(this.events.SERVER_VALIDATION_ERROR)}return null})).catch((exception=>this.onSubmitError(exception)))}setSaveButtonClasses(value){const button=this.modal.getFooter().find("[data-action='save']");if(!button)throw new Error("Unable to find the 'save' button");button.removeClass().addClass(value)}},_exports.default})); /** * Password Unmask functionality. * * @module core_form/passwordunmask * @copyright 2016 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("core_form/passwordunmask",["jquery","core/templates"],(function($,Template){var PasswordUnmask=function(elementid){this.wrapperSelector='[data-passwordunmask="wrapper"][data-passwordunmaskid="'+elementid+'"]',this.wrapper=$(this.wrapperSelector),this.editorSpace=this.wrapper.find('[data-passwordunmask="editor"]'),this.editLink=this.wrapper.find('a[data-passwordunmask="edit"]'),this.editInstructions=this.wrapper.find('[data-passwordunmask="instructions"]'),this.displayValue=this.wrapper.find('[data-passwordunmask="displayvalue"]'),this.inputFieldLabel=$('label[for="'+elementid+'"]'),this.inputField=this.editorSpace.find(document.getElementById(elementid)),this.inputField.addClass("d-none"),this.inputField.removeClass("hiddenifjs"),this.editInstructions.attr("id")||this.editInstructions.attr("id",elementid+"_instructions"),this.editInstructions.hide(),this.setDisplayValue(),this.addListeners()};return PasswordUnmask.prototype.addListeners=function(){return this.wrapper.on("click keypress",'[data-passwordunmask="edit"]',$.proxy((function(e){"keypress"===e.type&&13!==e.keyCode||(e.stopImmediatePropagation(),e.preventDefault(),this.isEditing()?"click"===e.type||$(e.relatedTarget).is(":input")?this.turnEditingOff(!1):this.turnEditingOff(!0):this.turnEditingOn())}),this)),this.wrapper.on("click keypress",'[data-passwordunmask="unmask"]',$.proxy((function(e){"keypress"===e.type&&13!==e.keyCode||(e.stopImmediatePropagation(),e.preventDefault(),this.wrapper.data("unmasked",!this.wrapper.data("unmasked")),this.setDisplayValue())}),this)),this.wrapper.on("keydown","input",$.proxy((function(e){"keydown"===e.type&&13!==e.keyCode||(e.stopImmediatePropagation(),e.preventDefault(),this.turnEditingOff(!0))}),this)),this.inputFieldLabel.on("click",$.proxy((function(e){e.preventDefault(),this.turnEditingOn()}),this)),this},PasswordUnmask.prototype.checkFocusOut=function(e){this.isEditing()&&window.setTimeout($.proxy((function(){var relatedTarget=e.relatedTarget||document.activeElement;this.wrapper.has($(relatedTarget)).length||this.turnEditingOff(!$(relatedTarget).is(":input,a"))}),this),100)},PasswordUnmask.prototype.passwordVisible=function(){return!!this.wrapper.data("unmasked")},PasswordUnmask.prototype.isEditing=function(){return this.inputField.hasClass("d-inline-block")},PasswordUnmask.prototype.turnEditingOn=function(){var value=this.getDisplayValue();return this.passwordVisible()?this.inputField.attr("type","text"):this.inputField.attr("type","password"),this.inputField.val(value),this.inputField.attr("size",this.inputField.attr("data-size")),this.inputField.addClass("d-inline-block"),this.editInstructions.length&&(this.inputField.attr("aria-describedby",this.editInstructions.attr("id")),this.editInstructions.show()),this.wrapper.attr("data-passwordunmask-visible",1),this.editLink.hide(),this.inputField.focus().select(),$("body").on("focusout",this.wrapperSelector,$.proxy(this.checkFocusOut,this)),this},PasswordUnmask.prototype.turnEditingOff=function(focusOnEditLink){$("body").off("focusout",this.wrapperSelector,this.checkFocusOut);var value=this.getDisplayValue();return this.inputField.attr("aria-describedby",null),this.inputField.val(value),this.inputField.removeClass("d-inline-block"),this.editInstructions.hide(),this.wrapper.removeAttr("data-passwordunmask-visible"),this.inputField.removeAttr("size"),this.editLink.show(),this.setDisplayValue(),focusOnEditLink&&this.editLink.focus(),this},PasswordUnmask.prototype.getDisplayValue=function(){return this.inputField.val()},PasswordUnmask.prototype.setDisplayValue=function(){var value=this.getDisplayValue();return this.isEditing()&&(this.wrapper.data("unmasked")?this.inputField.attr("type","text"):this.inputField.attr("type","password"),this.inputField.val(value)),value&&this.wrapper.data("unmasked")?this.displayValue.text(value):(value||(value=""),Template.render("core_form/element-passwordunmask-fill",{element:{frozen:this.inputField.is("[readonly]"),value:value,valuechars:value.split("")}}).done($.proxy((function(html,js){this.displayValue.html(html),Template.runTemplateJS(js)}),this))),this},PasswordUnmask})); /** * A class to help show and hide advanced form content. * * @module core_form/showadvanced * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_form/showadvanced",["jquery","core/log","core/str","core/notification"],(function($,Log,Strings,Notification){var SELECTORS_FIELDSETCONTAINSADVANCED="fieldset.containsadvancedelements",SELECTORS_DIVFITEMADVANCED="div.fitem.advanced",SELECTORS_DIVADVANCEDSECTION="div#form-advanced-div",SELECTORS_MORELESSLINK="fieldset.containsadvancedelements .moreless-toggler",CSS_SHOW="show",CSS_MORELESSACTIONS="moreless-actions",CSS_MORELESSTOGGLER="moreless-toggler",CSS_SHOWLESS="moreless-less",WRAPPERS_FITEM='<div class="fitem"></div>',WRAPPERS_FELEMENT='<div class="felement"></div>',WRAPPERS_ADVANCEDDIV='<div id="form-advanced-div"></div>',uniqIdSeed=0,ShowAdvanced=function(id){this.id=id;var form=$(document.getElementById(id));this.enhanceForm(form)};return ShowAdvanced.prototype.id="",ShowAdvanced.prototype.enhanceForm=function(form){return form.find(SELECTORS_FIELDSETCONTAINSADVANCED).each(function(index,item){this.enhanceFieldset($(item))}.bind(this)),form.on("click",SELECTORS_MORELESSLINK,this.switchState),form.on("keydown",SELECTORS_MORELESSLINK,function(e){return 13!=e.which&&32!=e.which||this.switchState(e)}.bind(this)),this},ShowAdvanced.prototype.generateId=function(node){var id=node.prop("id");return void 0===id&&(id="showadvancedid-"+uniqIdSeed++,node.prop("id",id)),id},ShowAdvanced.prototype.enhanceFieldset=function(fieldset){var statuselement=$("input[name=mform_showmore_"+fieldset.prop("id")+"]");return statuselement.length?(Strings.get_strings([{key:"showmore",component:"core_form"},{key:"showless",component:"core_form"}]).then(function(results){var showmore=results[0],showless=results[1],morelesslink=$('<a href="#"></a>');morelesslink.addClass(CSS_MORELESSTOGGLER),"0"===statuselement.val()?(morelesslink.html(showmore),morelesslink.attr("aria-expanded","false")):(morelesslink.html(showless),morelesslink.attr("aria-expanded","true"),morelesslink.addClass(CSS_SHOWLESS),fieldset.find(SELECTORS_DIVFITEMADVANCED).addClass(CSS_SHOW));var idlist=[];fieldset.find(SELECTORS_DIVFITEMADVANCED).each(function(index,node){idlist[idlist.length]=this.generateId($(node))}.bind(this)),morelesslink.attr("role","button"),morelesslink.attr("aria-controls","form-advanced-div");var formadvancedsection=$(WRAPPERS_ADVANCEDDIV);fieldset.find(SELECTORS_DIVFITEMADVANCED).wrapAll(formadvancedsection);var fitem=$(WRAPPERS_FITEM);fitem.addClass(CSS_MORELESSACTIONS);var felement=$(WRAPPERS_FELEMENT);return felement.append(morelesslink),fitem.append(felement),fieldset.find(SELECTORS_DIVADVANCEDSECTION).before(fitem),!0}.bind(this)).fail(Notification.exception),this):(Log.debug("M.form.showadvanced::processFieldset was called on an fieldset without a status field: '"+fieldset.prop("id")+"'"),this)},ShowAdvanced.prototype.switchState=function(e){return e.preventDefault(),Strings.get_strings([{key:"showmore",component:"core_form"},{key:"showless",component:"core_form"}]).then((function(results){var showmore=results[0],showless=results[1],fieldset=$(e.target).closest(SELECTORS_FIELDSETCONTAINSADVANCED);fieldset.find(SELECTORS_DIVFITEMADVANCED).toggleClass(CSS_SHOW);var statuselement=$("input[name=mform_showmore_"+fieldset.prop("id")+"]");return"0"===statuselement.val()?(statuselement.val(1),$(e.target).addClass(CSS_SHOWLESS),$(e.target).html(showless),$(e.target).attr("aria-expanded","true")):(statuselement.val(0),$(e.target).removeClass(CSS_SHOWLESS),$(e.target).html(showmore),$(e.target).attr("aria-expanded","false")),!0})).fail(Notification.exception),this},{init:function(formid){return new ShowAdvanced(formid)}}})); define("core_form/submit",["exports","core_form/events"],(function(_exports,_events){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Submit button JavaScript. All submit buttons will be automatically disabled once the form is * submitted, unless that submission results in an error/cancelling the submit. * * @module core_form/submit * @copyright 2019 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.8 */ let cookieListener=0;const cookieListeningButtons=[];let currentUploadCount=0;const uploadListeningButtons=[];let uploadListenersRegistered=!1;const getCookieName=()=>"moodledownload_"+M.cfg.sesskey,clearDownloadCookie=()=>{document.cookie=encodeURIComponent(getCookieName())+"=deleted; expires="+new Date(0).toUTCString()},checkUploadCount=()=>{currentUploadCount?uploadListeningButtons.forEach((button=>{button.disabled=!0})):uploadListeningButtons.forEach((button=>{button.disabled=!1}))};_exports.init=elementId=>{const button=document.getElementById(elementId);null!==button&&(button.disabled||uploadListeningButtons.push(button),uploadListenersRegistered||(document.addEventListener(_events.eventTypes.uploadStarted,(()=>{currentUploadCount++,checkUploadCount()})),document.addEventListener(_events.eventTypes.uploadCompleted,(()=>{currentUploadCount--,checkUploadCount()})),uploadListenersRegistered=!0),"off"!==button.form.dataset.doubleSubmitProtection&&button.form.addEventListener("submit",(function(event){const disableAction=function(){event.defaultPrevented||button.disabled||(button.disabled=!0,clearDownloadCookie(),(button=>{cookieListeningButtons.push(button),cookieListener||(cookieListener=setInterval((()=>{2==document.cookie.split(getCookieName()+"=").length&&(clearDownloadCookie(),clearInterval(cookieListener),cookieListener=0,cookieListeningButtons.forEach((button=>{button.disabled=!1})))}),500))})(button))};window.addEventListener("beforeunload",disableAction),setTimeout((function(){window.removeEventListener("beforeunload",disableAction)}),0)}),!1))}})); define("core_form/util",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.serialize=void 0;const serialize=function(data){let prefix=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return[...Object.entries(data).map((_ref=>{let[index,value]=_ref;const key=prefix?"".concat(prefix,"[").concat(index,"]"):index;return null!==value&&"object"==typeof value?serialize(value,key):"".concat(key,"=").concat(encodeURIComponent(value))}))].join("&")};_exports.serialize=serialize})); define("core_form/changechecker",["exports","core_editor/events","core/str"],(function(_exports,_events,_str){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.watchFormById=_exports.watchForm=_exports.unWatchForm=_exports.startWatching=_exports.resetFormDirtyStateById=_exports.resetFormDirtyState=_exports.resetAllFormDirtyStates=_exports.markFormSubmitted=_exports.markFormChangedFromNode=_exports.markFormAsDirtyById=_exports.markFormAsDirty=_exports.markAllFormsSubmitted=_exports.markAllFormsAsDirty=_exports.isAnyWatchedFormDirty=_exports.disableAllChecks=void 0; /** * This module provides change detection to forms, allowing a browser to warn the user before navigating away if changes * have been made. * * Two flags are stored for each form: * * a 'dirty' flag; and * * a 'submitted' flag. * * When the page is unloaded each watched form is checked. If the 'dirty' flag is set for any form, and the 'submitted' * flag is not set for any form, then a warning is shown. * * The 'dirty' flag is set when any form element is modified within a watched form. * The flag can also be set programatically. This may be required for custom form elements. * * It is not possible to customise the warning message in any modern browser. * * Please note that some browsers have controls on when these alerts may or may not be shown. * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload} for browser-specific * notes and references. * * @module core_form/changechecker * @copyright 2021 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @example <caption>Usage where the FormElement is already held</caption> * * import {watchForm} from 'core_form/changechecker'; * * // Fetch the form element somehow. * watchForm(formElement); * * @example <caption>Usage from the child of a form - i.e. an input, button, div, etc.</caption> * * import {watchForm} from 'core_form/changechecker'; * * // Watch the form by using a child of it. * watchForm(document.querySelector('input[data-foo="bar"]');); * * @example <caption>Usage from within a template</caption> * <form id="mod_example-entry-{{uniqid}}" ...> * <!-- * * --> * </form> * {{#js}} * require(['core_form/changechecker'], function(changeChecker) { * watchFormById('mod_example-entry-{{uniqid}}'); * }); * {{/js}} */ let warningString,watchedForms=[],formChangeCheckerDisabled=!1;const getFormFromChild=formChild=>formChild.closest("form"),watchForm=formNode=>{(formNode=getFormFromChild(formNode))&&(isWatchingForm(formNode)||watchedForms.push(formNode))};_exports.watchForm=watchForm;_exports.unWatchForm=formNode=>{watchedForms=watchedForms.filter((watchedForm=>!!watchedForm.contains(formNode)))};const resetAllFormDirtyStates=()=>{watchedForms.forEach((watchedForm=>{watchedForm.dataset.formSubmitted="false",watchedForm.dataset.formDirty="false"}))};_exports.resetAllFormDirtyStates=resetAllFormDirtyStates;const resetFormDirtyState=formNode=>{(formNode=getFormFromChild(formNode))&&(formNode.dataset.formSubmitted="false",formNode.dataset.formDirty="false")};_exports.resetFormDirtyState=resetFormDirtyState;const markAllFormsAsDirty=()=>{watchedForms.forEach((watchedForm=>{watchedForm.dataset.formDirty="true"}))};_exports.markAllFormsAsDirty=markAllFormsAsDirty;const markFormAsDirty=formNode=>{(formNode=getFormFromChild(formNode))&&(formNode.dataset.formDirty="true")};_exports.markFormAsDirty=markFormAsDirty;const disableAllChecks=()=>{formChangeCheckerDisabled=!0};_exports.disableAllChecks=disableAllChecks;const isAnyWatchedFormDirty=()=>{if(formChangeCheckerDisabled)return!1;if(watchedForms.some((watchedForm=>"true"===watchedForm.dataset.formSubmitted)))return!1;return!!watchedForms.some((watchedForm=>{if(!watchedForm.isConnected)return!1;if("true"===watchedForm.dataset.formDirty)return!0;if(document.activeElement&&document.activeElement.dataset.propertyIsEnumerable("initialValue")){const isActiveElementWatched=isWatchingForm(document.activeElement),hasValueChanged=document.activeElement.dataset.initialValue!==document.activeElement.value;if(isActiveElementWatched&&hasValueChanged)return!0}return!1}))||!(void 0===window.tinyMCE||!window.tinyMCE.editors||!window.tinyMCE.editors.some((editor=>editor.isDirty())))};_exports.isAnyWatchedFormDirty=isAnyWatchedFormDirty;const isWatchingForm=target=>watchedForms.some((watchedForm=>watchedForm.contains(target))),markFormChangedFromNode=changedNode=>{if(changedNode.dataset.formChangeCheckerOverride)return void disableAllChecks();if(!isWatchingForm(changedNode))return;if(changedNode.closest(".ignoredirty"))return;const formNode=(target=>watchedForms.find((watchedForm=>watchedForm.contains(target))))(changedNode);formNode.dataset.formDirty="true"};_exports.markFormChangedFromNode=markFormChangedFromNode;const markFormSubmitted=formNode=>{(formNode=getFormFromChild(formNode))&&(formNode.dataset.formSubmitted="true")};_exports.markFormSubmitted=markFormSubmitted;const markAllFormsSubmitted=()=>{watchedForms.forEach((watchedForm=>markFormSubmitted(watchedForm)))};_exports.markAllFormsSubmitted=markAllFormsSubmitted;const beforeUnloadHandler=e=>isAnyWatchedFormDirty()&&!M.cfg.behatsiterunning?(e.preventDefault(),e.returnValue=warningString,e.returnValue):(window.removeEventListener("beforeunload",beforeUnloadHandler),null),startWatching=()=>{addLegacyFunctions(),document.addEventListener("change",(e=>{isWatchingForm(e.target)&&markFormChangedFromNode(e.target)})),document.addEventListener("click",(e=>{if(!e.target.closest("[data-formchangechecker-ignore-submit]"))return;const ownerForm=getFormFromChild(e.target);ownerForm&&(ownerForm.dataset.ignoreSubmission="true")})),document.addEventListener("focusin",(e=>{if(e.target.matches("input, textarea, select")){if(e.target.dataset.propertyIsEnumerable("initialValue"))return;e.target.dataset.initialValue=e.target.value}})),document.addEventListener("submit",(e=>{const formNode=getFormFromChild(e.target);formNode&&(formNode.dataset.ignoreSubmission?formNode.dataset.ignoreSubmission="false":markFormSubmitted(formNode))})),document.addEventListener(_events.eventTypes.editorContentRestored,(e=>{e.target!=document?resetFormDirtyState(e.target):resetAllFormDirtyStates()})),(0,_str.get_string)("changesmadereallygoaway","moodle").then((changesMadeString=>{warningString=changesMadeString})).catch(),window.addEventListener("beforeunload",beforeUnloadHandler)};_exports.startWatching=startWatching;const addLegacyFunctions=()=>{const getLoggedLegacyFallback=(oldFunctionName,newFunctionName,newFunction)=>function(){window.console.warn("The moodle-core-formchangechecker has been deprecated and replaced with core_form/changechecker. "+"The ".concat(oldFunctionName," function has been replaced with ").concat(newFunctionName,".")),newFunction(...arguments)};window.M.core_formchangechecker={init:getLoggedLegacyFallback("init","watchFormById",watchFormById),reset_form_dirty_state:getLoggedLegacyFallback("reset_form_dirty_state","resetFormDirtyState",resetAllFormDirtyStates),set_form_changed:getLoggedLegacyFallback("set_form_changed","markFormAsDirty",markAllFormsAsDirty),set_form_submitted:getLoggedLegacyFallback("set_form_submitted","markFormSubmitted",markAllFormsSubmitted)}},watchFormById=formId=>{watchForm(document.getElementById(formId))};_exports.watchFormById=watchFormById;_exports.resetFormDirtyStateById=formId=>{resetFormDirtyState(document.getElementById(formId))};_exports.markFormAsDirtyById=formId=>{markFormAsDirty(document.getElementById(formId))},startWatching()})); define("core_form/collapsesections",["exports","jquery","core/pending"],(function(_exports,_jquery,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Collapse or expand all form sections on clicking the expand all / collapse al link. * * @module core_form/collapsesections * @copyright 2021 Bas Brands * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending);const SELECTORS_FORMHEADER=".fheader",SELECTORS_FORMCONTAINER="fieldset > .fcontainer",CLASSES_SHOW="show",CLASSES_COLLAPSED="collapsed";_exports.init=collapsesections=>{const pendingPromise=new _pending.default("core_form/collapsesections"),collapsemenu=document.querySelector(collapsesections),formParent=collapsemenu.closest("form"),formContainers=(null==formParent?void 0:formParent.querySelectorAll(SELECTORS_FORMCONTAINER))||[];collapsemenu.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),collapsemenu.click())}));let expandedcount=0;const formcontainercount=(0,_jquery.default)(SELECTORS_FORMCONTAINER).length;formContainers.forEach((container=>{container.classList.contains(CLASSES_SHOW)&&expandedcount++})),formcontainercount===expandedcount&&(collapsemenu.classList.remove(CLASSES_COLLAPSED),collapsemenu.setAttribute("aria-expanded",!0)),collapsemenu.addEventListener("click",(()=>{let action="hide";collapsemenu.classList.contains(CLASSES_COLLAPSED)&&(action="show"),formContainers.forEach((container=>(0,_jquery.default)(container).collapse(action)))}));const collapseElementIds=[...(0,_jquery.default)(SELECTORS_FORMHEADER)].map(((element,index)=>(element.id=element.id||"collapseElement-".concat(index),element.id)));collapsemenu.setAttribute("aria-controls",collapseElementIds.join(" ")),(0,_jquery.default)(SELECTORS_FORMCONTAINER).on("hidden.bs.collapse",(()=>{[...formContainers].every((container=>!container.classList.contains(CLASSES_SHOW)))&&(collapsemenu.classList.add(CLASSES_COLLAPSED),collapsemenu.setAttribute("aria-expanded",!1))})),(0,_jquery.default)(SELECTORS_FORMCONTAINER).on("shown.bs.collapse",(()=>{[...formContainers].every((container=>container.classList.contains(CLASSES_SHOW)))&&(collapsemenu.classList.remove(CLASSES_COLLAPSED),collapsemenu.setAttribute("aria-expanded",!0))})),pendingPromise.resolve()}})); define("core_form/dynamicform",["exports","core_form/changechecker","core_form/events","core/ajax","core/fragment","core/notification","core/pending","core/templates","core/str","./util"],(function(_exports,FormChangeChecker,FormEvents,_ajax,_fragment,_notification,_pending,_templates,_str,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,FormChangeChecker=_interopRequireWildcard(FormChangeChecker),FormEvents=_interopRequireWildcard(FormEvents),_ajax=_interopRequireDefault(_ajax),_fragment=_interopRequireDefault(_fragment),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_templates=_interopRequireDefault(_templates);return _exports.default=class{constructor(container,formClass){var obj,key,value;value={FORM_SUBMITTED:"core_form_dynamicform_formsubmitted",FORM_CANCELLED:"core_form_dynamicform_formcancelled",CLIENT_VALIDATION_ERROR:"core_form_dynamicform_clientvalidationerror",SERVER_VALIDATION_ERROR:"core_form_dynamicform_validationerror",ERROR:"core_form_dynamicform_error",NOSUBMIT_BUTTON_PRESSED:"core_form_dynamicform_nosubmitbutton",SUBMIT_BUTTON_PRESSED:"core_form_dynamicform_submitbutton",CANCEL_BUTTON_PRESSED:"core_form_dynamicform_cancelbutton"},(key="events")in(obj=this)?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,this.formClass=formClass,this.container=container,(0,_str.get_strings)([{key:"collapseall",component:"moodle"},{key:"expandall",component:"moodle"}]).catch(_notification.default.exception),this.container.addEventListener("click",(e=>{if(e.target.matches("form input[type=submit][data-cancel]")){e.preventDefault();this.trigger(this.events.CANCEL_BUTTON_PRESSED,e.target).defaultPrevented||this.processCancelButton()}else if(e.target.matches('form input[type=submit][data-no-submit="1"]')){e.preventDefault();this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED,e.target).defaultPrevented||this.processNoSubmitButton(e.target)}})),this.container.addEventListener("submit",(e=>{if(e.target.matches("form")){e.preventDefault();this.trigger(this.events.SUBMIT_BUTTON_PRESSED).defaultPrevented||this.submitFormAjax()}}))}load(){let args=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;const formData=(0,_util.serialize)(args||{}),pendingPromise=new _pending.default("core_form/dynamicform:load");return this.getBody(formData).then((resp=>this.updateForm(resp))).then(pendingPromise.resolve)}trigger(eventName){const e=new CustomEvent(eventName,{detail:arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,cancelable:!(arguments.length>2&&void 0!==arguments[2])||arguments[2]});return this.container.dispatchEvent(e),e}addEventListener(){this.container.addEventListener(...arguments)}getBody(formDataString){return _ajax.default.call([{methodname:"core_form_dynamic_form",args:{formdata:formDataString,form:this.formClass}}])[0].then((response=>({html:response.html,js:_fragment.default.processCollectedJavascript(response.javascript)})))}onSubmitSuccess(response){this.trigger(this.events.FORM_SUBMITTED,response).defaultPrevented||(this.container.innerHTML="")}onSubmitError(exception){this.trigger(this.events.ERROR,exception).defaultPrevented||_notification.default.exception(exception)}processNoSubmitButton(button){const pendingPromise=new _pending.default("core_form/dynamicform:nosubmit"),form=this.getFormNode(),formData=new URLSearchParams([...new FormData(form).entries()]);formData.append(button.getAttribute("name"),button.getAttribute("value")),FormEvents.notifyFormSubmittedByJavascript(form,!0),this.disableButtons(),this.getBody(formData.toString()).then((resp=>this.updateForm(resp))).then(pendingPromise.resolve).catch((exception=>this.onSubmitError(exception)))}getFormNode(){return this.container.querySelector("form")}notifyResetFormChanges(){FormEvents.notifyFormSubmittedByJavascript(this.getFormNode(),!0),FormChangeChecker.resetFormDirtyState(this.getFormNode())}processCancelButton(){this.notifyResetFormChanges();this.trigger(this.events.FORM_CANCELLED).defaultPrevented||(this.container.innerHTML="")}updateForm(_ref){let{html:html,js:js}=_ref;return _templates.default.replaceNodeContents(this.container,html,js)}validateElements(){FormEvents.notifyFormSubmittedByJavascript(this.getFormNode());const invalid=[...this.container.querySelectorAll('[aria-invalid="true"], .error')];return!invalid.length||(invalid[0].focus(),!1)}disableButtons(){this.container.querySelectorAll('form input[type="submit"]').forEach((el=>el.setAttribute("disabled",!0)))}enableButtons(){this.container.querySelectorAll('form input[type="submit"]').forEach((el=>el.removeAttribute("disabled")))}async submitFormAjax(){if(!await this.validateElements())return void this.trigger(this.events.CLIENT_VALIDATION_ERROR,null,!1);this.disableButtons();const form=this.container.querySelector("form"),formData=new URLSearchParams([...new FormData(form).entries()]);_ajax.default.call([{methodname:"core_form_dynamic_form",args:{formdata:formData.toString(),form:this.formClass}}])[0].then((response=>{if(response.submitted){const data=JSON.parse(response.data);this.enableButtons(),this.notifyResetFormChanges(),this.onSubmitSuccess(data)}else this.updateForm({html:response.html,js:_fragment.default.processCollectedJavascript(response.javascript)}),this.enableButtons(),this.trigger(this.events.SERVER_VALIDATION_ERROR,null,!1);return null})).catch((exception=>this.onSubmitError(exception)))}},_exports.default})); define("core_form/events",["exports","core/str","core/event_dispatcher","jquery","core/yui"],(function(_exports,_str,_event_dispatcher,_jquery,_yui){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript events for the `core_form` subsystem. * * @module core_form/events * @copyright 2021 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.10 * * @example <caption>Example of listening to a form event.</caption> * import {eventTypes as formEventTypes} from 'core_form/events'; * * document.addEventListener(formEventTypes.formSubmittedByJavascript, e => { * window.console.log(e.target); // The form that was submitted. * window.console.log(e.detail.skipValidation); // Whether form validation was skipped. * }); */let changesMadeString;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.types=_exports.triggerUploadStarted=_exports.triggerUploadCompleted=_exports.notifyUploadStarted=_exports.notifyUploadCompleted=_exports.notifyUploadChanged=_exports.notifyFormSubmittedByJavascript=_exports.notifyFormError=_exports.notifyFieldValidationFailure=_exports.eventTypes=void 0,_jquery=_interopRequireDefault(_jquery),_yui=_interopRequireDefault(_yui);const changesMadeCheck=e=>{e&&(e.returnValue=changesMadeString)},eventTypes={formError:"core_form/error",formSubmittedByJavascript:"core_form/submittedByJavascript",formFieldValidationFailed:"core_form/fieldValidationFailed",uploadStarted:"core_form/uploadStarted",uploadCompleted:"core_form/uploadCompleted",uploadChanged:"core_form/uploadChanged"};_exports.eventTypes=eventTypes;_exports.notifyFormError=field=>(0,_event_dispatcher.dispatchEvent)(eventTypes.formError,{},field);_exports.notifyFormSubmittedByJavascript=function(form){let skipValidation=arguments.length>1&&void 0!==arguments[1]&&arguments[1],fallbackHandled=arguments.length>2&&void 0!==arguments[2]&&arguments[2];skipValidation&&(window.skipClientValidation=!0);const customEvent=(0,_event_dispatcher.dispatchEvent)(eventTypes.formSubmittedByJavascript,{skipValidation:skipValidation,fallbackHandled:fallbackHandled},form);return skipValidation&&(window.skipClientValidation=!1),customEvent};_exports.notifyFieldValidationFailure=(field,message)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.formFieldValidationFailed,{message:message},field,{cancelable:!0});const notifyUploadStarted=async elementId=>(changesMadeString=await(0,_str.get_string)("changesmadereallygoaway","moodle"),window.addEventListener("beforeunload",changesMadeCheck),(0,_event_dispatcher.dispatchEvent)(eventTypes.uploadStarted,{},document.getElementById(elementId),{bubbles:!0,cancellable:!1}));_exports.notifyUploadStarted=notifyUploadStarted;const notifyUploadCompleted=elementId=>(window.removeEventListener("beforeunload",changesMadeCheck),(0,_event_dispatcher.dispatchEvent)(eventTypes.uploadCompleted,{},document.getElementById(elementId),{bubbles:!0,cancellable:!1}));_exports.notifyUploadCompleted=notifyUploadCompleted;const triggerUploadStarted=notifyUploadStarted;_exports.triggerUploadStarted=triggerUploadStarted;const triggerUploadCompleted=notifyUploadCompleted;_exports.triggerUploadCompleted=triggerUploadCompleted;_exports.types={uploadStarted:"core_form/uploadStarted",uploadCompleted:"core_form/uploadCompleted"};let legacyEventsRegistered=!1;legacyEventsRegistered||(_yui.default.use("event","moodle-core-event",(()=>{document.addEventListener(eventTypes.formError,(e=>{const element=_yui.default.one(e.target),formElement=_yui.default.one(e.target.closest("form"));_yui.default.Global.fire(M.core.globalEvents.FORM_ERROR,{formid:formElement.generateID(),elementid:element.generateID()})})),document.addEventListener(eventTypes.formSubmittedByJavascript,(e=>{if(e.detail.fallbackHandled)return;e.skipValidation&&(window.skipClientValidation=!0);const form=_yui.default.one(e.target);form.fire(M.core.event.FORM_SUBMIT_AJAX,{currentTarget:form,fallbackHandled:!0}),e.skipValidation&&(window.skipClientValidation=!1)}))})),document.addEventListener(eventTypes.formFieldValidationFailed,(e=>{const legacyEvent=_jquery.default.Event("core_form-field-validation");(0,_jquery.default)(e.target).trigger(legacyEvent,e.detail.message)})),legacyEventsRegistered=!0);_exports.notifyUploadChanged=elementId=>(0,_event_dispatcher.dispatchEvent)(eventTypes.uploadChanged,{},document.getElementById(elementId),{bubbles:!0,cancellable:!1})})); define("core_grades/grades/grader/gradingpanel/comparison",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.fillInitialValues=_exports.compareData=void 0; /** * Compare a given form's values and its previously set data attributes. * * @module core_grades/grades/grader/gradingpanel/comparison * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const fillInitialValues=form=>{Array.prototype.forEach.call(form.elements,(input=>{"submit"!==input.type&&"button"!==input.type&&("radio"===input.type||"checkbox"===input.type?input.dataset.initialValue=JSON.stringify(input.checked):void 0!==input.value?input.dataset.initialValue=JSON.stringify(input.value):"select-one"===input.type&&Array.prototype.forEach.call(input.options,(option=>{option.dataset.initialValue=JSON.stringify(option.selected)})))}))};_exports.fillInitialValues=fillInitialValues;_exports.compareData=form=>{const result=Array.prototype.some.call(form.elements,(input=>{if("submit"===input.type||"button"===input.type)return!1;if("radio"===input.type||"checkbox"===input.type){if(void 0!==input.dataset.initialValue)return input.dataset.initialValue!==JSON.stringify(input.checked)}else if(void 0!==input.value){if(void 0!==input.dataset.initialValue)return input.dataset.initialValue!==JSON.stringify(input.value)}else if("select-one"===input.type)return Array.prototype.some.call(input.options,(option=>void 0!==option.dataset.initialValue&&option.dataset.initialValue!==JSON.stringify(option.selected)));return!0}));return fillInitialValues(form),result}})); define("core_grades/grades/grader/gradingpanel/normalise",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.normaliseResult=_exports.invalidResult=_exports.failedUpdate=void 0;_exports.normaliseResult=result=>({result:result,failed:!!result.warnings.length,success:!result.warnings.length,error:null});_exports.invalidResult=()=>({success:!1,failed:!1,result:{},error:null});_exports.failedUpdate=error=>({success:!1,failed:!0,result:{},error:error})})); define("core_grades/grades/grader/gradingpanel/point",["exports","./repository","core_grades/grades/grader/gradingpanel/comparison","jquery","./normalise"],(function(_exports,_repository,_comparison,_jquery,_normalise){var obj; /** * Grading panel for simple direct grading. * * @module core_grades/grades/grader/gradingpanel/point * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.storeCurrentGrade=_exports.fetchCurrentGrade=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.fetchCurrentGrade=function(){return(0,_repository.fetchGrade)("point")(...arguments)};_exports.storeCurrentGrade=async(component,context,itemname,userId,notifyUser,rootNode)=>{const form=rootNode.querySelector("form"),grade=form.querySelector('input[name="grade"]');return grade.checkValidity()&&grade.value.trim()?!0===(0,_comparison.compareData)(form)?await(0,_repository.saveGrade)("point")(component,context,itemname,userId,notifyUser,(0,_jquery.default)(form).serialize()):"":_normalise.invalidResult}})); define("core_grades/grades/grader/gradingpanel/repository",["exports","core/ajax","./normalise"],(function(_exports,_ajax,_normalise){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.saveGrade=_exports.fetchGrade=void 0;_exports.fetchGrade=type=>(component,contextid,itemname,gradeduserid)=>(0,_ajax.call)([{methodname:"core_grades_grader_gradingpanel_".concat(type,"_fetch"),args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid}}])[0];_exports.saveGrade=type=>async(component,contextid,itemname,gradeduserid,notifyUser,formdata)=>(0,_normalise.normaliseResult)(await(0,_ajax.call)([{methodname:"core_grades_grader_gradingpanel_".concat(type,"_store"),args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid,notifyuser:notifyUser,formdata:formdata}}])[0])})); define("core_grades/grades/grader/gradingpanel/scale",["exports","./repository","core_grades/grades/grader/gradingpanel/comparison","jquery","./normalise"],(function(_exports,_repository,_comparison,_jquery,_normalise){var obj; /** * Grading panel for simple direct grading. * * @module core_grades/grades/grader/gradingpanel/scale * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.storeCurrentGrade=_exports.fetchCurrentGrade=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.fetchCurrentGrade=function(){return(0,_repository.fetchGrade)("scale")(...arguments)};_exports.storeCurrentGrade=(component,context,itemname,userId,notifyUser,rootNode)=>{const form=rootNode.querySelector("form"),grade=form.querySelector('select[name="grade"]');return grade.checkValidity()&&grade.value.trim()?!0===(0,_comparison.compareData)(form)?(0,_repository.saveGrade)("scale")(component,context,itemname,userId,notifyUser,(0,_jquery.default)(form).serialize()):"":_normalise.invalidResult}})); define("core_grades/searchwidget/basewidget",["exports","core/utils","core/templates","core_grades/searchwidget/selectors","core/notification"],(function(_exports,_utils,Templates,Selectors,_notification){var obj;function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * A widget to search users or grade items within the gradebook. * * @module core_grades/searchwidget/basewidget * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.showLoader=_exports.registerListenerEvents=_exports.promisesAndResolvers=_exports.init=void 0,Templates=_interopRequireWildcard(Templates),Selectors=_interopRequireWildcard(Selectors),_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj};_exports.init=async function(widgetContentContainer,bodyPromise,data,searchFunc){let unsearchableContent=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;bodyPromise.then((async bodyContent=>{if(widgetContentContainer.innerHTML=bodyContent,unsearchableContent){widgetContentContainer.querySelector(Selectors.regions.unsearchableContent).innerHTML+=unsearchableContent}const searchResultsContainer=widgetContentContainer.querySelector(Selectors.regions.searchResults);await showLoader(searchResultsContainer),await renderSearchResults(searchResultsContainer,data),registerListenerEvents(widgetContentContainer,data,searchFunc)})).catch(_notification.default.exception)};const registerListenerEvents=(widgetContentContainer,data,searchFunc)=>{const searchResultsContainer=widgetContentContainer.querySelector(Selectors.regions.searchResults),searchInput=widgetContentContainer.querySelector(Selectors.actions.search);if(!searchInput)return;searchInput.focus();const clearSearchButton=widgetContentContainer.querySelector(Selectors.actions.clearSearch);searchInput.addEventListener("input",(0,_utils.debounce)((async()=>{searchInput.value.length>0?clearSearchButton.classList.remove("d-none"):clearSearchButton.classList.add("d-none"),await renderSearchResults(searchResultsContainer,debounceCallee(searchInput.value,data,searchFunc()))}),300)),clearSearchButton.addEventListener("click",(async e=>{e.stopPropagation(),searchInput.value="",searchInput.focus(),clearSearchButton.classList.add("d-none"),await renderSearchResults(searchResultsContainer,debounceCallee(searchInput.value,data,searchFunc()))}))};_exports.registerListenerEvents=registerListenerEvents;const showLoader=async container=>{const{html:html,js:js}=await Templates.renderForPromise("core_grades/searchwidget/loading",{});Templates.replaceNodeContents(container,html,js)};_exports.showLoader=showLoader;const debounceCallee=(searchValue,data,searchFunction)=>searchValue.length>0?searchFunction(data,searchValue):data,renderSearchResults=async(searchResultsContainer,searchResultsData)=>{const templateData={searchresults:searchResultsData},{html:html,js:js}=await Templates.renderForPromise("core_grades/searchwidget/searchresults",templateData);await Templates.replaceNodeContents(searchResultsContainer,html,js)};_exports.promisesAndResolvers=()=>{let bodyPromiseResolver;const bodyPromise=new Promise((resolve=>{bodyPromiseResolver=resolve}));return{bodyPromiseResolver:bodyPromiseResolver,bodyPromise:bodyPromise}}})); define("core_grades/searchwidget/group",["exports","core/pending","core/templates","core_grades/searchwidget/repository","core_grades/searchwidget/basewidget","jquery","core_grades/searchwidget/selectors"],(function(_exports,_pending,Templates,Repository,WidgetBase,_jquery,Selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A widget to search groups within the gradebook. * * @module core_grades/searchwidget/group * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=_interopRequireDefault(_pending),Templates=_interopRequireWildcard(Templates),Repository=_interopRequireWildcard(Repository),WidgetBase=_interopRequireWildcard(WidgetBase),_jquery=_interopRequireDefault(_jquery),Selectors=_interopRequireWildcard(Selectors);let registered=!1;_exports.init=()=>{if(registered)return;const pendingPromise=new _pending.default;registerListenerEvents(),pendingPromise.resolve(),registered=!0};const registerListenerEvents=()=>{let{bodyPromiseResolver:bodyPromiseResolver,bodyPromise:bodyPromise}=WidgetBase.promisesAndResolvers();const dropdownMenuContainer=document.querySelector(Selectors.elements.getSearchWidgetDropdownSelector("group"));(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("group")).on("show.bs.dropdown",(async e=>{const courseID=e.relatedTarget.dataset.courseid,actionBaseUrl=e.relatedTarget.dataset.actionBaseUrl;await WidgetBase.showLoader(dropdownMenuContainer);const data=await Repository.groupFetch(courseID,actionBaseUrl).catch((async e=>{const errorTemplateData={errormessage:e.message};bodyPromiseResolver(await Templates.render("core_grades/searchwidget/error",errorTemplateData))}));data!==[]&&await WidgetBase.init(dropdownMenuContainer,bodyPromise,data.groups,searchGroups())})),bodyPromiseResolver(Templates.render("core_grades/searchwidget/group/groupsearch_body",[])),(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("group")).on("hide.bs.dropdown",(()=>{dropdownMenuContainer.innerHTML=""}))},searchGroups=()=>()=>(groups,searchTerm)=>{if(""===searchTerm)return groups;searchTerm=searchTerm.toLowerCase();const searchResults=[];return groups.forEach((group=>{group.name.toLowerCase().includes(searchTerm)&&searchResults.push(group)})),searchResults}})); define("core_grades/searchwidget/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * A repo for the search widget. * * @module core_grades/searchwidget/repository * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.userFetch=_exports.groupFetch=_exports.gradeitemFetch=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.userFetch=(courseid,actionBaseUrl,groupId)=>{const request={methodname:"core_grades_get_enrolled_users_for_search_widget",args:{courseid:courseid,actionbaseurl:actionBaseUrl,groupid:groupId}};return _ajax.default.call([request])[0]};_exports.groupFetch=(courseid,actionBaseUrl)=>{const request={methodname:"core_grades_get_groups_for_search_widget",args:{courseid:courseid,actionbaseurl:actionBaseUrl}};return _ajax.default.call([request])[0]};_exports.gradeitemFetch=courseid=>{const request={methodname:"gradereport_singleview_get_grade_items_for_search_widget",args:{courseid:courseid}};return _ajax.default.call([request])[0]}})); define("core_grades/searchwidget/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={regions:{searchResults:'[data-region="search-results-container-widget"]',unsearchableContent:'[data-region="unsearchable-content-container-widget"]'},actions:{search:'[data-action="search"]',clearSearch:'[data-action="clearsearch"]'},elements:{getSearchWidgetSelector:searchtype=>'.search-widget[data-searchtype="'.concat(searchtype,'"]'),getSearchWidgetDropdownSelector:searchtype=>'.search-widget[data-searchtype="'.concat(searchtype,'"] .dropdown-menu')}},_exports.default})); /** * Enhance the gradebook tree setup with various facilities. * * @module core_grades/edittree_index * @copyright 2016 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_grades/edittree_index",["jquery"],(function($){var edittree=function(){$("body").on("change",".weightoverride",edittree.toggleWeightInput),$("#menumoveafter").on("change",(function(){var form=$(this).closest("form");form.find("#bulkmoveinput").val(1),form.submit()}))};return edittree.toggleWeightInput=function(e){e.preventDefault();var node=$(this),row=node.closest("tr");$('input[name="weight_'+row.data("itemid")+'"]').prop("disabled",!node.prop("checked"))},{enhance:edittree}})); define("core_h5p/editor_display",["exports","jquery"],(function(_exports,_jquery){var obj; /** * This module handles the display of the H5P authoring tool. * * @module core_h5p/editor_display * @copyright 2020 Victor Deniz <victor@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.init=elementId=>{const editorwrapper=(0,_jquery.default)("#"+elementId),editor=(0,_jquery.default)(".h5p-editor"),mform=editor.closest("form"),editorupload=(0,_jquery.default)("h5p-editor-upload"),h5plibrary=(0,_jquery.default)('input[name="h5plibrary"]'),h5pparams=(0,_jquery.default)('input[name="h5pparams"]'),inputname=(0,_jquery.default)('input[name="name"]'),h5paction=(0,_jquery.default)('input[name="h5paction"]');h5paction.val("create"),H5PEditor.init(mform,h5paction,editorupload,editorwrapper,editor,h5plibrary,h5pparams,"",inputname,(function($button){return $button.is('[name="cancel"]')})),document.querySelector("#"+elementId+" iframe").setAttribute("name","h5p-editor")}})); define("core_message/default_notification_preferences",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Controls the default settings for the list of notification types on the * notifications admin page * * @module core_message/default_notification_preferences * @class default_notification_preferences * @copyright 2021 Moodle * @author Pau Ferrer Ocaña <pau@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const selectors_provider=".defaultmessageoutputs .provider_enabled",selectors_lockSetting=".locked_message_setting",selectors_allSettings=".locked_message_setting, .enabled_message_setting";var _default={init:()=>{(()=>{const toggleLockSetting=lockedElement=>{const isEnabled=lockedElement.checked||!1,enabledId=lockedElement.id.replace("_locked[","_enabled[");document.getElementById(enabledId).closest("div.custom-control").classList.toggle("dimmed_text",isEnabled)},toggleEnableProviderSettings=providerEnabledElement=>{const isEnabled=providerEnabledElement.checked||!1;providerEnabledElement.closest("tr").querySelectorAll(selectors_allSettings).forEach((element=>{element.toggleAttribute("disabled",!isEnabled)}))},container=document.querySelector(".preferences-container");container.querySelectorAll(selectors_provider).forEach((providerEnabledElement=>{providerEnabledElement.checked||toggleEnableProviderSettings(providerEnabledElement),providerEnabledElement.addEventListener("change",(e=>{toggleEnableProviderSettings(e.target)}))})),container.querySelectorAll(selectors_lockSetting).forEach((lockedElement=>{lockedElement.checked&&toggleLockSetting(lockedElement),lockedElement.addEventListener("change",(e=>{toggleLockSetting(e.target)}))}))})()}};return _exports.default=_default,_exports.default})); /** * Controls the message drawer. * * @module core_message/message_drawer * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer",["jquery","core/custom_interaction_events","core/pubsub","core_message/message_drawer_view_contact","core_message/message_drawer_view_contacts","core_message/message_drawer_view_conversation","core_message/message_drawer_view_group_info","core_message/message_drawer_view_overview","core_message/message_drawer_view_search","core_message/message_drawer_view_settings","core_message/message_drawer_router","core_message/message_drawer_routes","core_message/message_drawer_events","core_message/message_drawer_helper","core/pending","core/drawer"],(function($,CustomEvents,PubSub,ViewContact,ViewContacts,ViewConversation,ViewGroupInfo,ViewOverview,ViewSearch,ViewSettings,Router,Routes,Events,Helper,Pending,Drawer){var SELECTORS_DRAWER='[data-region="right-hand-drawer"]',SELECTORS_JUMPTO='.popover-region [data-region="jumpto"]',SELECTORS_PANEL_BODY_CONTAINER='[data-region="panel-body-container"]',SELECTORS_PANEL_HEADER_CONTAINER='[data-region="panel-header-container"]',SELECTORS_VIEW_CONTACT='[data-region="view-contact"]',SELECTORS_VIEW_CONTACTS='[data-region="view-contacts"]',SELECTORS_VIEW_CONVERSATION='[data-region="view-conversation"]',SELECTORS_VIEW_GROUP_INFO='[data-region="view-group-info"]',SELECTORS_VIEW_OVERVIEW='[data-region="view-overview"]',SELECTORS_VIEW_SEARCH='[data-region="view-search"]',SELECTORS_VIEW_SETTINGS='[data-region="view-settings"]',SELECTORS_ROUTES="[data-route]",SELECTORS_ROUTES_BACK="[data-route-back]",SELECTORS_HEADER_CONTAINER='[data-region="header-container"]',SELECTORS_BODY_CONTAINER='[data-region="body-container"]',SELECTORS_FOOTER_CONTAINER='[data-region="footer-container"]',SELECTORS_CLOSE_BUTTON='[data-action="closedrawer"]',routes=[[Routes.VIEW_CONTACT,SELECTORS_VIEW_CONTACT,ViewContact.show,ViewContact.description],[Routes.VIEW_CONTACTS,SELECTORS_VIEW_CONTACTS,ViewContacts.show,ViewContacts.description],[Routes.VIEW_CONVERSATION,SELECTORS_VIEW_CONVERSATION,ViewConversation.show,ViewConversation.description],[Routes.VIEW_GROUP_INFO,SELECTORS_VIEW_GROUP_INFO,ViewGroupInfo.show,ViewGroupInfo.description],[Routes.VIEW_OVERVIEW,SELECTORS_VIEW_OVERVIEW,ViewOverview.show,ViewOverview.description],[Routes.VIEW_SEARCH,SELECTORS_VIEW_SEARCH,ViewSearch.show,ViewSearch.description],[Routes.VIEW_SETTINGS,SELECTORS_VIEW_SETTINGS,ViewSettings.show,ViewSettings.description]],createRoutes=function(namespace,root){routes.forEach((function(route){Router.add(namespace,route[0],function(namespace,root,selector){var header=root.find(SELECTORS_HEADER_CONTAINER).find(selector);header.length||(header=root.find(SELECTORS_PANEL_HEADER_CONTAINER).find(selector));var body=root.find(SELECTORS_BODY_CONTAINER).find(selector);body.length||(body=root.find(SELECTORS_PANEL_BODY_CONTAINER).find(selector));var footer=root.find(SELECTORS_FOOTER_CONTAINER).find(selector);return[namespace,header.length?header:null,body.length?body:null,footer.length?footer:null]}(namespace,root,route[1]),route[2],route[3])}))},show=function(namespace,root){root.attr("data-shown")||(Router.go(namespace,Routes.VIEW_OVERVIEW),root.attr("data-shown",!0));var drawerRoot=Drawer.getDrawerRoot(root);drawerRoot.length&&Drawer.show(drawerRoot)},hide=function(root){var drawerRoot=Drawer.getDrawerRoot(root);drawerRoot.length&&Drawer.hide(drawerRoot)},setJumpFrom=function(buttonid){$(SELECTORS_DRAWER).attr("data-origin",buttonid)},registerEventListeners=function(namespace,root,alwaysVisible){CustomEvents.define(root,[CustomEvents.events.activate]);var paramRegex=/^data-route-param-?(\d*)$/;root.on(CustomEvents.events.activate,SELECTORS_ROUTES,(function(e,data){for(var element=$(e.target).closest(SELECTORS_ROUTES),route=element.attr("data-route"),attributes=[],i=0;i<element[0].attributes.length;i++)attributes.push(element[0].attributes[i]);var paramAttributes=attributes.filter((function(attribute){var name=attribute.nodeName;return paramRegex.test(name)}));paramAttributes.sort((function(a,b){var aParts=paramRegex.exec(a.nodeName),bParts=paramRegex.exec(b.nodeName),aIndex=aParts.length>1?aParts[1]:0,bIndex=bParts.length>1?bParts[1]:0;return aIndex<bIndex?-1:bIndex<aIndex?1:0}));var params=paramAttributes.map((function(attribute){return attribute.nodeValue})),routeParams=[namespace,route].concat(params);Router.go.apply(null,routeParams),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,SELECTORS_ROUTES_BACK,(function(e,data){Router.back(namespace),data.originalEvent.preventDefault()})),root.on("hide.bs.collapse",".collapse",(function(e){var pendingPromise=new Pending;$(e.target).one("hidden.bs.collapse",(function(){pendingPromise.resolve()}))})),root.on("show.bs.collapse",".collapse",(function(e){var pendingPromise=new Pending;$(e.target).one("shown.bs.collapse",(function(){pendingPromise.resolve()}))})),$(SELECTORS_JUMPTO).focus((function(){var firstInput=root.find(SELECTORS_CLOSE_BUTTON);firstInput.length?firstInput.focus():$(SELECTORS_HEADER_CONTAINER).find(SELECTORS_ROUTES_BACK).focus()})),$(SELECTORS_DRAWER).focus((function(){var button=$(this).attr("data-origin");button&&$("#"+button).focus()})),alwaysVisible||(PubSub.subscribe(Events.SHOW,(function(){show(namespace,root)})),PubSub.subscribe(Events.HIDE,(function(){hide(root)})),PubSub.subscribe(Events.TOGGLE_VISIBILITY,(function(buttonid){!function(root){var drawerRoot=Drawer.getDrawerRoot(root);return!drawerRoot.length||Drawer.isVisible(drawerRoot)}(root)?(show(namespace,root),setJumpFrom(buttonid),$(SELECTORS_JUMPTO).attr("tabindex",0)):(hide(root),$(SELECTORS_JUMPTO).attr("tabindex",-1))}))),PubSub.subscribe(Events.SHOW_CONVERSATION,(function(args){setJumpFrom(args.buttonid),show(namespace,root),Router.go(namespace,Routes.VIEW_CONVERSATION,args.conversationid)})),root.find(SELECTORS_CLOSE_BUTTON).on(CustomEvents.events.activate,(function(e,data){data.originalEvent.preventDefault();var button=$(SELECTORS_DRAWER).attr("data-origin");button&&$("#"+button).focus(),PubSub.publish(Events.TOGGLE_VISIBILITY)})),PubSub.subscribe(Events.CREATE_CONVERSATION_WITH_USER,(function(args){setJumpFrom(args.buttonid),show(namespace,root),Router.go(namespace,Routes.VIEW_CONVERSATION,null,"create",args.userid)})),PubSub.subscribe(Events.SHOW_SETTINGS,(function(){show(namespace,root),Router.go(namespace,Routes.VIEW_SETTINGS)})),PubSub.subscribe(Events.PREFERENCES_UPDATED,(function(preferences){var filteredPreferences=preferences.filter((function(preference){return"message_entertosend"==preference.type})),enterToSendPreference=filteredPreferences.length?filteredPreferences[0]:null;enterToSendPreference&&root.find(SELECTORS_FOOTER_CONTAINER).find(SELECTORS_VIEW_CONVERSATION).attr("data-enter-to-send",enterToSendPreference.value)}))};return{init:function(root,uniqueId,alwaysVisible,route){if(root=$(root),createRoutes(uniqueId,root),registerEventListeners(uniqueId,root,alwaysVisible),alwaysVisible&&(show(uniqueId,root),route)){var routeParams=route.params||[];routeParams=[uniqueId,route.path].concat(routeParams),Router.go.apply(null,routeParams)}Helper.markDrawerReady()}}})); define("core_message/message_drawer_events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={CREATE_CONVERSATION_WITH_USER:"message-drawer-create-conversation-with-user",CONTACT_BLOCKED:"message-drawer-contact-blocked",CONTACT_UNBLOCKED:"message-drawer-contact-unblocked",CONTACT_ADDED:"message-drawer-contact-added",CONTACT_REMOVED:"message-drawer-contact-removed",CONTACT_REQUEST_ACCEPTED:"message-drawer-contact-request-accepted",CONTACT_REQUEST_DECLINED:"message-drawer-contact-request-declined",CONVERSATION_CREATED:"message-drawer-conversation-created",CONVERSATION_NEW_LAST_MESSAGE:"message-drawer-conversation-new-last-message",CONVERSATION_DELETED:"message-drawer-conversation-deleted",CONVERSATION_READ:"message-drawer-conversation-read",CONVERSATION_SET_FAVOURITE:"message-drawer-conversation-set-favourite",CONVERSATION_SET_MUTED:"message-drawer-conversation-set-muted",CONVERSATION_UNSET_FAVOURITE:"message-drawer-conversation-unset-favourite",CONVERSATION_UNSET_MUTED:"message-drawer-conversation-unset-muted",PREFERENCES_UPDATED:"message-drawer-preferences-updated",READY:"message-drawer-ready",ROUTE_CHANGED:"message-drawer-route-change",SHOW:"message-drawer-show",HIDE:"message-drawer-hide",TOGGLE_VISIBILITY:"message-drawer-toggle",SHOW_CONVERSATION:"message-drawer-show-conversation",SHOW_SETTINGS:"message-drawer-show-settings"},_exports.default})); define("core_message/message_drawer_helper",["exports","core/pubsub","core_message/message_drawer_events"],(function(_exports,_pubsub,_message_drawer_events){var obj; /** * Provides some helper functions to trigger actions in the message drawer. * * @module core_message/message_drawer_helper * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.waitForDrawerToLoad=_exports.showSettings=_exports.showConversation=_exports.show=_exports.markDrawerReady=_exports.hide=_exports.createConversationWithUser=void 0,_message_drawer_events=(obj=_message_drawer_events)&&obj.__esModule?obj:{default:obj};let drawerMarkedReady=!1;_exports.createConversationWithUser=async args=>{await waitForDrawerToLoad(),(0,_pubsub.publish)(_message_drawer_events.default.CREATE_CONVERSATION_WITH_USER,args)};_exports.hide=async()=>{await waitForDrawerToLoad(),(0,_pubsub.publish)(_message_drawer_events.default.HIDE)};_exports.show=async()=>{await waitForDrawerToLoad(),(0,_pubsub.publish)(_message_drawer_events.default.SHOW)};_exports.showConversation=async args=>{await waitForDrawerToLoad(),(0,_pubsub.publish)(_message_drawer_events.default.SHOW_CONVERSATION,args)};_exports.showSettings=async()=>{await waitForDrawerToLoad(),(0,_pubsub.publish)(_message_drawer_events.default.SHOW_SETTINGS)};const waitForDrawerToLoad=()=>new Promise((resolve=>{drawerMarkedReady?resolve():(0,_pubsub.subscribe)(_message_drawer_events.default.READY,resolve)}));_exports.waitForDrawerToLoad=waitForDrawerToLoad;_exports.markDrawerReady=()=>{drawerMarkedReady=!0,(0,_pubsub.publish)(_message_drawer_events.default.READY)}})); /** * Lazy loaded list of items. * * @module core_message/message_drawer_lazy_load_list * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_lazy_load_list",["jquery","core/custom_interaction_events"],(function($,CustomEvents){var SELECTORS_ROOT='[data-region="lazy-load-list"]',SELECTORS_LOADING_ICON_CONTAINER='[data-region="loading-icon-container"]',SELECTORS_CONTENT_CONTAINER='[data-region="content-container"]',SELECTORS_EMPTY_MESSAGE='[data-region="empty-message-container"]',SELECTORS_PLACEHOLDER='[data-region="placeholder-container"]',stopLoading=function(root){root.attr("data-loading",!1)},getContentContainer=function(root){return root.find(SELECTORS_CONTENT_CONTAINER)},hideLoadingIcon=function(root){root.find(SELECTORS_LOADING_ICON_CONTAINER).addClass("hidden")},showEmptyMessage=function(root){root.find(SELECTORS_EMPTY_MESSAGE).removeClass("hidden")},hidePlaceholder=function(root){root.find(SELECTORS_PLACEHOLDER).addClass("hidden")},showContent=function(root){getContentContainer(root).removeClass("hidden")},hideContent=function(root){getContentContainer(root).addClass("hidden")},setLoadedAll=function(root,value){root.attr("data-loaded-all",value)},loadAndRender=function(root,loadCallback,renderCallback){var userId=function(root){return root.attr("data-user-id")}(root);return function(root){root.attr("data-loading",!0)}(root),loadCallback(root,userId).then((function(items){if(items.length>0){var contentContainer=getContentContainer(root);return renderCallback(contentContainer,items,userId).then((function(){return items}))}return items})).then((function(items){return stopLoading(root),root.attr("data-seen",!0),items.length||setLoadedAll(root,!0),items})).catch((function(){stopLoading(root),root.attr("data-seen",!0)}))},initialLoadAndRender=function(root,loadCallback,renderCallback){return getContentContainer(root).empty(),function(root){root.find(SELECTORS_PLACEHOLDER).removeClass("hidden")}(root),hideContent(root),loadAndRender(root,loadCallback,renderCallback).then((function(items){hidePlaceholder(root),items.length?showContent(root):showEmptyMessage(root)})).catch((function(){hidePlaceholder(root),showContent(root)}))},registerEventListeners=function(root,loadCallback,renderCallback){CustomEvents.define(root,[CustomEvents.events.scrollBottom]),root.on(CustomEvents.events.scrollBottom,(function(){(function(root){return!function(root){return"true"==root.attr("data-loaded-all")}(root)&&!function(root){return"true"===root.attr("data-loading")}(root)})(root)&&(!function(root){root.find(SELECTORS_LOADING_ICON_CONTAINER).removeClass("hidden")}(root),loadAndRender(root,loadCallback,renderCallback).then((function(){return hideLoadingIcon(root)})).catch((function(){return hideLoadingIcon(root)})))}))};return{show:function(root,loadCallback,renderCallback){(root=$(root)).attr("data-init")||(registerEventListeners(root,loadCallback,renderCallback),initialLoadAndRender(root,loadCallback,renderCallback),root.attr("data-init",!0))},getContentContainer:getContentContainer,getRoot:function(containerElement){return containerElement.find(SELECTORS_ROOT)},setLoadedAll:setLoadedAll,showEmptyMessage:showEmptyMessage,hideEmptyMessage:function(root){root.find(SELECTORS_EMPTY_MESSAGE).addClass("hidden")},showContent:showContent,hideContent:hideContent}})); /** * A simple router for the message drawer that allows navigating between * the "pages" in the drawer. * * This module will maintain a linear history of the unique pages access * to allow navigating back. * * @module core_message/message_drawer_router * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_router",["jquery","core/pubsub","core/str","core_message/message_drawer_events","core/aria"],(function($,PubSub,Str,MessageDrawerEvents,Aria){var routes={},history={},SELECTORS_CAN_RECEIVE_FOCUS='input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',SELECTORS_ROUTES_BACK="[data-route-back]",changeRoute=function(namespace,newRoute){var newConfig,fromPanel=[].slice.call(arguments).some((function(arg){return"frompanel"==arg})),args=[].slice.call(arguments,2),renderPromise=$.Deferred().resolve().promise();if(Object.keys(routes[namespace]).forEach((function(route){var config=routes[namespace][route],isMatch=route===newRoute;isMatch&&(newConfig=config),config.parameters.forEach((function(element){"object"==typeof element&&null!==element&&(element.removeClass("previous"),element.attr("data-from-panel",!1),isMatch?(fromPanel&&element.attr("data-from-panel",!0),element.removeClass("hidden"),Aria.unhide(element.get())):element.attr("data-in-panel")&&"view-search"!=newRoute&&"view-overview"!=newRoute||(element.addClass("hidden"),Aria.hide(element.get())))}))})),newConfig&&newConfig.onGo){renderPromise=newConfig.onGo.apply(void 0,newConfig.parameters.concat(args));for(var currentFocusElement=$(document.activeElement),hasFocus=!1,firstFocusable=null,i=1;i<newConfig.parameters.length;i++){var element=newConfig.parameters[i];if("object"==typeof element&&null!==element&&(firstFocusable||(firstFocusable=element),element.has(currentFocusElement).length)){hasFocus=!0;break}}hasFocus||firstFocusable.find(SELECTORS_CAN_RECEIVE_FOCUS).filter(":visible").first().focus()}var record={route:newRoute,params:args,renderPromise:renderPromise};return PubSub.publish(MessageDrawerEvents.ROUTE_CHANGED,record),record},go=function(namespace){var currentFocusElement=$(document.activeElement),record=changeRoute.apply(namespace,arguments),inHistory=!1;history[namespace]||(history[namespace]=[]),history[namespace]=history[namespace].reduce((function(carry,previous){return previous.route===record.route&&(inHistory=!0),inHistory||carry.push(previous),carry}),[]);var historylength=history[namespace].length,previousRecord=historylength?history[namespace][historylength-1]:null;if(previousRecord){for(var prevConfig=routes[namespace][previousRecord.route],elements=prevConfig.parameters,i=1;i<elements.length;i++)"object"==typeof elements[i]&&null!==elements[i]&&elements[i].addClass("previous");previousRecord.focusElement=currentFocusElement,prevConfig.getDescription&&prevConfig.getDescription.apply(null,prevConfig.parameters.concat(previousRecord.params)).then((function(description){return Str.get_string("backto","core_message",description)})).then((function(label){return record.renderPromise.then((function(){routes[namespace][record.route].parameters.forEach((function(element){"object"==typeof element&&element&&element.find(SELECTORS_ROUTES_BACK).attr("aria-label",label)}))}))})).catch((function(){}))}return history[namespace].push(record),record};return{add:function(namespace,route,parameters,onGo,getDescription){routes[namespace]||(routes[namespace]=[]),routes[namespace][route]={parameters:parameters,onGo:onGo,getDescription:getDescription}},go:go,back:function(namespace){if(history[namespace].length){history[namespace].pop();var previous=history[namespace].pop();previous&&(go.apply(void 0,[namespace,previous.route].concat(previous.params)),window.setTimeout((function(){previous.focusElement.focus()}),50))}}}})); /** * Available routes for the message drawer. * * @module core_message/message_drawer_routes * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_routes",[],(function(){return{VIEW_CONTACT:"view-contact",VIEW_CONTACTS:"view-contacts",VIEW_CONVERSATION:"view-conversation",VIEW_GROUP_INFO:"view-group-info",VIEW_OVERVIEW:"view-overview",VIEW_SEARCH:"view-search",VIEW_SETTINGS:"view-settings"}})); /** * Controls the contact page in the message drawer. * * @module core_message/message_drawer_view_contact * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_contact",["jquery","core/str","core/templates"],(function($,Str,Templates){var SELECTORS_CONTENT_CONTAINER='[data-region="content-container"]',TEMPLATES_CONTENT="core_message/message_drawer_view_contact_body_content",getContentContainer=function(root){return root.find(SELECTORS_CONTENT_CONTAINER)};return{show:function(namespace,header,body,footer,contact){var root=$(body);return getContentContainer(root).empty(),function(root,profile){return Templates.render(TEMPLATES_CONTENT,profile).then((function(html){return getContentContainer(root).append(html),html}))}(root,contact)},description:function(root,contact){return Str.get_string("messagedrawerviewcontact","core_message",contact.fullname)}}})); /** * Controls the contacts page of the message drawer. * * @module core_message/message_drawer_view_contacts * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_contacts",["jquery","core/pubsub","core/str","core_message/message_drawer_events","core_message/message_drawer_view_contacts_section_contacts","core_message/message_drawer_view_contacts_section_requests"],(function($,PubSub,Str,MessageDrawerEvents,ContactsSection,RequestsSection){var SELECTORS_ACTION_SHOW_CONTACTS_SECTION='[data-action="show-contacts-section"]',SELECTORS_ACTION_SHOW_REQUESTS_SECTION='[data-action="show-requests-section"]',SELECTORS_CONTACT_REQUEST_COUNT='[data-region="contact-request-count"]',SELECTORS_CONTACTS_SECTION_CONTAINER='[data-section="contacts"]',SELECTORS_REQUESTS_SECTION_CONTAINER='[data-section="requests"]',getContactsSectionContainer=function(body){return body.find(SELECTORS_CONTACTS_SECTION_CONTAINER)},getRequestsSectionContainer=function(body){return body.find(SELECTORS_REQUESTS_SECTION_CONTAINER)},getShowContactsAction=function(body){return body.find(SELECTORS_ACTION_SHOW_CONTACTS_SECTION)},getShowRequestsAction=function(body){return body.find(SELECTORS_ACTION_SHOW_REQUESTS_SECTION)},decrementContactRequestCount=function(body){return function(){var countContainer=body.find(SELECTORS_CONTACT_REQUEST_COUNT),count=parseInt(countContainer.text(),10);(count=isNaN(count)?0:count-1)<=0?countContainer.addClass("hidden"):countContainer.text(count)}};return{show:function(namespace,header,body,footer,tab){(body=$(body)).attr("data-contacts-init")||(!function(body){var contactsSection=getContactsSectionContainer(body),requestsSection=getRequestsSectionContainer(body),showContactsAction=getShowContactsAction(body),showRequestsAction=getShowRequestsAction(body);showContactsAction.on("show.bs.tab",(function(){ContactsSection.show(contactsSection)})),showRequestsAction.on("show.bs.tab",(function(){RequestsSection.show(requestsSection)})),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,decrementContactRequestCount(body)),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,decrementContactRequestCount(body))}(body),body.attr("data-contacts-init",!0));var contactsSection=getContactsSectionContainer(body),requestsSection=getRequestsSectionContainer(body);if(tab){var showContactsAction=getShowContactsAction(body),showRequestsAction=getShowRequestsAction(body);"requests"==tab?(showContactsAction.removeClass("active"),contactsSection.removeClass("show active"),showRequestsAction.addClass("active"),requestsSection.addClass("show active")):(showRequestsAction.removeClass("active"),requestsSection.removeClass("show active"),showContactsAction.addClass("active"),contactsSection.addClass("show active"))}return contactsSection.hasClass("active")?ContactsSection.show(contactsSection):RequestsSection.show(requestsSection),$.Deferred().resolve().promise()},description:function(){return Str.get_string("messagedrawerviewcontacts","core_message")}}})); /** * Controls the contacts section of the contacts page. * * @module core_message/message_drawer_view_contacts_section_contacts * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_contacts_section_contacts",["jquery","core/notification","core/pubsub","core/templates","core_message/message_repository","core_message/message_drawer_events","core_message/message_drawer_lazy_load_list"],(function($,Notification,PubSub,Templates,MessageRepository,Events,LazyLoadList){var SELECTORS_BLOCK_ICON_CONTAINER='[data-region="block-icon-container"]',SELECTORS_CONTACT='[data-region="contact"]',TEMPLATES_CONTACTS_LIST="core_message/message_drawer_contacts_list",findContact=function(body,userId){return body.find('[data-contact-user-id="'+userId+'"]')},render=function(contentContainer,contacts){var formattedContacts=contacts.map((function(contact){return $.extend(contact,{id:contact.userid})}));return Templates.render(TEMPLATES_CONTACTS_LIST,{contacts:formattedContacts}).then((function(html){return contentContainer.append(html),html})).catch(Notification.exception)},registerEventListeners=function(root){PubSub.subscribe(Events.CONTACT_ADDED,(function(profile){var listContentContainer=LazyLoadList.getContentContainer(root);render(listContentContainer,[profile]),LazyLoadList.hideEmptyMessage(root),LazyLoadList.showContent(root)})),PubSub.subscribe(Events.CONTACT_REMOVED,(function(userId){!function(body,userId){findContact(body,userId).remove()}(root,userId),root.find(SELECTORS_CONTACT).length||(LazyLoadList.hideContent(root),LazyLoadList.showEmptyMessage(root))})),PubSub.subscribe(Events.CONTACT_BLOCKED,(function(userId){!function(body,userId){var contact=findContact(body,userId);contact.length&&contact.find(SELECTORS_BLOCK_ICON_CONTAINER).removeClass("hidden")}(root,userId)})),PubSub.subscribe(Events.CONTACT_UNBLOCKED,(function(userId){!function(body,userId){var contact=findContact(body,userId);contact.length&&contact.find(SELECTORS_BLOCK_ICON_CONTAINER).addClass("hidden")}(root,userId)}))};return{show:function(root){var offset;root.attr("data-contacts-init")||(registerEventListeners(root),root.attr("data-contacts-init",!0)),LazyLoadList.show(root,(offset=0,function(listRoot,userId){return MessageRepository.getContacts(userId,101,offset).then((function(result){return result})).then((function(contacts){return contacts.length>100?contacts.pop():LazyLoadList.setLoadedAll(listRoot,!0),contacts})).then((function(contacts){return offset+=100,contacts})).catch(Notification.exception)}),render)}}})); /** * Controls the requests section of the contacts page. * * @module core_message/message_drawer_view_contacts_section_requests * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_contacts_section_requests",["jquery","core/notification","core/pubsub","core/templates","core_message/message_repository","core_message/message_drawer_events","core_message/message_drawer_lazy_load_list"],(function($,Notification,PubSub,Templates,MessageRepository,MessageDrawerEvents,LazyLoadList){var SELECTORS_CONTACT_REQUEST='[data-region="contact-request"]',TEMPLATES_REQUESTS_LIST="core_message/message_drawer_view_contacts_body_section_requests_list",render=function(contentContainer,requests){var formattedRequests=requests.map((function(request){return{id:request.id,profileimageurl:request.profileimageurl,fullname:request.fullname}}));return Templates.render(TEMPLATES_REQUESTS_LIST,{requests:formattedRequests}).then((function(html){return contentContainer.append(html),html})).catch(Notification.exception)},load=function(listRoot,userId){return MessageRepository.getContactRequests(userId).then((function(requests){return LazyLoadList.setLoadedAll(listRoot,!0),requests})).catch(Notification.exception)},handleContactRequestProcessed=function(root){return function(request){root.find('[data-request-id="'+request.userid+'"]').remove(),root.find(SELECTORS_CONTACT_REQUEST).length||(LazyLoadList.showEmptyMessage(root),LazyLoadList.hideContent(root))}};return{show:function(root){root.attr("data-contacts-init")||(!function(root){PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,handleContactRequestProcessed(root)),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,handleContactRequestProcessed(root))}(root),root.attr("data-contacts-init",!0)),LazyLoadList.show(root,load,render)}}})); /** * Controls the conversation page in the message drawer. * * This function handles all of the user actions that the user can take * when interacting with the conversation page. * * It maintains a view state which is a data representation of the view * and only operates on that data. * * The view state is immutable and should never be modified directly. Instead * all changes to the view state should be done using the StateManager which * will generate a new version of the view state with the requested changes. * * After any changes to the view state the module will call the render function * to ask the renderer to update the UI. * * General rules for this module: * 1.) Never modify viewState directly. All changes should be via the StateManager. * 2.) Call render() with the new state when you want to update the UI * 3.) Never modify the UI directly in this module. This module is only concerned * with the data in the view state. * * The general flow for a user interaction will be something like: * User interaction: User clicks "confirm block" button to block the other user * 1.) This module is hears the click * 2.) This module sends a request to the server to block the user * 3.) The server responds with the new user profile * 4.) This module generates a new state using the StateManager with the updated * user profile. * 5.) This module asks the Patcher to generate a patch from the current state and * the newly generated state. This patch tells the renderer what has changed * between the states. * 6.) This module gives the Renderer the generated patch. The renderer updates * the UI with changes according to the patch. * * @module core_message/message_drawer_view_conversation * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_conversation",["jquery","core/auto_rows","core/backoff_timer","core/custom_interaction_events","core/notification","core/pending","core/pubsub","core/str","core_message/message_repository","core_message/message_drawer_events","core_message/message_drawer_view_conversation_constants","core_message/message_drawer_view_conversation_patcher","core_message/message_drawer_view_conversation_renderer","core_message/message_drawer_view_conversation_state_manager","core_message/message_drawer_router","core_message/message_drawer_routes","core/emoji/auto_complete","core/emoji/picker"],(function($,AutoRows,BackOffTimer,CustomEvents,Notification,Pending,PubSub,Str,Repository,MessageDrawerEvents,Constants,Patcher,Renderer,StateManager,MessageDrawerRouter,MessageDrawerRoutes,initialiseEmojiAutoComplete,initialiseEmojiPicker){var stateCache={},viewState=null,loadedAllMessages=!1,messagesOffset=0,newMessagesPollTimer=null,isRendering=!1,renderBuffer=[],isResetting=!0,isSendingMessage=!1,isDeletingConversationContent=!1,sendMessageBuffer=[],render=null,renderers=[],NEWEST_FIRST=Constants.NEWEST_MESSAGES_FIRST,LOAD_MESSAGE_LIMIT=Constants.LOAD_MESSAGE_LIMIT,MILLISECONDS_IN_SEC=Constants.MILLISECONDS_IN_SEC,SELECTORS=Constants.SELECTORS,CONVERSATION_TYPES=Constants.CONVERSATION_TYPES,getOtherUserId=function(){if(!viewState||viewState.type==CONVERSATION_TYPES.PUBLIC)return null;var loggedInUserId=viewState.loggedInUserId;if(viewState.type==CONVERSATION_TYPES.SELF)return loggedInUserId;var otherUserIds=Object.keys(viewState.members).filter((function(userId){return loggedInUserId!=userId}));return otherUserIds.length?otherUserIds[0]:null},getMessagesOffset=function(){return messagesOffset},setMessagesOffset=function(value){messagesOffset=value,stateCache[viewState.id].messagesOffset=value},hasLoadedAllMessages=function(){return loadedAllMessages},setLoadedAllMessages=function(value){loadedAllMessages=value,stateCache[viewState.id].loadedAllMessages=value},formatConversationForEvent=function(state){return{id:state.id,name:state.name,subname:state.subname,imageUrl:state.imageUrl,isFavourite:state.isFavourite,isMuted:state.isMuted,type:state.type,totalMemberCount:state.totalMemberCount,loggedInUserId:state.loggedInUserId,messages:state.messages.map((function(message){return $.extend({},message)})),members:Object.keys(state.members).map((function(id){var formattedMember=$.extend({},state.members[id]);return formattedMember.contactrequests=state.members[id].contactrequests.map((function(request){return $.extend({},request)})),formattedMember}))}},updateStateFromConversation=function(conversation,loggedInUserId){var otherUser=null;if(conversation.type==CONVERSATION_TYPES.PRIVATE){var otherUsers=conversation.members.filter((function(member){return member.id!=loggedInUserId}));otherUser=otherUsers.length?otherUsers[0]:null}else conversation.type==CONVERSATION_TYPES.SELF&&(otherUser=conversation.members[0]);var name=conversation.name,imageUrl=conversation.imageurl;conversation.type!=CONVERSATION_TYPES.PUBLIC&&(name=name||otherUser?otherUser.fullname:"",imageUrl=imageUrl||otherUser?otherUser.profileimageurl:"");var newState=StateManager.addMembers(viewState,conversation.members);return newState=StateManager.setName(newState,name),newState=StateManager.setSubname(newState,conversation.subname),newState=StateManager.setType(newState,conversation.type),newState=StateManager.setImageUrl(newState,imageUrl),newState=StateManager.setTotalMemberCount(newState,conversation.membercount),newState=StateManager.setIsFavourite(newState,conversation.isfavourite),newState=StateManager.setIsMuted(newState,conversation.ismuted),newState=StateManager.addMessages(newState,conversation.messages),newState=StateManager.setCanDeleteMessagesForAllUsers(newState,conversation.candeletemessagesforallusers)},loadMessages=function(conversationId,limit,offset,newestFirst,ignoreList,timeFrom){return Repository.getMessages(viewState.loggedInUserId,conversationId,limit?limit+1:limit,offset,newestFirst,timeFrom).then((function(result){return result.id!=viewState.id&&(result.messages=[],result.id in stateCache&&delete stateCache[result.id]),result})).then((function(result){return result.messages.length&&ignoreList.length&&(result.messages=result.messages.filter((function(message){return ignoreList.indexOf(parseInt(message.id,10))<0}))),result})).then((function(result){return limit?(result.messages.length>limit?result.messages=result.messages.slice(0,-1):setLoadedAllMessages(!0),result):result})).then((function(result){var membersToAdd=result.members.filter((function(member){return!(member.id in viewState.members)})),newState=StateManager.addMembers(viewState,membersToAdd);return newState=StateManager.addMessages(newState,result.messages),newState=StateManager.setLoadingMessages(newState,!1),render(newState).then((function(){return result}))})).catch((function(error){var newState=StateManager.setLoadingMessages(viewState,!1);throw render(newState),error}))},markConversationAsRead=function(conversationId){var loggedInUserId=viewState.loggedInUserId,pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead");return Repository.markAllConversationMessagesAsRead(loggedInUserId,conversationId).then((function(){var newState=StateManager.markMessagesAsRead(viewState,viewState.messages);return PubSub.publish(MessageDrawerEvents.CONVERSATION_READ,conversationId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestBlockUser=function(userId){cancelRequest(userId);var newState=StateManager.addPendingBlockUsersById(viewState,[userId]);render(newState)},blockUser=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:blockUser");return render(newState),Repository.blockUser(viewState.loggedInUserId,userId).then((function(profile){var newState=StateManager.addMembers(viewState,[profile]);return newState=StateManager.removePendingBlockUsersById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_BLOCKED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestUnblockUser=function(userId){cancelRequest(userId);var newState=StateManager.addPendingUnblockUsersById(viewState,[userId]);render(newState)},unblockUser=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:unblockUser");return render(newState),Repository.unblockUser(viewState.loggedInUserId,userId).then((function(profile){var newState=StateManager.addMembers(viewState,[profile]);return newState=StateManager.removePendingUnblockUsersById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_UNBLOCKED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestRemoveContact=function(userId){cancelRequest(userId);var newState=StateManager.addPendingRemoveContactsById(viewState,[userId]);render(newState)},removeContact=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:removeContact");return render(newState),Repository.deleteContacts(viewState.loggedInUserId,[userId]).then((function(profiles){var newState=StateManager.addMembers(viewState,profiles);return newState=StateManager.removePendingRemoveContactsById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_REMOVED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestAddContact=function(userId){cancelRequest(userId);var newState=StateManager.addPendingAddContactsById(viewState,[userId]);render(newState)},addContact=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:addContactRequests");return render(newState),Repository.createContactRequest(viewState.loggedInUserId,userId).then((function(response){if(!response.request)throw new Error(response.warnings[0].message);return response.request})).then((function(request){var newState=StateManager.removePendingAddContactsById(viewState,[userId]);return newState=StateManager.addContactRequests(newState,[request]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestDeleteSelectedMessages=function(userId){var selectedMessageIds=viewState.selectedMessageIds;cancelRequest(userId);var newState=StateManager.addPendingDeleteMessagesById(viewState,selectedMessageIds);render(newState)},deleteSelectedMessages=function(){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:deleteSelectedMessages"),messageIds=viewState.pendingDeleteMessageIds,sentMessages=viewState.messages.filter((function(message){return messageIds.indexOf(message.id)>=0&&("sent"==message.sendState||null===message.sendState)})),newState=StateManager.setLoadingConfirmAction(viewState,!0);render(newState);var deleteMessagesPromise=$.Deferred().resolve().promise();if(sentMessages.length){var sentMessageIds=sentMessages.map((function(message){return message.id}));deleteMessagesPromise=newState.deleteMessagesForAllUsers?Repository.deleteMessagesForAllUsers(viewState.loggedInUserId,sentMessageIds):Repository.deleteMessages(viewState.loggedInUserId,sentMessageIds)}return isDeletingConversationContent=!0,newMessagesPollTimer&&newMessagesPollTimer.stop(),deleteMessagesPromise.then((function(){var newState=StateManager.removeMessagesById(viewState,messageIds);newState=StateManager.removePendingDeleteMessagesById(newState,messageIds),newState=StateManager.removeSelectedMessagesById(newState,messageIds),newState=StateManager.setLoadingConfirmAction(newState,!1),newState=StateManager.setDeleteMessagesForAllUsers(newState,!1);var prevLastMessage=viewState.messages[viewState.messages.length-1],newLastMessage=newState.messages.length?newState.messages[newState.messages.length-1]:null;if(newLastMessage&&newLastMessage.id!=prevLastMessage.id){var conversation=formatConversationForEvent(newState);PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation)}else newState.messages.length||PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED,newState.id);return isDeletingConversationContent=!1,render(newState)})).then((function(result){return pendingPromise.resolve(),result})).catch(Notification.exception)},requestDeleteConversation=function(userId){cancelRequest(userId);var newState=StateManager.setPendingDeleteConversation(viewState,!0);render(newState)},deleteConversation=function(){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead"),newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),isDeletingConversationContent=!0,newMessagesPollTimer&&newMessagesPollTimer.stop(),Repository.deleteConversation(viewState.loggedInUserId,viewState.id).then((function(){var newState=StateManager.removeMessages(viewState,viewState.messages);return newState=StateManager.removeSelectedMessagesById(newState,viewState.selectedMessageIds),newState=StateManager.setPendingDeleteConversation(newState,!1),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED,newState.id),isDeletingConversationContent=!1,render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},cancelRequest=function(userId){var pendingDeleteMessageIds=viewState.pendingDeleteMessageIds,newState=StateManager.removePendingAddContactsById(viewState,[userId]);newState=StateManager.removePendingRemoveContactsById(newState,[userId]),newState=StateManager.removePendingUnblockUsersById(newState,[userId]),newState=StateManager.removePendingBlockUsersById(newState,[userId]),newState=StateManager.removePendingDeleteMessagesById(newState,pendingDeleteMessageIds),newState=StateManager.setPendingDeleteConversation(newState,!1),newState=StateManager.setDeleteMessagesForAllUsers(newState,!1),render(newState)},acceptContactRequest=function(userId){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:acceptContactRequest"),loggedInUserId=viewState.loggedInUserId,requests=viewState.members[userId].contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId})),request=requests[0],newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),Repository.acceptContactRequest(userId,loggedInUserId).then((function(profile){var newState=StateManager.removeContactRequests(viewState,[request]);return newState=StateManager.addMembers(viewState,[profile]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(){PubSub.publish(MessageDrawerEvents.CONTACT_ADDED,viewState.members[userId]),PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,request)})).then((function(result){return pendingPromise.resolve(),result}))},declineContactRequest=function(userId){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:declineContactRequest"),loggedInUserId=viewState.loggedInUserId,requests=viewState.members[userId].contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId})),request=requests[0],newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),Repository.declineContactRequest(userId,loggedInUserId).then((function(profile){var newState=StateManager.removeContactRequests(viewState,[request]);return newState=StateManager.addMembers(viewState,[profile]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(){PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,request)})).then((function(result){return pendingPromise.resolve(),result}))},processSendMessageBuffer=function(){if(!isSendingMessage&&sendMessageBuffer.length){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:processSendMessageBuffer");isSendingMessage=!0;var messagesToSend=sendMessageBuffer.slice();sendMessageBuffer=[];var conversationId=viewState.id,newConversationId=null,messagesText=messagesToSend.map((function(message){return message.text})),messageIds=messagesToSend.map((function(message){return message.id})),sendMessagePromise=null,newCanDeleteMessagesForAllUsers=null;if(conversationId||viewState.type==CONVERSATION_TYPES.PUBLIC)sendMessagePromise=Repository.sendMessagesToConversation(conversationId,messagesText);else{var otherUserId=getOtherUserId();sendMessagePromise=Repository.sendMessagesToUser(otherUserId,messagesText).then((function(messages){return messages.length&&(newConversationId=parseInt(messages[0].conversationid,10),newCanDeleteMessagesForAllUsers=messages[0].candeletemessagesforallusers),messages}))}sendMessagePromise.then((function(messages){var newMessageIds=messages.map((function(message){return message.id})),data=[],selectedToRemove=[],selectedToAdd=[];messagesToSend.forEach((function(oldMessage,index){var newMessage=messages[index];data.push([oldMessage,newMessage]),viewState.selectedMessageIds.indexOf(oldMessage.id)>=0&&(selectedToRemove.push(oldMessage.id),selectedToAdd.push(newMessage.id))}));var newState=StateManager.updateMessages(viewState,data);newState=StateManager.setMessagesSendSuccessById(newState,newMessageIds),selectedToRemove.length&&(newState=StateManager.removeSelectedMessagesById(newState,selectedToRemove)),selectedToAdd.length&&(newState=StateManager.addSelectedMessagesById(newState,selectedToAdd));var conversation=formatConversationForEvent(newState);newState.id||(newState=StateManager.setId(newState,newConversationId),conversation.id=newConversationId,resetMessagePollTimer(newConversationId),PubSub.publish(MessageDrawerEvents.CONVERSATION_CREATED,conversation),newState=StateManager.setCanDeleteMessagesForAllUsers(newState,newCanDeleteMessagesForAllUsers)),render(newState),isSendingMessage=!1,processSendMessageBuffer(),PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation)})).then((function(result){return pendingPromise.resolve(),result})).catch((function(e){var errorMessage;errorMessage=e.message?$.Deferred().resolve(e.message).promise():Str.get_string("unknownerror","core");var handleFailedMessages=function(errorMessage){var newState=StateManager.setMessagesSendFailById(viewState,messageIds,errorMessage);render(newState),isSendingMessage=!1,processSendMessageBuffer()};errorMessage.then(handleFailedMessages).then((function(result){return pendingPromise.resolve(),result})).catch((function(e){var finalError=e.message||"Something went wrong!";handleFailedMessages(finalError)}))}))}};const previewText=function(text){let plaintext=text.replace(/<style([\s\S]*?)<\/style>/gi,"");return plaintext=plaintext.replace(/<script([\s\S]*?)<\/script>/gi,""),plaintext=plaintext.replace(/<\/div>/gi,"\n"),plaintext=plaintext.replace(/<\/li>/gi,"\n"),plaintext=plaintext.replace(/<li>/gi," * "),plaintext=plaintext.replace(/<\/ul>/gi,"\n"),plaintext=plaintext.replace(/<\/p>/gi,"\n"),plaintext=plaintext.replace(/<br[^>]*>/gi,"\n"),plaintext=plaintext.replace(/<[^>]+>/gi,""),plaintext=plaintext.replace(/\n+/gi,"\n"),plaintext.replace(/\n/gi,"<br>")};var processRenderBuffer=function(header,body,footer){if(!isRendering&&renderBuffer.length){isRendering=!0;var renderable=renderBuffer.shift(),renderPromises=renderers.map((function(renderFunc){return renderFunc(renderable.patch)}));$.when.apply(null,renderPromises).then((function(){isRendering=!1,renderable.deferred.resolve(!0),processRenderBuffer(header,body,footer)})).catch((function(error){isRendering=!1,renderable.deferred.reject(error),Notification.exception(error)}))}},generateConfirmActionHandler=function(actionCallback){return function(e,data){if(!viewState.loadingConfirmAction){actionCallback(getOtherUserId());var newState=StateManager.setLoadingConfirmAction(viewState,!1);render(newState)}data.originalEvent.preventDefault()}},handleSendMessage=function(e,data){var textArea=$(e.target).closest(SELECTORS.FOOTER_CONTAINER).find(SELECTORS.MESSAGE_TEXT_AREA),text=textArea.val().trim();""!==text&&(!function(text){var id="temp"+Date.now();let loadingmessage={id:id,useridfrom:viewState.loggedInUserId,text:previewText(text),timecreated:null};var newState=StateManager.addMessages(viewState,[loadingmessage]);render(newState);var message={id:id,useridfrom:viewState.loggedInUserId,text:text,timecreated:null};sendMessageBuffer.push(message),processSendMessageBuffer()}(text),textArea.val(""),textArea.focus()),data.originalEvent.preventDefault()},handleSelectMessage=function(e,data){var selection=window.getSelection(),target=$(e.target);""==selection.toString()&&(target.is("a")||(!function(messageId){var newState=viewState;newState=viewState.selectedMessageIds.indexOf(messageId)>-1?StateManager.removeSelectedMessagesById(viewState,[messageId]):StateManager.addSelectedMessagesById(viewState,[messageId]),render(newState)}(target.closest(SELECTORS.MESSAGE).attr("data-message-id")),data.originalEvent.preventDefault()))},handleRetrySendMessage=function(e,data){var messageId=$(e.target).closest(SELECTORS.MESSAGE).attr("data-message-id"),messages=viewState.messages.filter((function(message){return message.id==messageId})),message=messages.length?messages[0]:null;message&&function(message){var newState=StateManager.setMessagesSendPendingById(viewState,[message.id]);render(newState),sendMessageBuffer.push(message),processSendMessageBuffer()}(message),data.originalEvent.preventDefault(),data.originalEvent.stopPropagation(),e.stopPropagation()},handleCancelEditMode=function(e,data){!function(){cancelRequest(getOtherUserId());var newState=StateManager.removeSelectedMessagesById(viewState,viewState.selectedMessageIds);render(newState)}(),data.originalEvent.preventDefault()},generateHandleViewContact=function(namespace){return function(e,data){var otherUserId=getOtherUserId(),otherUser=viewState.members[otherUserId];MessageDrawerRouter.go(namespace,MessageDrawerRoutes.VIEW_CONTACT,otherUser),data.originalEvent.preventDefault()}},handleSetFavourite=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:setFavourite"),Repository.setFavouriteConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsFavourite(viewState,!0);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_SET_FAVOURITE,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleUnsetFavourite=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:unsetFavourite"),Repository.unsetFavouriteConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsFavourite(viewState,!1);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_UNSET_FAVOURITE,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleSetMuted=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead"),Repository.setMutedConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsMuted(viewState,!0);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_SET_MUTED,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleUnsetMuted=function(e,data){var userId,conversationId;(userId=viewState.loggedInUserId,conversationId=viewState.id,Repository.unsetMutedConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsMuted(viewState,!1);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_UNSET_MUTED,formatConversationForEvent(viewState))}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleDeleteMessagesForAllUsersToggle=function(e){var newValue=$(e.target).prop("checked"),newState=StateManager.setDeleteMessagesForAllUsers(viewState,newValue);render(newState)},generateHandleViewGroupInfo=function(namespace){return function(e,data){MessageDrawerRouter.go(namespace,MessageDrawerRoutes.VIEW_GROUP_INFO,{id:viewState.id,name:viewState.name,subname:viewState.subname,imageUrl:viewState.imageUrl,totalMemberCount:viewState.totalMemberCount},viewState.loggedInUserId),data.originalEvent.preventDefault()}},handleToggleEmojiPicker=function(e,data){var newState=StateManager.setShowEmojiPicker(viewState,!viewState.showEmojiPicker);render(newState),data.originalEvent.preventDefault()},handleCloseEmojiPicker=function(e){var target=$(e.target);if(viewState.showEmojiPicker&&!target.closest(SELECTORS.EMOJI_PICKER_CONTAINER).length&&!target.closest(SELECTORS.TOGGLE_EMOJI_PICKER_BUTTON).length){var newState=StateManager.setShowEmojiPicker(viewState,!1);render(newState)}},registerEventListeners=function(namespace,header,body,footer){var isLoadingMoreMessages=!1,messagesContainer=function(body){return body.find(SELECTORS.MESSAGES_CONTAINER)}(body),emojiPickerElement=footer.find(SELECTORS.EMOJI_PICKER),emojiAutoCompleteContainer=footer.find(SELECTORS.EMOJI_AUTO_COMPLETE_CONTAINER),messageTextArea=footer.find(SELECTORS.MESSAGE_TEXT_AREA),headerActivateHandlers=[[SELECTORS.ACTION_REQUEST_BLOCK,generateConfirmActionHandler(requestBlockUser)],[SELECTORS.ACTION_REQUEST_UNBLOCK,generateConfirmActionHandler(requestUnblockUser)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_REQUEST_REMOVE_CONTACT,generateConfirmActionHandler(requestRemoveContact)],[SELECTORS.ACTION_REQUEST_DELETE_CONVERSATION,generateConfirmActionHandler(requestDeleteConversation)],[SELECTORS.ACTION_CANCEL_EDIT_MODE,handleCancelEditMode],[SELECTORS.ACTION_VIEW_CONTACT,generateHandleViewContact(namespace)],[SELECTORS.ACTION_VIEW_GROUP_INFO,generateHandleViewGroupInfo(namespace)],[SELECTORS.ACTION_CONFIRM_FAVOURITE,handleSetFavourite],[SELECTORS.ACTION_CONFIRM_MUTE,handleSetMuted],[SELECTORS.ACTION_CONFIRM_UNFAVOURITE,handleUnsetFavourite],[SELECTORS.ACTION_CONFIRM_UNMUTE,handleUnsetMuted]],bodyActivateHandlers=[[SELECTORS.ACTION_CANCEL_CONFIRM,generateConfirmActionHandler(cancelRequest)],[SELECTORS.ACTION_CONFIRM_BLOCK,generateConfirmActionHandler(blockUser)],[SELECTORS.ACTION_CONFIRM_UNBLOCK,generateConfirmActionHandler(unblockUser)],[SELECTORS.ACTION_CONFIRM_ADD_CONTACT,generateConfirmActionHandler(addContact)],[SELECTORS.ACTION_CONFIRM_REMOVE_CONTACT,generateConfirmActionHandler(removeContact)],[SELECTORS.ACTION_CONFIRM_DELETE_SELECTED_MESSAGES,generateConfirmActionHandler(deleteSelectedMessages)],[SELECTORS.ACTION_CONFIRM_DELETE_CONVERSATION,generateConfirmActionHandler(deleteConversation)],[SELECTORS.ACTION_OKAY_CONFIRM,generateConfirmActionHandler(cancelRequest)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_ACCEPT_CONTACT_REQUEST,generateConfirmActionHandler(acceptContactRequest)],[SELECTORS.ACTION_DECLINE_CONTACT_REQUEST,generateConfirmActionHandler(declineContactRequest)],[SELECTORS.MESSAGE,handleSelectMessage],[SELECTORS.DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE,handleDeleteMessagesForAllUsersToggle],[SELECTORS.RETRY_SEND,handleRetrySendMessage]],footerActivateHandlers=[[SELECTORS.SEND_MESSAGE_BUTTON,handleSendMessage],[SELECTORS.TOGGLE_EMOJI_PICKER_BUTTON,handleToggleEmojiPicker],[SELECTORS.ACTION_REQUEST_DELETE_SELECTED_MESSAGES,generateConfirmActionHandler(requestDeleteSelectedMessages)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_REQUEST_UNBLOCK,generateConfirmActionHandler(requestUnblockUser)]];AutoRows.init(footer),emojiAutoCompleteContainer.length&&initialiseEmojiAutoComplete(emojiAutoCompleteContainer[0],messageTextArea[0],(function(hasSuggestions){var newState=StateManager.setShowEmojiAutoComplete(viewState,hasSuggestions);render(newState)}),(function(emoji){var newState=StateManager.setShowEmojiAutoComplete(viewState,!1);render(newState),messageTextArea.focus();var cursorPos=messageTextArea.prop("selectionStart"),currentText=messageTextArea.val(),textBefore=currentText.substring(0,cursorPos).replace(/\S*$/,""),textAfter=currentText.substring(cursorPos).replace(/^\S*/,"");messageTextArea.val(textBefore+emoji+textAfter),messageTextArea.prop("selectionStart",textBefore.length+emoji.length),messageTextArea.prop("selectionEnd",textBefore.length+emoji.length)})),emojiPickerElement.length&&initialiseEmojiPicker(emojiPickerElement[0],(function(emoji){var newState=StateManager.setShowEmojiPicker(viewState,!viewState.showEmojiPicker);render(newState),messageTextArea.focus();var cursorPos=messageTextArea.prop("selectionStart"),currentText=messageTextArea.val(),textBefore=currentText.substring(0,cursorPos),textAfter=currentText.substring(cursorPos,currentText.length);messageTextArea.val(textBefore+emoji+textAfter),messageTextArea.prop("selectionStart",cursorPos+emoji.length),messageTextArea.prop("selectionEnd",cursorPos+emoji.length)})),CustomEvents.define(header,[CustomEvents.events.activate]),CustomEvents.define(body,[CustomEvents.events.activate]),CustomEvents.define(footer,[CustomEvents.events.activate,CustomEvents.events.enter,CustomEvents.events.escape]),CustomEvents.define(messagesContainer,[CustomEvents.events.scrollTop,CustomEvents.events.scrollLock]),messagesContainer.on(CustomEvents.events.scrollTop,(function(e,data){var hasMembers=Object.keys(viewState.members).length>1;if(!isResetting&&!isLoadingMoreMessages&&!hasLoadedAllMessages()&&hasMembers){isLoadingMoreMessages=!0;var newState=StateManager.setLoadingMessages(viewState,!0);render(newState),loadMessages(viewState.id,LOAD_MESSAGE_LIMIT,getMessagesOffset(),NEWEST_FIRST,[]).then((function(){isLoadingMoreMessages=!1,setMessagesOffset(getMessagesOffset()+LOAD_MESSAGE_LIMIT)})).catch((function(error){isLoadingMoreMessages=!1,Notification.exception(error)}))}data.originalEvent.preventDefault()})),headerActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];header.on(CustomEvents.events.activate,selector,handlerFunction)})),bodyActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];body.on(CustomEvents.events.activate,selector,handlerFunction)})),footerActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];footer.on(CustomEvents.events.activate,selector,handlerFunction)})),footer.on(CustomEvents.events.enter,SELECTORS.MESSAGE_TEXT_AREA,(function(e,data){var enterToSend=footer.attr("data-enter-to-send");enterToSend&&"false"!=enterToSend&&"0"!=enterToSend&&handleSendMessage(e,data)})),footer.on(CustomEvents.events.escape,SELECTORS.EMOJI_PICKER_CONTAINER,handleToggleEmojiPicker),$(document.body).on("click",handleCloseEmojiPicker),PubSub.subscribe(MessageDrawerEvents.ROUTE_CHANGED,(function(newRouteData){newMessagesPollTimer&&newRouteData.route!=MessageDrawerRoutes.VIEW_CONVERSATION&&newMessagesPollTimer.stop()}))},resetMessagePollTimer=function(conversationId){newMessagesPollTimer&&newMessagesPollTimer.stop(),newMessagesPollTimer=new BackOffTimer(function(conversationId,newestFirst){return function(){var messages=viewState.messages,mostRecentMessage=messages.length?messages[messages.length-1]:null,lastTimeCreated=mostRecentMessage?mostRecentMessage.timeCreated:null;if(lastTimeCreated&&!isResetting&&!isSendingMessage&&!isDeletingConversationContent){for(var ignoreMessageIds=[],i=messages.length-1;i>=0;i--){var message=messages[i];if(message.timeCreated!==lastTimeCreated)break;ignoreMessageIds.push(message.id)}return loadMessages(conversationId,0,0,newestFirst,ignoreMessageIds,lastTimeCreated).then((function(result){if(result.messages.length){newMessagesPollTimer.restart();var conversation=formatConversationForEvent(viewState);return PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation),markConversationAsRead(conversationId)}return result}))}return $.Deferred().resolve().promise()}}(conversationId,NEWEST_FIRST),BackOffTimer.getIncrementalCallback(viewState.messagePollMin*MILLISECONDS_IN_SEC,MILLISECONDS_IN_SEC,viewState.messagePollMax*MILLISECONDS_IN_SEC,viewState.messagePollAfterMax*MILLISECONDS_IN_SEC)),newMessagesPollTimer.start()},resetState=function(body,conversationId,loggedInUserProfile){newMessagesPollTimer&&newMessagesPollTimer.stop(),loadedAllMessages=!1,messagesOffset=0,newMessagesPollTimer=null,isRendering=!1,renderBuffer=[],isResetting=!0,isSendingMessage=!1,isDeletingConversationContent=!1,sendMessageBuffer=[];var loggedInUserId=loggedInUserProfile.id,midnight=parseInt(body.attr("data-midnight"),10),messagePollMin=parseInt(body.attr("data-message-poll-min"),10),messagePollMax=parseInt(body.attr("data-message-poll-max"),10),messagePollAfterMax=parseInt(body.attr("data-message-poll-after-max"),10),initialState=StateManager.buildInitialState(midnight,loggedInUserId,conversationId,messagePollMin,messagePollMax,messagePollAfterMax);viewState||(viewState=initialState),render(initialState)},resetNoConversation=function(body,loggedInUserProfile,otherUserId){resetState(body,null,loggedInUserProfile);return(loggedInUserProfile.id!=otherUserId?Repository.getConversationBetweenUsers(loggedInUserProfile.id,otherUserId,!0,!0,0,0,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST):Repository.getSelfConversation(loggedInUserProfile.id,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST)).then((function(conversation){return resetByConversation(body,conversation,loggedInUserProfile)})).catch((function(){return function(loggedInUserProfile,otherUserId){var loggedInUserId=loggedInUserProfile.id,conversationType=loggedInUserId==otherUserId?CONVERSATION_TYPES.SELF:CONVERSATION_TYPES.PRIVATE,newState=StateManager.setLoadingMembers(viewState,!0);return newState=StateManager.setLoadingMessages(newState,!0),render(newState),Repository.getMemberInfo(loggedInUserId,[otherUserId],!0,!0).then((function(profiles){if(profiles.length)return profiles[0];throw new Error("Unable to load other user profile")})).then((function(profile){var members=conversationType==CONVERSATION_TYPES.SELF?[profile]:[profile,loggedInUserProfile],newState=StateManager.addMembers(viewState,members);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setName(newState,profile.fullname),newState=StateManager.setType(newState,conversationType),newState=StateManager.setImageUrl(newState,profile.profileimageurl),newState=StateManager.setTotalMemberCount(newState,members.length),render(newState),profile})).catch((function(error){var newState=StateManager.setLoadingMembers(viewState,!1);render(newState),Notification.exception(error)}))}(loggedInUserProfile,otherUserId)}))},resetById=function(body,conversationId,loggedInUserProfile){var cache=null;conversationId in stateCache&&(cache=stateCache[conversationId]),resetState(body,conversationId,loggedInUserProfile);var promise=$.Deferred().resolve({}).promise();if(cache){var newState=cache.state;newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setLoadingMembers(newState,!1),setMessagesOffset(cache.messagesOffset),setLoadedAllMessages(cache.loadedAllMessages),render(newState)}else promise=function(conversationId,loggedInUserProfile,messageLimit,messageOffset,newestFirst){var loggedInUserId=loggedInUserProfile.id,newState=StateManager.setLoadingMembers(viewState,!0);return newState=StateManager.setLoadingMessages(newState,!0),render(newState),Repository.getConversation(loggedInUserId,conversationId,!0,!0,0,0,messageLimit+1,messageOffset,newestFirst).then((function(conversation){return conversation.messages.length>messageLimit?conversation.messages=conversation.messages.slice(1):setLoadedAllMessages(!0),setMessagesOffset(messageOffset+messageLimit),conversation})).then((function(conversation){conversation.members.filter((function(member){return member.id==loggedInUserProfile.id})).length<1&&(conversation.members=conversation.members.concat([loggedInUserProfile]));var newState=updateStateFromConversation(conversation,loggedInUserProfile.id);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!1),render(newState).then((function(){return conversation}))})).then((function(){return markConversationAsRead(conversationId)})).catch((function(error){var newState=StateManager.setLoadingMembers(viewState,!1);newState=StateManager.setLoadingMessages(newState,!1),render(newState),Notification.exception(error)}))}(conversationId,loggedInUserProfile,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST);return promise.then((function(){return resetMessagePollTimer(conversationId)}))},resetByConversation=function(body,conversation,loggedInUserProfile){var cache=null;conversation.id in stateCache&&(cache=stateCache[conversation.id]),resetState(body,conversation.id,loggedInUserProfile);var promise=$.Deferred().resolve({}).promise();if(cache){var newState=cache.state;newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setLoadingMembers(newState,!1),setMessagesOffset(cache.messagesOffset),setLoadedAllMessages(cache.loadedAllMessages),render(newState)}else promise=function(conversation,loggedInUserProfile,messageLimit,newestFirst){conversation.members.filter((function(member){return member.id==loggedInUserProfile.id})).length<1&&(conversation.members=conversation.members.concat([loggedInUserProfile]));var messageCount=conversation.messages.length,hasLoadedEnoughMessages=messageCount>=messageLimit,newState=updateStateFromConversation(conversation,loggedInUserProfile.id);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!hasLoadedEnoughMessages),render(newState).then((function(){return hasLoadedEnoughMessages?{messages:conversation.messages}:loadMessages(conversation.id,messageLimit,messageCount,newestFirst,[])})).then((function(){var messages=viewState.messages;return setMessagesOffset(messages.length),markConversationAsRead(viewState.id),messages})).catch(Notification.exception)}(conversation,loggedInUserProfile,LOAD_MESSAGE_LIMIT,NEWEST_FIRST);return promise.then((function(){return resetMessagePollTimer(conversation.id)}))};return{show:function(namespace,header,body,footer,conversationOrId,action,otherUserId){var userId,conversation=null,conversationId=null;conversationOrId&&null!==conversationOrId&&"object"==typeof conversationOrId?(conversation=conversationOrId,conversationId=parseInt(conversation.id,10)):(conversation=null,conversationId=parseInt(conversationOrId,10),conversationId=isNaN(conversationId)?null:conversationId),!conversationId&&action&&otherUserId&&(userId=otherUserId,conversationId=Object.keys(stateCache).reduce((function(carry,id){if(!carry){var state=stateCache[id].state;state.type!=CONVERSATION_TYPES.PUBLIC&&userId in state.members&&(carry=state.id)}return carry}),null));var isNewConversation=!viewState||viewState.id!=conversationId||otherUserId&&otherUserId!=getOtherUserId();if(body.attr("data-init")||(render=function(header,body,footer,isNewConversation){var rendererFunc=function(patch){return Renderer.render(header,body,footer,patch)};if(!isNewConversation){var initialState=StateManager.buildInitialState(viewState.midnight,viewState.loggedInUserId,viewState.id);rendererFunc(Patcher.buildPatch(initialState,viewState))}return renderers.push(rendererFunc),function(newState){var patch=Patcher.buildPatch(viewState,newState),deferred=$.Deferred();return Object.keys(patch).length?renderBuffer.push({patch:patch,deferred:deferred}):deferred.resolve(!0),viewState=newState,newState.id&&(stateCache[newState.id]={state:newState,messagesOffset:getMessagesOffset(),loadedAllMessages:hasLoadedAllMessages()}),processRenderBuffer(header,body,footer),deferred.promise()}}(header,body,footer,isNewConversation),registerEventListeners(namespace,header,body,footer),body.attr("data-init",!0)),isNewConversation){var loggedInUserProfile=function(body){return{id:parseInt(body.attr("data-user-id"),10),fullname:null,profileimageurl:null,profileimageurlsmall:null,isonline:null,showonlinestatus:null,isblocked:null,iscontact:null,isdeleted:null,canmessage:null,canmessageevenifblocked:null,requirescontact:null,contactrequests:[]}}(body);return(conversation?resetByConversation(body,conversation,loggedInUserProfile,otherUserId):conversationId?resetById(body,conversationId,loggedInUserProfile):resetNoConversation(body,loggedInUserProfile,otherUserId)).then((function(){isResetting=!1,header.find(Constants.SELECTORS.CAN_RECEIVE_FOCUS).first().focus()})).catch((function(error){isResetting=!1,Notification.exception(error)}))}if(resetMessagePollTimer(conversationId),viewState.type==CONVERSATION_TYPES.PRIVATE&&action){var currentOtherUserId=getOtherUserId();switch(action){case"block":return requestBlockUser(currentOtherUserId);case"unblock":return requestUnblockUser(currentOtherUserId);case"add-contact":return requestAddContact(currentOtherUserId);case"remove-contact":return requestRemoveContact(currentOtherUserId)}}return $.Deferred().resolve().promise()},description:function(){return Str.get_string("messagedrawerviewconversation","core_message",viewState.name)}}})); /** * Constant values for the conversation page in the message drawer. * * @module core_message/message_drawer_view_conversation_constants * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_conversation_constants",[],(function(){return{SELECTORS:{ACTION_ACCEPT_CONTACT_REQUEST:'[data-action="accept-contact-request"]',ACTION_CANCEL_CONFIRM:'[data-action="cancel-confirm"]',ACTION_OKAY_CONFIRM:'[data-action="okay-confirm"]',ACTION_CANCEL_EDIT_MODE:'[data-action="cancel-edit-mode"]',ACTION_CONFIRM_ADD_CONTACT:'[data-action="confirm-add-contact"]',ACTION_CONFIRM_BLOCK:'[data-action="confirm-block"]',ACTION_CONFIRM_DELETE_SELECTED_MESSAGES:'[data-action="confirm-delete-selected-messages"]',ACTION_CONFIRM_DELETE_CONVERSATION:'[data-action="confirm-delete-conversation"]',ACTION_CONFIRM_FAVOURITE:'[data-action="confirm-favourite"]',ACTION_CONFIRM_MUTE:'[data-action="confirm-mute"]',ACTION_CONFIRM_UNFAVOURITE:'[data-action="confirm-unfavourite"]',ACTION_CONFIRM_REMOVE_CONTACT:'[data-action="confirm-remove-contact"]',ACTION_CONFIRM_UNBLOCK:'[data-action="confirm-unblock"]',ACTION_CONFIRM_UNMUTE:'[data-action="confirm-unmute"]',ACTION_DECLINE_CONTACT_REQUEST:'[data-action="decline-contact-request"]',ACTION_REQUEST_ADD_CONTACT:'[data-action="request-add-contact"]',ACTION_REQUEST_BLOCK:'[data-action="request-block"]',ACTION_REQUEST_DELETE_CONVERSATION:'[data-action="request-delete-conversation"]',ACTION_REQUEST_DELETE_SELECTED_MESSAGES:'[data-action="delete-selected-messages"]',ACTION_REQUEST_REMOVE_CONTACT:'[data-action="request-remove-contact"]',ACTION_REQUEST_UNBLOCK:'[data-action="request-unblock"]',ACTION_VIEW_CONTACT:'[data-action="view-contact"]',ACTION_VIEW_GROUP_INFO:'[data-action="view-group-info"]',CAN_RECEIVE_FOCUS:'input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',CONFIRM_DIALOGUE:'[data-region="confirm-dialogue"]',CONFIRM_DIALOGUE_BUTTON_TEXT:'[data-region="dialogue-button-text"]',CONFIRM_DIALOGUE_CANCEL_BUTTON:'[data-action="cancel-confirm"]',CONFIRM_DIALOGUE_CONTAINER:'[data-region="confirm-dialogue-container"]',CONFIRM_DIALOGUE_HEADER:'[data-region="dialogue-header"]',CONFIRM_DIALOGUE_OKAY_BUTTON:'[data-action="okay-confirm"]',CONFIRM_DIALOGUE_TEXT:'[data-region="dialogue-text"]',CONTACT_REQUEST_SENT_MESSAGE_CONTAINER:'[data-region="contact-request-sent-message-container"]',CONTENT_PLACEHOLDER_CONTAINER:'[data-region="content-placeholder"]',CONTENT_CONTAINER:'[data-region="content-container"]',CONTENT_MESSAGES_CONTAINER:'[data-region="content-message-container"]',CONTENT_MESSAGES_FOOTER_CONTAINER:'[data-region="content-messages-footer-container"]',CONTENT_MESSAGES_FOOTER_EDIT_MODE_CONTAINER:'[data-region="content-messages-footer-edit-mode-container"]',CONTENT_MESSAGES_FOOTER_REQUIRE_CONTACT_CONTAINER:'[data-region="content-messages-footer-require-contact-container"]',CONTENT_MESSAGES_FOOTER_REQUIRE_UNBLOCK_CONTAINER:'[data-region="content-messages-footer-require-unblock-container"]',CONTENT_MESSAGES_FOOTER_UNABLE_TO_MESSAGE_CONTAINER:'[data-region="content-messages-footer-unable-to-message"]',DAY_MESSAGES_CONTAINER:'[data-region="day-messages-container"]',DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE:'[data-region="delete-messages-for-all-users-toggle"]',DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE_CONTAINER:'[data-region="delete-messages-for-all-users-toggle-container"]',EMOJI_AUTO_COMPLETE_CONTAINER:'[data-region="emoji-auto-complete-container"]',EMOJI_PICKER_CONTAINER:'[data-region="emoji-picker-container"]',EMOJI_PICKER:'[data-region="emoji-picker"]',EMOJI_PICKER_SEARCH_INPUT:'[data-region="search-input"]',ERROR_MESSAGE_CONTAINER:'[data-region="error-message-container"]',ERROR_MESSAGE:'[data-region="error-message"]',FAVOURITE_ICON_CONTAINER:'[data-region="favourite-icon-container"]',FOOTER_CONTAINER:'[data-region="content-messages-footer-container"]',HEADER:'[data-region="header-content"]',HEADER_EDIT_MODE:'[data-region="header-edit-mode"]',HEADER_PLACEHOLDER_CONTAINER:'[data-region="header-placeholder"]',LOADING_ICON_CONTAINER:'[data-region="loading-icon-container"]',MESSAGE:'[data-region="message"]',MESSAGE_NOT_SELECTED:'[data-region="message"][aria-checked="false"]',MESSAGE_NOT_SELECTED_ICON:'[data-region="not-selected-icon"]',MESSAGE_SELECTED_ICON:'[data-region="selected-icon"]',MESSAGES:'[data-region="content-message-container"]',MESSAGES_CONTAINER:'[data-region="content-message-container"]',MESSAGES_SELECTED_COUNT:'[data-region="message-selected-court"]',MESSAGE_TEXT_AREA:'[data-region="send-message-txt"]',MORE_MESSAGES_LOADING_ICON_CONTAINER:'[data-region="more-messages-loading-icon-container"]',MUTED_ICON_CONTAINER:'[data-region="muted-icon-container"]',PLACEHOLDER_CONTAINER:'[data-region="placeholder-container"]',RETRY_SEND:'[data-region="retry-send"]',SELF_CONVERSATION_MESSAGE_CONTAINER:'[data-region="self-conversation-message-container"]',SEND_MESSAGE_BUTTON:'[data-action="send-message"]',SEND_MESSAGE_ICON_CONTAINER:'[data-region="send-icon-container"]',TEXT:'[data-region="text"]',TEXT_CONTAINER:'[data-region="text-container"]',TIME_CREATED:'[data-region="time-created"]',TITLE:'[data-region="title"]',TOGGLE_EMOJI_PICKER_BUTTON:'[data-action="toggle-emoji-picker"]'},TEMPLATES:{HEADER_PRIVATE:"core_message/message_drawer_view_conversation_header_content_type_private",HEADER_PRIVATE_NO_CONTROLS:"core_message/message_drawer_view_conversation_header_content_type_private_no_controls",HEADER_PUBLIC:"core_message/message_drawer_view_conversation_header_content_type_public",HEADER_SELF:"core_message/message_drawer_view_conversation_header_content_type_self",DAY:"core_message/message_drawer_view_conversation_body_day",MESSAGE:"core_message/message_drawer_view_conversation_body_message",MESSAGES:"core_message/message_drawer_view_conversation_body_messages"},CONVERSATION_TYPES:{PRIVATE:1,PUBLIC:2,SELF:3},NEWEST_MESSAGES_FIRST:!0,LOAD_MESSAGE_LIMIT:100,MILLISECONDS_IN_SEC:1e3}})); /** * This module will take 2 view states from the message_drawer_view_conversation * module and generate a patch that can be given to the * message_drawer_view_conversation_renderer module to update the UI. * * This module should never modify either state. It's purely a read only * module. * * @module core_message/message_drawer_view_conversation_patcher * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_conversation_patcher",["jquery","core/user_date","core_message/message_drawer_view_conversation_constants"],(function($,UserDate,Constants){var sortMessagesByDay=function(messages,midnight){var messagesByDay=messages.reduce((function(carry,message){var timeCreated=message.timeCreated?message.timeCreated:midnight,dayTimestamp=UserDate.getUserMidnightForTimestamp(timeCreated,midnight);return carry.hasOwnProperty(dayTimestamp)?carry[dayTimestamp].push(message):carry[dayTimestamp]=[message],carry}),{});return Object.keys(messagesByDay).map((function(dayTimestamp){return{timestamp:dayTimestamp,messages:messagesByDay[dayTimestamp]}}))},diffArrays=function(a,b,matchFunction){b=b.slice();var missingFromB=[],matches=[];return a.forEach((function(current){for(var found=!1,index=0;index<b.length;index++){var next=b[index];if(matchFunction(current,next)){found=!0,matches.push({a:current,b:next});break}}found?b.splice(index,1):missingFromB.push(current)})),{missingFromA:b,missingFromB:missingFromB,matches:matches}},findPositionInArray=function(array,breakFunction){for(var i=0;i<array.length;i++){var candidate=array[i];if(breakFunction(candidate))return candidate}return null},isArrayEqual=function(a,b){a=a.slice(),b=b.slice(),a.sort(),b.sort();var aLength=a.length,bLength=b.length;return aLength<1&&bLength<1||aLength==bLength&&a.every((function(item,index){return item==b[index]}))},isObjectEqual=function(a,b){var aKeys=Object.keys(a),bKeys=Object.keys(b);return aKeys.length==bKeys.length&&aKeys.every((function(key){var aVal=a[key],bVal=b[key],aType=typeof aVal,bType=typeof bVal;if(bType=null===aVal?"null":bType,(aType="object"===(aType=null===aVal?"null":aType)&&Array.isArray(aType)?"array":aType)!==(bType="object"===bType&&Array.isArray(bType)?"array":bType))return!1;switch(aType){case"object":return isObjectEqual(aVal,bVal);case"array":return isArrayEqual(aVal,bVal);default:return a[key]==b[key]}}))},isMessageEqual=function(a,b){return isObjectEqual({id:a.id,state:a.sendState,text:a.text,timeCreated:a.timeCreated},{id:b.id,state:b.sendState,text:b.text,timeCreated:b.timeCreated})},buildDaysPatch=function(current,remove,add){return{remove:remove,add:add.map((function(day){return{before:findPositionInArray(current,(function(candidate){return day.timestamp<candidate.timestamp})),value:day}}))}},buildConversationPatch=function(state,newState){var matchingDays,remove,add,update,diff=diffArrays(state.messages,newState.messages,isMessageEqual);if(diff.missingFromA.length||diff.missingFromB.length){var current=sortMessagesByDay(state.messages,state.midnight),next=sortMessagesByDay(newState.messages,newState.midnight),daysDiff=diffArrays(current,next,(function(dayCurrent,dayNext){return dayCurrent.timestamp==dayNext.timestamp}));return{days:buildDaysPatch(current,daysDiff.missingFromB,daysDiff.missingFromA),messages:(matchingDays=daysDiff.matches,remove=[],add=[],update=[],matchingDays.forEach((function(days){var dayCurrent=days.a,dayNext=days.b,messagesDiff=diffArrays(dayCurrent.messages,dayNext.messages,isMessageEqual),patch=diffArrays(messagesDiff.missingFromB,messagesDiff.missingFromA,(function(a,b){return a.id==b.id||a.sendState!=b.sendState&&a.timeAdded==b.timeAdded}));remove=remove.concat(patch.missingFromB),patch.missingFromA.forEach((function(message){var before=null;message.timeCreated&&(before=findPositionInArray(dayCurrent.messages,(function(candidate){return message.timeCreated==candidate.timeCreated?message.id<candidate.id:message.timeCreated<candidate.timeCreated}))),add.push({before:before,value:message,day:dayCurrent})})),update=update.concat(patch.matches.map((function(message){return{before:message.a,after:message.b}})))})),{add:add,remove:remove,update:update})}}return null},buildHeaderPatchTypePrivate=function(state,newState){var requireAddContact=buildRequireAddContact(state,newState),confirmContactRequest=buildConfirmContactRequest(state,newState),oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState),requiresAddContact=requireAddContact&&requireAddContact.show&&!requireAddContact.hasMessages,requiredAddContact=requireAddContact&&!requireAddContact.show,shouldRenderHeader=!oldOtherUser&&newOtherUser;return(shouldRenderHeader=(shouldRenderHeader=shouldRenderHeader||requiresAddContact||requiredAddContact)||null!==confirmContactRequest)?{type:Constants.CONVERSATION_TYPES.PRIVATE,showControls:!requiresAddContact&&!confirmContactRequest,context:{id:newState.id,name:newState.name,subname:newState.subname,totalmembercount:newState.totalMemberCount,imageurl:newState.imageUrl,isfavourite:newState.isFavourite,ismuted:newState.isMuted,showfavourite:null!==newState.id,userid:newOtherUser.id,showonlinestatus:newOtherUser.showonlinestatus,isonline:newOtherUser.isonline,isblocked:newOtherUser.isblocked,iscontact:newOtherUser.iscontact}}:null},buildHeaderPatchTypeSelf=function(state,newState){return null===state.name&&null!==newState.name?{type:Constants.CONVERSATION_TYPES.SELF,showControls:!1,context:{id:newState.id,name:newState.name,subname:newState.subname,imageurl:newState.imageUrl,isfavourite:newState.isFavourite,showfavourite:null!==newState.id,showonlinestatus:!0}}:null},buildHeaderPatchTypePublic=function(state,newState){return state.totalMemberCount!=newState.totalMemberCount?{type:Constants.CONVERSATION_TYPES.PUBLIC,showControls:!0,context:{id:newState.id,name:newState.name,subname:newState.subname,totalmembercount:newState.totalMemberCount,imageurl:newState.imageUrl,isfavourite:newState.isFavourite,ismuted:newState.isMuted,showfavourite:null!==newState.id}}:null},buildScrollToMessagePatch=function(state,newState){var oldMessages=state.messages,newMessages=newState.messages;if(newMessages.length<1)return null;if(oldMessages.length<1)return newMessages[newMessages.length-1].id;var previousNewest=oldMessages[state.messages.length-1],currentNewest=newMessages[newMessages.length-1],previousOldest=oldMessages[0],currentOldest=newMessages[0];return previousNewest.id!=currentNewest.id?currentNewest.id:previousOldest.id!=currentOldest.id?previousOldest.id:null},buildLoadingMembersPatch=function(state,newState){return!(state.loadingMembers||!newState.loadingMembers)||!(state.loadingMembers&&!newState.loadingMembers)&&null},buildLoadingFirstMessages=function(state,newState){return state.hasTriedToLoadMessages===newState.hasTriedToLoadMessages?null:!(newState.hasTriedToLoadMessages||!newState.loadingMessages)||!(newState.hasTriedToLoadMessages&&!newState.loadingMessages)&&null},buildLoadingMessages=function(state,newState){return!(state.loadingMessages||!newState.loadingMessages)||!(state.loadingMessages&&!newState.loadingMessages)&&null},buildShowEmojiPicker=function(state,newState){return!(state.showEmojiPicker||!newState.showEmojiPicker)||!(state.showEmojiPicker&&!newState.showEmojiPicker)&&null},buildShowEmojiAutoComplete=function(state,newState){return!(state.showEmojiAutoComplete||!newState.showEmojiAutoComplete)||!(state.showEmojiAutoComplete&&!newState.showEmojiAutoComplete)&&null},buildConfirmBlockUser=function(state,newState){if(newState.pendingBlockUserIds.length){var userId=newState.pendingBlockUserIds[0];return newState.members[userId]}return!state.pendingBlockUserIds.length&&null},buildConfirmUnblockUser=function(state,newState){if(newState.pendingUnblockUserIds.length){var userId=newState.pendingUnblockUserIds[0];return newState.members[userId]}return!state.pendingUnblockUserIds.length&&null},buildConfirmAddContact=function(state,newState){if(newState.pendingAddContactIds.length){var userId=newState.pendingAddContactIds[0];return newState.members[userId]}return!state.pendingAddContactIds.length&&null},buildConfirmRemoveContact=function(state,newState){if(newState.pendingRemoveContactIds.length){var userId=newState.pendingRemoveContactIds[0];return newState.members[userId]}return!state.pendingRemoveContactIds.length&&null},buildConfirmDeleteSelectedMessages=function(state,newState){var oldPendingCount=state.pendingDeleteMessageIds.length,newPendingCount=newState.pendingDeleteMessageIds.length;return newPendingCount&&!oldPendingCount?{show:!0,type:newState.type,canDeleteMessagesForAllUsers:newState.canDeleteMessagesForAllUsers}:oldPendingCount&&!newPendingCount?{show:!1}:null},buildConfirmDeleteConversation=function(state,newState){return!state.pendingDeleteConversation&&newState.pendingDeleteConversation?newState.type:!(state.pendingDeleteConversation&&!newState.pendingDeleteConversation)&&null},buildConfirmContactRequest=function(state,newState){var loggedInUserId=state.loggedInUserId,oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState),oldReceivedRequests=oldOtherUser?oldOtherUser.contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId&&request.userid==oldOtherUser.id})):[],newReceivedRequests=newOtherUser?newOtherUser.contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId&&request.userid==newOtherUser.id})):[],oldRequest=oldReceivedRequests.length?oldReceivedRequests[0]:null,newRequest=newReceivedRequests.length?newReceivedRequests[0]:null;return!oldRequest&&newRequest?newOtherUser:!(oldRequest&&!newRequest)&&null},buildIsBlocked=function(state,newState){var oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState);return oldOtherUser||newOtherUser?!oldOtherUser&&newOtherUser?!!newOtherUser.isblocked||null:!newOtherUser&&oldOtherUser?!oldOtherUser.isblocked&&null:!(oldOtherUser.isblocked&&!newOtherUser.isblocked)&&(!(oldOtherUser.isblocked||!newOtherUser.isblocked)||null):null},buildIsFavourite=function(state,newState){var oldIsFavourite=state.isFavourite,newIsFavourite=newState.isFavourite;return null===state.id&&null===newState.id?null:null===state.id&&null!==newState.id?"show-add":null!==state.id&&null===newState.id?"hide":oldIsFavourite==newIsFavourite?null:!oldIsFavourite&&newIsFavourite?"show-remove":oldIsFavourite&&!newIsFavourite?"show-add":null},buildIsMuted=function(state,newState){var oldIsMuted=state.isMuted,newIsMuted=newState.isMuted;return null===state.id&&null===newState.id?null:null===state.id&&null!==newState.id?"show-mute":null!==state.id&&null===newState.id?"hide":oldIsMuted==newIsMuted?null:!oldIsMuted&&newIsMuted?"show-unmute":oldIsMuted&&!newIsMuted?"show-mute":null},buildIsContact=function(state,newState){var loggedInUserId=state.loggedInUserId,oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState),oldContactRequests=oldOtherUser?oldOtherUser.contactrequests.filter((function(request){return request.userid==loggedInUserId&&request.requesteduserid==oldOtherUser.id||request.userid==oldOtherUser.id&&request.requesteduserid==loggedInUserId})):[],newContactRequests=newOtherUser?newOtherUser.contactrequests.filter((function(request){return request.userid==loggedInUserId&&request.requesteduserid==newOtherUser.id||request.userid==newOtherUser.id&&request.requesteduserid==loggedInUserId})):[],oldHasContactRequests=oldContactRequests.length>0,newHasContactRequests=newContactRequests.length>0;return oldOtherUser||newOtherUser?oldHasContactRequests&&newHasContactRequests?null:oldHasContactRequests||!newHasContactRequests||newOtherUser.iscontact?!oldOtherUser&&newOtherUser?newOtherUser.iscontact?"contact":null:!newOtherUser&&oldOtherUser?oldOtherUser.iscontact?"non-contact":null:oldOtherUser.iscontact&&!newOtherUser.iscontact?newHasContactRequests?"pending-contact":"non-contact":!oldOtherUser.iscontact&&newOtherUser.iscontact?"contact":null:"pending-contact":null},buildLoadingConfirmationAction=function(state,newState){return!(state.loadingConfirmAction||!newState.loadingConfirmAction)||!(state.loadingConfirmAction&&!newState.loadingConfirmAction)&&null},buildInEditMode=function(state,newState){var oldHasSelectedMessages=state.selectedMessageIds.length>0,newHasSelectedMessages=newState.selectedMessageIds.length>0,numberOfMessagesHasChanged=state.messages.length!=newState.messages.length;return!(oldHasSelectedMessages||!newHasSelectedMessages)||!(oldHasSelectedMessages&&!newHasSelectedMessages)&&(!(!oldHasSelectedMessages||!numberOfMessagesHasChanged)||null)},buildSelectedMessages=function(state,newState){var oldSelectedMessages=state.selectedMessageIds,newSelectedMessages=newState.selectedMessageIds;if(isArrayEqual(oldSelectedMessages,newSelectedMessages))return null;var diff=diffArrays(oldSelectedMessages,newSelectedMessages,(function(a,b){return a==b}));return{count:newSelectedMessages.length,add:diff.missingFromA,remove:diff.missingFromB}},getOtherUserFromState=function(state){return Object.keys(state.members).reduce((function(carry,userId){return userId==state.loggedInUserId||carry||(carry=state.members[userId]),carry}),null)},requiresContactRequest=function(loggedInUserId,user){if(user.canmessage)return!1;var hasSentContactRequest=user.contactrequests.filter((function(request){return request.userid==loggedInUserId||request.requesteduserid})).length>0;return user.requirescontact&&!user.iscontact&&!hasSentContactRequest},buildRequireAddContact=function(state,newState){var oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState),hadMessages=state.messages.length>0,hasMessages=newState.messages.length>0,loggedInUserId=newState.loggedInUserId,prevRequiresContactRequest=oldOtherUser&&requiresContactRequest(loggedInUserId,oldOtherUser),nextRequiresContactRequest=newOtherUser&&requiresContactRequest(loggedInUserId,newOtherUser),finishedAddContact=!1===buildConfirmAddContact(state,newState);if(!state.hasTriedToLoadMessages&&!newState.hasTriedToLoadMessages)return null;if(!oldOtherUser&&!newOtherUser)return null;if(!oldOtherUser&&nextRequiresContactRequest)return{show:!0,hasMessages:hasMessages,user:newOtherUser};if(finishedAddContact&&nextRequiresContactRequest)return{show:!0,hasMessages:hasMessages,user:newOtherUser};if(state.hasTriedToLoadMessages&&newState.hasTriedToLoadMessages){if(!prevRequiresContactRequest&&nextRequiresContactRequest)return{show:!0,hasMessages:hasMessages,user:newOtherUser};if(prevRequiresContactRequest&&!nextRequiresContactRequest)return{show:!1,hasMessages:hasMessages}}return!state.hasTriedToLoadMessages&&newState.hasTriedToLoadMessages&&nextRequiresContactRequest?{show:!0,hasMessages:hasMessages,user:newOtherUser}:state.hasTriedToLoadMessages&&!newState.hasTriedToLoadMessages&&prevRequiresContactRequest?{show:!1,hasMessages:hadMessages}:null},buildFooterPatchTypePrivate=function(state,newState){var loadingFirstMessages=buildLoadingFirstMessages(state,newState),inEditMode=buildInEditMode(state,newState),requireAddContact=buildRequireAddContact(state,newState),requireUnblock=function(state,newState){var oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState);return oldOtherUser||newOtherUser?oldOtherUser&&!newOtherUser?!oldOtherUser.isblocked&&null:!oldOtherUser&&newOtherUser?!!newOtherUser.isblocked||null:!(oldOtherUser.isblocked||!newOtherUser.isblocked)||!(oldOtherUser.isblocked&&!newOtherUser.isblocked)&&null:null}(state,newState),unableToMessage=function(state,newState){var oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState);return newState.type==Constants.CONVERSATION_TYPES.SELF?null:oldOtherUser||newOtherUser?oldOtherUser&&!newOtherUser?!oldOtherUser.canmessage||null:!oldOtherUser&&newOtherUser?!newOtherUser.canmessage||null:!(!oldOtherUser.canmessage&&newOtherUser.canmessage)&&(!(!oldOtherUser.canmessage||newOtherUser.canmessage)||null):null}(state,newState),showRequireAddContact=null!==requireAddContact?requireAddContact.show&&requireAddContact.hasMessages:null,otherUser=getOtherUserFromState(newState),generateReturnValue=function(checkValue,successReturn){if(checkValue)return successReturn;if(null!==checkValue&&!checkValue){if(!otherUser)return{type:"content"};if(otherUser.isblocked)return{type:"unblock"};if(newState.messages.length&&requiresContactRequest(newState.loggedInUserId,otherUser))return{type:"add-contact",user:otherUser};if(!otherUser.canmessage&&otherUser.requirescontact&&!otherUser.iscontact)return{type:"unable-to-message"}}return null};if(null===loadingFirstMessages&&null===inEditMode&&null===requireAddContact&&null===requireUnblock)return null;for(var checks=[[loadingFirstMessages,{type:"placeholder"}],[inEditMode,{type:"edit-mode"}],[unableToMessage,{type:"unable-to-message"}],[requireUnblock,{type:"unblock"}],[showRequireAddContact,{type:"add-contact",user:otherUser}]],i=0;i<checks.length;i++){var result=generateReturnValue(checks[i][0],checks[i][1]);if(null!==result)return result}return{type:"content"}},buildFooterPatchTypePublic=function(state,newState){var loadingFirstMessages=buildLoadingFirstMessages(state,newState),inEditMode=buildInEditMode(state,newState);return null===loadingFirstMessages&&null===inEditMode?null:loadingFirstMessages?{type:"placeholder"}:inEditMode?{type:"edit-mode"}:{type:"content"}},buildReset=function(state,newState){var oldType=state.type,newType=newState.type,oldConversationId=state.id,newConversationId=newState.id,oldMemberIds=Object.keys(state.members),newMemberIds=Object.keys(newState.members);oldMemberIds.sort(),newMemberIds.sort();var membersUnchanged=oldMemberIds.every((function(id,index){return id==newMemberIds[index]}));return oldType!=newType||(!(!oldConversationId||newConversationId)||(!(!oldConversationId||!newConversationId||oldConversationId==newConversationId)||(!(oldConversationId||newConversationId||membersUnchanged)||null)))},buildSelfConversationMessage=function(state,newState){return state.type!=newState.type?newState.type==Constants.CONVERSATION_TYPES.SELF:null},buildContactRequestSent=function(state,newState){var loggedInUserId=newState.loggedInUserId,oldOtherUser=getOtherUserFromState(state),newOtherUser=getOtherUserFromState(newState),oldSentRequests=oldOtherUser?oldOtherUser.contactrequests.filter((function(request){return request.userid==loggedInUserId})):[],newSentRequests=newOtherUser?newOtherUser.contactrequests.filter((function(request){return request.userid==loggedInUserId})):[],oldRequest=oldSentRequests.length>0,newRequest=newSentRequests.length>0;return oldRequest||!newRequest||newOtherUser.iscontact?!(oldOtherUser&&!oldOtherUser.iscontact&&newRequest&&newOtherUser.iscontact)&&(!(oldRequest&&!newRequest)&&null):newOtherUser.fullname};return{buildPatch:function(state,newState){var config={all:{reset:buildReset,conversation:buildConversationPatch,scrollToMessage:buildScrollToMessagePatch,loadingMembers:buildLoadingMembersPatch,loadingFirstMessages:buildLoadingFirstMessages,loadingMessages:buildLoadingMessages,confirmDeleteSelectedMessages:buildConfirmDeleteSelectedMessages,inEditMode:buildInEditMode,selectedMessages:buildSelectedMessages,isFavourite:buildIsFavourite,isMuted:buildIsMuted,showEmojiPicker:buildShowEmojiPicker,showEmojiAutoComplete:buildShowEmojiAutoComplete}};config[Constants.CONVERSATION_TYPES.PRIVATE]={header:buildHeaderPatchTypePrivate,footer:buildFooterPatchTypePrivate,confirmBlockUser:buildConfirmBlockUser,confirmUnblockUser:buildConfirmUnblockUser,confirmAddContact:buildConfirmAddContact,confirmRemoveContact:buildConfirmRemoveContact,confirmContactRequest:buildConfirmContactRequest,confirmDeleteConversation:buildConfirmDeleteConversation,isBlocked:buildIsBlocked,isContact:buildIsContact,loadingConfirmAction:buildLoadingConfirmationAction,requireAddContact:buildRequireAddContact,contactRequestSent:buildContactRequestSent},config[Constants.CONVERSATION_TYPES.PUBLIC]={header:buildHeaderPatchTypePublic,footer:buildFooterPatchTypePublic},config[Constants.CONVERSATION_TYPES.SELF]={header:buildHeaderPatchTypeSelf,footer:buildFooterPatchTypePublic,confirmDeleteConversation:buildConfirmDeleteConversation,selfConversationMessage:buildSelfConversationMessage};var patchConfig=$.extend({},config.all);return newState.type&&newState.type in config&&(patchConfig=$.extend(patchConfig,config[newState.type])),Object.keys(patchConfig).reduce((function(patch,key){var value=(0,patchConfig[key])(state,newState);return null!==value&&(patch[key]=value),patch}),{})}}})); /** * This module updates the UI for the conversation page in the message * drawer. * * The module will take a patch from the message_drawer_view_conversation_patcher * module and update the UI to reflect the changes. * * This is the only module that ever modifies the UI of the conversation page. * * @module core_message/message_drawer_view_conversation_renderer * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_conversation_renderer",["jquery","core/notification","core/str","core/templates","core/user_date","core_message/message_drawer_view_conversation_constants","core/aria"],(function($,Notification,Str,Templates,UserDate,Constants,Aria){var SELECTORS=Constants.SELECTORS,TEMPLATES=Constants.TEMPLATES,CONVERSATION_TYPES=Constants.CONVERSATION_TYPES,getMessagesContainer=function(body){return body.find(SELECTORS.CONTENT_MESSAGES_CONTAINER)},getSelfConversationMessageContainer=function(body){return body.find(SELECTORS.SELF_CONVERSATION_MESSAGE_CONTAINER)},getContactRequestSentContainer=function(body){return body.find(SELECTORS.CONTACT_REQUEST_SENT_MESSAGE_CONTAINER)},getFooterContentContainer=function(footer){return footer.find(SELECTORS.CONTENT_MESSAGES_FOOTER_CONTAINER)},getFooterEditModeContainer=function(footer){return footer.find(SELECTORS.CONTENT_MESSAGES_FOOTER_EDIT_MODE_CONTAINER)},getFooterPlaceholderContainer=function(footer){return footer.find(SELECTORS.PLACEHOLDER_CONTAINER)},showFooterPlaceholder=function(footer){getFooterPlaceholderContainer(footer).removeClass("hidden")},getFooterRequireContactContainer=function(footer){return footer.find(SELECTORS.CONTENT_MESSAGES_FOOTER_REQUIRE_CONTACT_CONTAINER)},getFooterRequireUnblockContainer=function(footer){return footer.find(SELECTORS.CONTENT_MESSAGES_FOOTER_REQUIRE_UNBLOCK_CONTAINER)},getFooterUnableToMessageContainer=function(footer){return footer.find(SELECTORS.CONTENT_MESSAGES_FOOTER_UNABLE_TO_MESSAGE_CONTAINER)},hideAllFooterElements=function(footer){!function(footer){getFooterContentContainer(footer).addClass("hidden")}(footer),function(footer){getFooterEditModeContainer(footer).addClass("hidden")}(footer),function(footer){getFooterPlaceholderContainer(footer).addClass("hidden")}(footer),function(footer){getFooterRequireContactContainer(footer).addClass("hidden")}(footer),function(footer){getFooterRequireUnblockContainer(footer).addClass("hidden")}(footer),function(footer){getFooterUnableToMessageContainer(footer).addClass("hidden")}(footer)},getContentPlaceholderContainer=function(body){return body.find(SELECTORS.CONTENT_PLACEHOLDER_CONTAINER)},getHeaderContent=function(header){return header.find(SELECTORS.HEADER)},showHeaderContent=function(header){getHeaderContent(header).removeClass("hidden")},hideHeaderContent=function(header){getHeaderContent(header).addClass("hidden")},getHeaderEditMode=function(header){return header.find(SELECTORS.HEADER_EDIT_MODE)},hideHeaderEditMode=function(header){getHeaderEditMode(header).addClass("hidden")},getHeaderPlaceholderContainer=function(header){return header.find(SELECTORS.HEADER_PLACEHOLDER_CONTAINER)},showHeaderPlaceholder=function(header){getHeaderPlaceholderContainer(header).removeClass("hidden")},hideHeaderPlaceholder=function(header){getHeaderPlaceholderContainer(header).addClass("hidden")},getMessageElement=function(body,messageId){return getMessagesContainer(body).find('[data-message-id="'+messageId+'"]')},getDayElement=function(body,dayTimeCreated){return getMessagesContainer(body).find('[data-day-id="'+dayTimeCreated+'"]')},getMoreMessagesLoadingIconContainer=function(body){return body.find(SELECTORS.MORE_MESSAGES_LOADING_ICON_CONTAINER)},getConfirmDialogueContainer=function(root){return root.find(SELECTORS.CONFIRM_DIALOGUE_CONTAINER)},showConfirmDialogueContainer=function(root){var container=getConfirmDialogueContainer(root),siblings=container.siblings(":not(.hidden)");Aria.hide(siblings.get()),siblings.attr("data-confirm-dialogue-hidden",!0),container.removeClass("hidden")},hideConfirmDialogueContainer=function(root){var container=getConfirmDialogueContainer(root),siblings=container.siblings('[data-confirm-dialogue-hidden="true"]');Aria.unhide(siblings.get()),siblings.removeAttr("data-confirm-dialogue-hidden"),container.addClass("hidden")},formatMessagesForTemplate=function(messages,datesCache){return messages.map((function(message){return{id:message.id,isread:message.isRead,fromloggedinuser:message.fromLoggedInUser,userfrom:message.userFrom,text:message.text,formattedtime:message.timeCreated?datesCache[message.timeCreated]:null}}))},renderConversation=function(header,body,footer,data){var renderingPromises=[],hasAddDays=data.days.add.length>0,hasAddMessages=data.messages.add.length>0,hasUpdateMessages=data.messages.update.length>0,timestampsToFormat=[],datesCachePromise=$.Deferred().resolve({}).promise();return hasAddDays&&(timestampsToFormat=timestampsToFormat.concat(data.days.add.reduce((function(carry,day){return carry.concat(day.value.messages.reduce((function(timestamps,message){return message.timeCreated&×tamps.push(message.timeCreated),timestamps}),[]))}),[]))),hasAddMessages&&(timestampsToFormat=timestampsToFormat.concat(data.messages.add.reduce((function(timestamps,message){return message.value.timeCreated&×tamps.push(message.value.timeCreated),timestamps}),[]))),hasUpdateMessages&&(timestampsToFormat=timestampsToFormat.concat(data.messages.update.reduce((function(timestamps,message){return message.before.timeCreated!=message.after.timeCreated&×tamps.push(message.after.timeCreated),timestamps}),[]))),timestampsToFormat.length&&(datesCachePromise=Str.get_string("strftimetime24","core_langconfig").then((function(format){var requests=timestampsToFormat.map((function(timestamp){return{timestamp:timestamp,format:format}}));return UserDate.get(requests)})).then((function(formattedTimes){return timestampsToFormat.reduce((function(carry,timestamp,index){return carry[timestamp]=formattedTimes[index],carry}),{})}))),hasAddDays&&renderingPromises.push(datesCachePromise.then((function(datesCache){return function(header,body,footer,days,datesCache){var messagesContainer=getMessagesContainer(body),daysRenderPromises=days.map((function(data){var timestampDate=new Date(1e3*data.value.timestamp);return Templates.render(TEMPLATES.DAY,{timestamp:data.value.timestamp,currentyear:timestampDate.getFullYear()===(new Date).getFullYear(),messages:formatMessagesForTemplate(data.value.messages,datesCache)})}));return $.when.apply($,daysRenderPromises).then((function(){days.forEach((function(data,index){daysRenderPromises[index].then((function(html){if(data.before){var element=getDayElement(body,data.before.timestamp);return $(html).insertBefore(element)}return messagesContainer.append(html)})).catch((function(){}))}))}))}(0,body,0,data.days.add,datesCache)}))),hasAddMessages&&renderingPromises.push(datesCachePromise.then((function(datesCache){return function(header,body,footer,messages,datesCache){var messagesData=messages.map((function(data){return data.value})),formattedMessages=formatMessagesForTemplate(messagesData,datesCache);return Templates.render(TEMPLATES.MESSAGES,{messages:formattedMessages}).then((function(html){var messageList=$(html);messages.forEach((function(data){var messageHtml=messageList.find('[data-message-id="'+data.value.id+'"]');if(data.before){var element=getMessageElement(body,data.before.id);return messageHtml.insertBefore(element)}return getDayElement(body,data.day.timestamp).find(SELECTORS.DAY_MESSAGES_CONTAINER).append(messageHtml)}))}))}(0,body,0,data.messages.add,datesCache)}))),hasUpdateMessages&&renderingPromises.push(datesCachePromise.then((function(datesCache){return function(header,body,footer,messages,datesCache){messages.forEach((function(message){var before=message.before,after=message.after,element=getMessageElement(body,before.id);if(before.id!=after.id&&element.attr("data-message-id",after.id),before.timeCreated!=after.timeCreated){var formattedTime=datesCache[after.timeCreated];element.find(SELECTORS.LOADING_ICON_CONTAINER).addClass("hidden"),element.find(SELECTORS.TIME_CREATED).text(formattedTime).removeClass("hidden")}if(before.sendState!=after.sendState){var loading=element.find(SELECTORS.LOADING_ICON_CONTAINER),time=element.find(SELECTORS.TIME_CREATED),retry=element.find(SELECTORS.RETRY_SEND);switch(loading.addClass("hidden"),Aria.hide(loading.get()),time.addClass("hidden"),Aria.hide(time.get()),retry.addClass("hidden"),Aria.hide(retry.get()),element.removeClass("border border-danger"),after.sendState){case"pending":loading.removeClass("hidden"),Aria.unhide(loading.get());break;case"error":retry.removeClass("hidden"),Aria.unhide(retry.get()),element.addClass("border border-danger");break;case"sent":time.removeClass("hidden"),Aria.unhide(time.get())}}if(before.text!=after.text&&element.find(SELECTORS.TEXT_CONTAINER).html(after.text),before.errorMessage!=after.errorMessage){var messageContainer=element.find(SELECTORS.ERROR_MESSAGE_CONTAINER);message=messageContainer.find(SELECTORS.ERROR_MESSAGE),after.errorMessage?(messageContainer.removeClass("hidden"),Aria.unhide(messageContainer.get()),message.text(after.errorMessage)):(messageContainer.addClass("hidden"),Aria.unhide(messageContainer.get()),message.text(""))}}))}(0,body,0,data.messages.update,datesCache)}))),data.days.remove.length>0&&function(body,days){days.forEach((function(data){getDayElement(body,data.timestamp).remove()}))}(body,data.days.remove),data.messages.remove.length>0&&function(body,messages){messages.forEach((function(data){getMessageElement(body,data.id).remove()}))}(body,data.messages.remove),$.when.apply($,renderingPromises)},renderHeader=function(header,body,footer,data){var headerContainer=getHeaderContent(header),template=TEMPLATES.HEADER_PUBLIC;return data.context.showrouteback="false"===header.attr("data-from-panel"),data.type==CONVERSATION_TYPES.PRIVATE?template=data.showControls?TEMPLATES.HEADER_PRIVATE:TEMPLATES.HEADER_PRIVATE_NO_CONTROLS:data.type==CONVERSATION_TYPES.SELF&&(template=TEMPLATES.HEADER_SELF),Templates.render(template,data.context).then((function(html,js){Templates.replaceNodeContents(headerContainer,html,js)}))},renderFooter=function(header,body,footer,data){switch(hideAllFooterElements(footer),data.type){case"placeholder":return showFooterPlaceholder(footer);case"add-contact":return Str.get_strings([{key:"requirecontacttomessage",component:"core_message",param:data.user.fullname},{key:"isnotinyourcontacts",component:"core_message",param:data.user.fullname}]).then((function(strings){var title=strings[1],text=strings[0],footerContainer=getFooterRequireContactContainer(footer);return footerContainer.find(SELECTORS.TITLE).text(title),footerContainer.find(SELECTORS.TEXT).text(text),function(footer){getFooterRequireContactContainer(footer).removeClass("hidden")}(footer),strings}));case"edit-mode":return function(footer){getFooterEditModeContainer(footer).removeClass("hidden")}(footer);case"content":return function(footer){getFooterContentContainer(footer).removeClass("hidden")}(footer);case"unblock":return function(footer){getFooterRequireUnblockContainer(footer).removeClass("hidden")}(footer);case"unable-to-message":return function(footer){getFooterUnableToMessageContainer(footer).removeClass("hidden")}(footer)}return!0},renderScrollToMessage=function(header,body,footer,messageId){var messagesContainer=getMessagesContainer(body),position=getMessageElement(body,messageId).position();if(position){var scrollTop=messagesContainer.scrollTop()+position.top;messagesContainer.scrollTop(scrollTop)}},renderLoadingMembers=function(header,body,footer,isLoadingMembers){isLoadingMembers?(hideHeaderContent(header),showHeaderPlaceholder(header)):(showHeaderContent(header),hideHeaderPlaceholder(header))},renderLoadingFirstMessages=function(header,body,footer,isLoadingFirstMessages){isLoadingFirstMessages?(function(body){getMessagesContainer(body).addClass("hidden")}(body),function(body){getContentPlaceholderContainer(body).removeClass("hidden")}(body)):(function(body){getMessagesContainer(body).removeClass("hidden")}(body),function(body){getContentPlaceholderContainer(body).addClass("hidden")}(body))},renderLoadingMessages=function(header,body,footer,isLoading){isLoading?function(body){getMoreMessagesLoadingIconContainer(body).removeClass("hidden")}(body):function(body){getMoreMessagesLoadingIconContainer(body).addClass("hidden")}(body)},renderShowEmojiPicker=function(header,body,footer,show){var container=function(footer){return footer.find(SELECTORS.EMOJI_PICKER_CONTAINER)}(footer);show?(container.removeClass("hidden"),Aria.unhide(container.get()),container.find(SELECTORS.EMOJI_PICKER_SEARCH_INPUT).focus()):(container.addClass("hidden"),Aria.hide(container.get()))},renderShowEmojiAutoComplete=function(header,body,footer,show){var container=function(footer){return footer.find(SELECTORS.EMOJI_AUTO_COMPLETE_CONTAINER)}(footer);show?(container.removeClass("hidden"),Aria.unhide(container.get())):(container.addClass("hidden"),Aria.hide(container.get()))},showConfirmDialogue=function(header,body,footer,buttonSelectors,bodyText,headerText,canCancel,skipHeader,showOk){var dialogue=getConfirmDialogueContainer(body),buttons=buttonSelectors.map((function(selector){return dialogue.find(selector)})),cancelButton=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_CANCEL_BUTTON),okayButton=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_OKAY_BUTTON),text=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_TEXT),dialogueHeader=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_HEADER);(dialogue.find("button").addClass("hidden"),canCancel?cancelButton.removeClass("hidden"):cancelButton.addClass("hidden"),showOk?okayButton.removeClass("hidden"):okayButton.addClass("hidden"),headerText)?((dialogueHeader=$('<h3 class="h6" data-region="dialogue-header"></h3>')).text(headerText),dialogue.find(SELECTORS.CONFIRM_DIALOGUE).prepend(dialogueHeader)):dialogueHeader.length&&dialogueHeader.remove();buttons.forEach((function(button){button.removeClass("hidden")})),text.text(bodyText),showConfirmDialogueContainer(footer),showConfirmDialogueContainer(body),skipHeader||showConfirmDialogueContainer(header),dialogue.find(SELECTORS.CAN_RECEIVE_FOCUS).filter(":visible").first().focus()},hideConfirmDialogue=function(header,body,footer){var dialogue=getConfirmDialogueContainer(body),cancelButton=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_CANCEL_BUTTON),okayButton=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_OKAY_BUTTON),text=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_TEXT),dialogueHeader=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_HEADER);return hideCheckDeleteDialogue(body),hideConfirmDialogueContainer(body),hideConfirmDialogueContainer(footer),hideConfirmDialogueContainer(header),dialogue.find("button").addClass("hidden"),cancelButton.removeClass("hidden"),okayButton.removeClass("hidden"),text.text(""),dialogueHeader.length&&dialogueHeader.remove(),header.find(SELECTORS.CAN_RECEIVE_FOCUS).first().focus(),!0},renderConfirmBlockUser=function(header,body,footer,user){return user?user.canmessageevenifblocked?Str.get_string("cantblockuser","core_message",user.fullname).then((function(string){return showConfirmDialogue(header,body,footer,[],string,"",!1,!1,!0)})):Str.get_string("blockuserconfirm","core_message",user.fullname).then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_BLOCK],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmUnblockUser=function(header,body,footer,user){return user?Str.get_string("unblockuserconfirm","core_message",user.fullname).then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_UNBLOCK],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmAddContact=function(header,body,footer,user){return user?Str.get_string("addcontactconfirm","core_message",user.fullname).then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_ADD_CONTACT],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmRemoveContact=function(header,body,footer,user){return user?Str.get_string("removecontactconfirm","core_message",user.fullname).then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_REMOVE_CONTACT],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmDeleteSelectedMessages=function(header,body,footer,data){var showmessage=null;return data.type==CONVERSATION_TYPES.SELF?showmessage="deleteselectedmessagesconfirmselfconversation":data.canDeleteMessagesForAllUsers?(showCheckDeleteDialogue(body),showmessage="deleteforeveryoneselectedmessagesconfirm"):showmessage="deleteselectedmessagesconfirm",data.show?Str.get_string(showmessage,"core_message").then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_DELETE_SELECTED_MESSAGES],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmDeleteConversation=function(header,body,footer,type){var showmessage=null;return type==CONVERSATION_TYPES.SELF?showmessage="deleteallselfconfirm":type&&(showmessage="deleteallconfirm"),showmessage?Str.get_string(showmessage,"core_message").then((function(string){return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_CONFIRM_DELETE_CONVERSATION],string,"",!0,!1)})):hideConfirmDialogue(header,body,footer)},renderConfirmContactRequest=function(header,body,footer,user){return user?Str.get_string("userwouldliketocontactyou","core_message",user.fullname).then((function(string){var buttonSelectors=[SELECTORS.ACTION_ACCEPT_CONTACT_REQUEST,SELECTORS.ACTION_DECLINE_CONTACT_REQUEST];return showConfirmDialogue(header,body,footer,buttonSelectors,string,"",!1,!0)})):hideConfirmDialogue(header,body,footer)},showCheckDeleteDialogue=function(body){getConfirmDialogueContainer(body).find(SELECTORS.DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE_CONTAINER).removeClass("hidden")},hideCheckDeleteDialogue=function(body){var dialogue=getConfirmDialogueContainer(body),checkboxRegion=dialogue.find(SELECTORS.DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE_CONTAINER);dialogue.find(SELECTORS.DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE).prop("checked",!1),checkboxRegion.addClass("hidden")},renderIsBlocked=function(header,body,footer,isBlocked){isBlocked?(header.find(SELECTORS.ACTION_REQUEST_BLOCK).addClass("hidden"),header.find(SELECTORS.ACTION_REQUEST_UNBLOCK).removeClass("hidden")):(header.find(SELECTORS.ACTION_REQUEST_BLOCK).removeClass("hidden"),header.find(SELECTORS.ACTION_REQUEST_UNBLOCK).addClass("hidden"))},renderIsFavourite=function(header,body,footer,state){var favouriteIcon=header.find(SELECTORS.FAVOURITE_ICON_CONTAINER),addFavourite=header.find(SELECTORS.ACTION_CONFIRM_FAVOURITE),removeFavourite=header.find(SELECTORS.ACTION_CONFIRM_UNFAVOURITE);switch(state){case"hide":favouriteIcon.addClass("hidden"),addFavourite.addClass("hidden"),removeFavourite.addClass("hidden");break;case"show-add":favouriteIcon.addClass("hidden"),addFavourite.removeClass("hidden"),removeFavourite.addClass("hidden");break;case"show-remove":favouriteIcon.removeClass("hidden"),addFavourite.addClass("hidden"),removeFavourite.removeClass("hidden")}},renderIsMuted=function(header,body,footer,state){var muteIcon=header.find(SELECTORS.MUTED_ICON_CONTAINER),setMuted=header.find(SELECTORS.ACTION_CONFIRM_MUTE),unsetMuted=header.find(SELECTORS.ACTION_CONFIRM_UNMUTE);switch(state){case"hide":muteIcon.addClass("hidden"),setMuted.addClass("hidden"),unsetMuted.addClass("hidden");break;case"show-mute":muteIcon.addClass("hidden"),setMuted.removeClass("hidden"),unsetMuted.addClass("hidden");break;case"show-unmute":muteIcon.removeClass("hidden"),setMuted.addClass("hidden"),unsetMuted.removeClass("hidden")}},renderIsContact=function(header,body,footer,state){var addContact=header.find(SELECTORS.ACTION_REQUEST_ADD_CONTACT),removeContact=header.find(SELECTORS.ACTION_REQUEST_REMOVE_CONTACT);switch(state){case"pending-contact":addContact.addClass("hidden"),removeContact.addClass("hidden");break;case"contact":addContact.addClass("hidden"),removeContact.removeClass("hidden");break;case"non-contact":addContact.removeClass("hidden"),removeContact.addClass("hidden")}},renderLoadingConfirmAction=function(header,body,footer,isLoading){var dialogue=getConfirmDialogueContainer(body),buttons=dialogue.find("button"),buttonText=dialogue.find(SELECTORS.CONFIRM_DIALOGUE_BUTTON_TEXT),loadingIcon=dialogue.find(SELECTORS.LOADING_ICON_CONTAINER);isLoading?(buttons.prop("disabled",!0),buttonText.addClass("hidden"),loadingIcon.removeClass("hidden")):(buttons.prop("disabled",!1),buttonText.removeClass("hidden"),loadingIcon.addClass("hidden"))},renderInEditMode=function(header,body,footer,inEditMode){var messages=null;inEditMode?((messages=body.find(SELECTORS.MESSAGE_NOT_SELECTED)).find(SELECTORS.MESSAGE_NOT_SELECTED_ICON).removeClass("hidden"),hideHeaderContent(header),function(header){getHeaderEditMode(header).removeClass("hidden")}(header)):((messages=getMessagesContainer(body)).find(SELECTORS.MESSAGE_NOT_SELECTED_ICON).addClass("hidden"),messages.find(SELECTORS.MESSAGE_SELECTED_ICON).addClass("hidden"),showHeaderContent(header),hideHeaderEditMode(header))},renderSelectedMessages=function(header,body,footer,data){var hasSelectedMessages=data.count>0;data.add.length&&data.add.forEach((function(messageId){var message=getMessageElement(body,messageId);message.find(SELECTORS.MESSAGE_NOT_SELECTED_ICON).addClass("hidden"),message.find(SELECTORS.MESSAGE_SELECTED_ICON).removeClass("hidden"),message.attr("aria-checked",!0)})),data.remove.length&&data.remove.forEach((function(messageId){var message=getMessageElement(body,messageId);hasSelectedMessages&&message.find(SELECTORS.MESSAGE_NOT_SELECTED_ICON).removeClass("hidden"),message.find(SELECTORS.MESSAGE_SELECTED_ICON).addClass("hidden"),message.attr("aria-checked",!1)})),function(header,value){getHeaderEditMode(header).find(SELECTORS.MESSAGES_SELECTED_COUNT).text(value)}(header,data.count)},renderRequireAddContact=function(header,body,footer,data){return data.show&&!data.hasMessages?Str.get_strings([{key:"requirecontacttomessage",component:"core_message",param:data.user.fullname},{key:"isnotinyourcontacts",component:"core_message",param:data.user.fullname}]).then((function(strings){var title=strings[1],text=strings[0];return showConfirmDialogue(header,body,footer,[SELECTORS.ACTION_REQUEST_ADD_CONTACT],text,title,!1,!0)})):hideConfirmDialogue(header,body,footer)},renderSelfConversationMessage=function(header,body,footer,displayMessage){var container=getSelfConversationMessageContainer(body);return displayMessage?container.removeClass("hidden"):container.addClass("hidden"),!0},renderContactRequestSent=function(header,body,footer,userFullName){var container=getContactRequestSentContainer(body);return userFullName?Str.get_string("yourcontactrequestpending","core_message",userFullName).then((function(string){return container.find(SELECTORS.TEXT).text(string),container.removeClass("hidden"),string})):(container.addClass("hidden"),!0)},renderReset=function(header,body,footer){return hideConfirmDialogue(header,body,footer),function(body){getContactRequestSentContainer(body).addClass("hidden")}(body),function(body){getSelfConversationMessageContainer(body).addClass("hidden")}(body),function(header){hideHeaderContent(header),hideHeaderEditMode(header),hideHeaderPlaceholder(header)}(header),showHeaderPlaceholder(header),hideAllFooterElements(footer),showFooterPlaceholder(footer),!0};return{render:function(header,body,footer,patch){var configs=[{reset:renderReset},{conversation:renderConversation,header:renderHeader,footer:renderFooter,confirmBlockUser:renderConfirmBlockUser,confirmUnblockUser:renderConfirmUnblockUser,confirmAddContact:renderConfirmAddContact,confirmRemoveContact:renderConfirmRemoveContact,confirmDeleteSelectedMessages:renderConfirmDeleteSelectedMessages,confirmDeleteConversation:renderConfirmDeleteConversation,confirmContactRequest:renderConfirmContactRequest,requireAddContact:renderRequireAddContact,selfConversationMessage:renderSelfConversationMessage,contactRequestSent:renderContactRequestSent},{loadingMembers:renderLoadingMembers,loadingFirstMessages:renderLoadingFirstMessages,loadingMessages:renderLoadingMessages,isBlocked:renderIsBlocked,isContact:renderIsContact,isFavourite:renderIsFavourite,isMuted:renderIsMuted,loadingConfirmAction:renderLoadingConfirmAction,inEditMode:renderInEditMode,showEmojiPicker:renderShowEmojiPicker,showEmojiAutoComplete:renderShowEmojiAutoComplete},{scrollToMessage:renderScrollToMessage,selectedMessages:renderSelectedMessages}],processConfig=function(config){var results=[];for(var key in patch)if(config.hasOwnProperty(key)){var renderFunc=config[key],patchValue=patch[key];results.push(renderFunc(header,body,footer,patchValue))}return results},renderingPromises=processConfig(configs[0]);return renderingPromises=renderingPromises.concat(processConfig(configs[1])),$.when.apply($,renderingPromises).then((function(){for(var i=2;i<configs.length;i++)processConfig(configs[i])})).catch(Notification.exception)}}})); /** * This module operates on the view states from the message_drawer_view_conversation module. * It exposes functions that can be used to generate new version of the state. * * Important notes for this module: * 1.) The existing state is always immutable. It should never be modified. * 2.) All functions that operate on the state should always clone the state and * modify the cloned state before returning it. * * It's important that the states remain immutable because they are diff'd in * the message_drawer_view_conversation_patcher module in order to work out what * has changed. * * @module core_message/message_drawer_view_conversation_state_manager * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_conversation_state_manager",["jquery"],(function($){var cloneState=function(state){return $.extend(!0,{},state)},formatMessages=function(messages,loggedInUserId,members){return messages.map((function(message){var fromLoggedInUser=message.useridfrom==loggedInUserId;return{id:""+message.id,fromLoggedInUser:fromLoggedInUser,userFrom:members[message.useridfrom],text:message.text,timeCreated:message.timecreated?parseInt(message.timecreated,10):null}}))};return{buildInitialState:function(midnight,loggedInUserId,id,messagePollMin,messagePollMax,messagePollAfterMax){return{midnight:midnight,loggedInUserId:loggedInUserId,id:id,messagePollMin:messagePollMin,messagePollMax:messagePollMax,messagePollAfterMax:messagePollAfterMax,name:null,subname:null,type:null,totalMemberCount:null,imageUrl:null,isFavourite:null,isMuted:null,canDeleteMessagesForAllUsers:!1,deleteMessagesForAllUsers:!1,members:{},messages:[],hasTriedToLoadMessages:!1,loadingMessages:!0,loadingMembers:!0,loadingConfirmAction:!1,pendingBlockUserIds:[],pendingUnblockUserIds:[],pendingRemoveContactIds:[],pendingAddContactIds:[],pendingDeleteMessageIds:[],pendingSendMessageIds:[],pendingDeleteConversation:!1,selectedMessageIds:[],showEmojiAutoComplete:!1,showEmojiPicker:!1}},addMessages:function(state,messages){var newState=cloneState(state),formattedMessages=formatMessages(messages,state.loggedInUserId,state.members);formattedMessages=formattedMessages.map((function(message){return message.sendState=null,message.timeAdded=Date.now(),message.errorMessage=null,message}));var allMessages=state.messages.concat(formattedMessages);return allMessages.sort((function(a,b){if(null===a.timeCreated&&null===b.timeCreated){if(a.timeAdded<b.timeAdded)return-1;if(a.timeAdded>b.timeAdded)return 1}return null===a.timeCreated&&null!==b.timeCreated?1:null!==a.timeCreated&&null===b.timeCreated||a.timeCreated<b.timeCreated?-1:a.timeCreated>b.timeCreated?1:a.id<b.id?-1:a.id>b.id?1:0})),newState.messages=allMessages.filter((function(message,index,sortedMessages){return!index||message.id!=sortedMessages[index-1].id})),newState},updateMessages:function(state,data){var newState=cloneState(state),updatesById=data.reduce((function(carry,messageData){var oldMessage=messageData[0],newMessage=messageData[1],formattedMessage=formatMessages([newMessage],state.loggedInUserId,state.members)[0];return carry[oldMessage.id]=formattedMessage,carry}),{});return newState.messages=newState.messages.map((function(message){return message.id in updatesById?$.extend(message,updatesById[message.id]):message})),newState},removeMessages:function(state,messages){var newState=cloneState(state),removeMessageIds=messages.map((function(message){return""+message.id}));return newState.messages=newState.messages.filter((function(message){return removeMessageIds.indexOf(message.id)<0})),newState},removeMessagesById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.messages=newState.messages.filter((function(message){return messageIds.indexOf(message.id)<0})),newState},addMembers:function(state,members){var newState=cloneState(state),formattedMembers=function(members){return members.map((function(member){return{id:member.id,fullname:member.fullname,profileurl:member.profileurl,profileimageurl:member.profileimageurl,profileimageurlsmall:member.profileimageurlsmall,isonline:member.isonline,showonlinestatus:member.showonlinestatus,isblocked:member.isblocked,iscontact:member.iscontact,isdeleted:member.isdeleted,canmessage:member.canmessage,canmessageevenifblocked:member.canmessageevenifblocked,requirescontact:member.requirescontact,contactrequests:member.contactrequests||[]}}))}(members);return formattedMembers.forEach((function(member){newState.members[member.id]=member})),newState},removeMembers:function(state,members){var newState=cloneState(state);return members.forEach((function(member){delete newState.members[member.id]})),newState},setLoadingMessages:function(state,value){var newState=cloneState(state);return newState.loadingMessages=value,state.loadingMessages&&!value&&(newState.hasTriedToLoadMessages=!0),newState},setLoadingMembers:function(state,value){var newState=cloneState(state);return newState.loadingMembers=value,newState},setId:function(state,value){var newState=cloneState(state);return newState.id=value,newState},setName:function(state,value){var newState=cloneState(state);return newState.name=value,newState},setSubname:function(state,value){var newState=cloneState(state);return newState.subname=value,newState},setType:function(state,type){var newState=cloneState(state);return newState.type=type,newState},setIsFavourite:function(state,isFavourite){var newState=cloneState(state);return newState.isFavourite=isFavourite,newState},setIsMuted:function(state,isMuted){var newState=cloneState(state);return newState.isMuted=isMuted,newState},setCanDeleteMessagesForAllUsers:function(state,value){var newState=cloneState(state);return newState.canDeleteMessagesForAllUsers=value,newState},setDeleteMessagesForAllUsers:function(state,value){var newState=cloneState(state);return newState.deleteMessagesForAllUsers=value,newState},setTotalMemberCount:function(state,count){var newState=cloneState(state);return newState.totalMemberCount=count,newState},setImageUrl:function(state,url){var newState=cloneState(state);return newState.imageUrl=url,newState},setLoadingConfirmAction:function(state,value){var newState=cloneState(state);return newState.loadingConfirmAction=value,newState},setPendingDeleteConversation:function(state,value){var newState=cloneState(state);return newState.pendingDeleteConversation=value,newState},setMessagesSendPendingById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.messages.forEach((function(message){messageIds.indexOf(message.id)>=0&&(message.sendState="pending",message.errorMessage=null)})),newState},setMessagesSendSuccessById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.messages.forEach((function(message){messageIds.indexOf(message.id)>=0&&(message.sendState="sent",message.errorMessage=null)})),newState},setMessagesSendFailById:function(state,messageIds,errorMessage){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.messages.forEach((function(message){messageIds.indexOf(message.id)>=0&&(message.sendState="error",message.errorMessage=errorMessage)})),newState},setShowEmojiAutoComplete:function(state,show){var newState=cloneState(state);return newState.showEmojiAutoComplete=show,newState},setShowEmojiPicker:function(state,show){var newState=cloneState(state);return newState.showEmojiPicker=show,newState},addPendingBlockUsersById:function(state,userIds){var newState=cloneState(state);return userIds.forEach((function(id){newState.pendingBlockUserIds.push(id)})),newState},addPendingRemoveContactsById:function(state,userIds){var newState=cloneState(state);return userIds.forEach((function(id){newState.pendingRemoveContactIds.push(id)})),newState},addPendingUnblockUsersById:function(state,userIds){var newState=cloneState(state);return userIds.forEach((function(id){newState.pendingUnblockUserIds.push(id)})),newState},addPendingAddContactsById:function(state,userIds){var newState=cloneState(state);return userIds.forEach((function(id){newState.pendingAddContactIds.push(id)})),newState},addPendingDeleteMessagesById:function(state,messageIds){var newState=cloneState(state);return messageIds.forEach((function(id){newState.pendingDeleteMessageIds.push(id)})),newState},removePendingBlockUsersById:function(state,userIds){var newState=cloneState(state);return newState.pendingBlockUserIds=newState.pendingBlockUserIds.filter((function(id){return userIds.indexOf(id)<0})),newState},removePendingRemoveContactsById:function(state,userIds){var newState=cloneState(state);return newState.pendingRemoveContactIds=newState.pendingRemoveContactIds.filter((function(id){return userIds.indexOf(id)<0})),newState},removePendingUnblockUsersById:function(state,userIds){var newState=cloneState(state);return newState.pendingUnblockUserIds=newState.pendingUnblockUserIds.filter((function(id){return userIds.indexOf(id)<0})),newState},removePendingAddContactsById:function(state,userIds){var newState=cloneState(state);return newState.pendingAddContactIds=newState.pendingAddContactIds.filter((function(id){return userIds.indexOf(id)<0})),newState},removePendingDeleteMessagesById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.pendingDeleteMessageIds=newState.pendingDeleteMessageIds.filter((function(id){return messageIds.indexOf(id)<0})),newState},addSelectedMessagesById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.selectedMessageIds=newState.selectedMessageIds.concat(messageIds),newState},removeSelectedMessagesById:function(state,messageIds){var newState=cloneState(state);return messageIds=messageIds.map((function(id){return""+id})),newState.selectedMessageIds=newState.selectedMessageIds.filter((function(id){return messageIds.indexOf(id)<0})),newState},markMessagesAsRead:function(state,readMessages){var newState=cloneState(state),readMessageIds=readMessages.map((function(message){return message.id}));return newState.messages=newState.messages.map((function(message){return readMessageIds.indexOf(message.id)>=0&&(message.isRead=!0),message})),newState},addContactRequests:function(state,requests){var newState=cloneState(state);return requests.forEach((function(request){var fromUserId=request.userid,toUserId=request.requesteduserid;newState.members[fromUserId].contactrequests.push(request),newState.members[toUserId].contactrequests.push(request)})),newState},removeContactRequests:function(state,requests){var newState=cloneState(state);return requests.forEach((function(request){var fromUserId=request.userid,toUserId=request.requesteduserid;newState.members[fromUserId].contactrequests=newState.members[fromUserId].contactrequests.filter((function(existing){return existing.userid!=fromUserId})),newState.members[toUserId].contactrequests=newState.members[toUserId].contactrequests.filter((function(existing){return existing.requesteduserid!=toUserId}))})),newState}}})); /** * Controls the group info page of the message drawer. * * @module core_message/message_drawer_view_group_info * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_group_info",["jquery","core/str","core/templates","core_message/message_repository","core_message/message_drawer_lazy_load_list"],(function($,Str,Templates,Repository,LazyLoadList){var SELECTORS_CONTENT_CONTAINER='[data-region="group-info-content-container"]',TEMPLATES_CONTENT="core_message/message_drawer_view_group_info_body_content",TEMPLATES_MEMBERS_LIST="core_message/message_drawer_view_group_info_participants_list",getContentContainer=function(root){return root.find(SELECTORS_CONTENT_CONTAINER)},renderMembersCallback=function(contentContainer,members){return Templates.render(TEMPLATES_MEMBERS_LIST,{contacts:members}).then((function(html){return contentContainer.append(html),html}))};return{show:function(namespace,header,body,footer,conversation,loggedInUserId){var root=$(body);return getContentContainer(root).empty(),function(root,conversation,loggedInUserId){var placeholderCount=conversation.totalMemberCount>50?50:conversation.totalMemberCount,placeholders=Array.apply(null,Array(placeholderCount)).map((function(){return!0})),templateContext={name:conversation.name,subname:conversation.subname,imageurl:conversation.imageUrl,placeholders:placeholders,loggedinuser:{id:loggedInUserId}};return Templates.render(TEMPLATES_CONTENT,templateContext).then((function(html){return getContentContainer(root).append(html),html}))}(root,conversation,loggedInUserId).then((function(){var listRoot=LazyLoadList.getRoot(root);LazyLoadList.show(listRoot,function(conversation,limit,offset){return function(root,userId){return Repository.getConversationMembers(conversation.id,userId,limit+1,offset).then((function(members){return members.length>limit?members=members.slice(0,-1):LazyLoadList.setLoadedAll(root,!0),offset+=limit,members.filter((function(member){return member.id!=userId}))}))}}(conversation,50,0),renderMembersCallback)}))},description:function(root,conversation){return Str.get_string("messagedrawerviewgroupinfo","core_message",conversation.name)}}})); /** * Controls the overview page of the message drawer. * * @module core_message/message_drawer_view_overview * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_overview",["jquery","core/key_codes","core/pubsub","core/str","core_message/message_drawer_router","core_message/message_drawer_routes","core_message/message_drawer_events","core_message/message_drawer_view_overview_section","core_message/message_repository","core_message/message_drawer_view_conversation_constants"],(function($,KeyCodes,PubSub,Str,Router,Routes,MessageDrawerEvents,Section,MessageRepository,Constants){var SELECTORS_CONTACT_REQUEST_COUNT='[data-region="contact-request-count"]',SELECTORS_FAVOURITES='[data-region="view-overview-favourites"]',SELECTORS_GROUP_MESSAGES='[data-region="view-overview-group-messages"]',SELECTORS_MESSAGES='[data-region="view-overview-messages"]',SELECTORS_SEARCH_INPUT='[data-region="view-overview-search-input"]',SELECTORS_SECTION_TOGGLE_BUTTON="[data-toggle]",OVERVIEW_SECTION_TYPES={PRIVATE:[Constants.CONVERSATION_TYPES.PRIVATE,Constants.CONVERSATION_TYPES.SELF],PUBLIC:[Constants.CONVERSATION_TYPES.PUBLIC],FAVOURITE:null},loadAllCountsPromise=null,filterCountsByTypes=function(counts,types,includeFavourites){var total=0;return types&&types.length&&(total=types.reduce((function(carry,type){return carry+counts.types[type]}),total)),includeFavourites&&(total+=counts.favourites),total},getSearchInput=function(header){return header.find(SELECTORS_SEARCH_INPUT)},decrementContactRequestCount=function(header){return function(){var countContainer=header.find(SELECTORS_CONTACT_REQUEST_COUNT),count=parseInt(countContainer.text(),10);(count=isNaN(count)?0:count-1)<=0?countContainer.addClass("hidden"):countContainer.text(count)}};return{show:function(namespace,header,body){header.attr("data-init")||(!function(namespace,header){var searchInput=getSearchInput(header),ignoredKeys=[KeyCodes.tab,KeyCodes.shift,KeyCodes.ctrl,KeyCodes.alt];searchInput.on("click",(function(){Router.go(namespace,Routes.VIEW_SEARCH)})),searchInput.on("keydown",(function(e){ignoredKeys.indexOf(e.keyCode)<0&&"Meta"!=e.key&&Router.go(namespace,Routes.VIEW_SEARCH)})),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,decrementContactRequestCount(header)),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,decrementContactRequestCount(header))}(namespace,header),header.attr("data-init",!0));var fromPanel=header.attr("data-in-panel")?"frompanel":null;getSearchInput(header).val("");var loggedInUserId=function(body){return body.attr("data-user-id")}(body),allCounts=function(loggedInUserId){return null===loadAllCountsPromise&&(loadAllCountsPromise=MessageRepository.getAllConversationCounts(loggedInUserId)),loadAllCountsPromise}(loggedInUserId),sections=[[body.find(SELECTORS_FAVOURITES),OVERVIEW_SECTION_TYPES.FAVOURITE,!0],[body.find(SELECTORS_GROUP_MESSAGES),OVERVIEW_SECTION_TYPES.PUBLIC,!1],[body.find(SELECTORS_MESSAGES),OVERVIEW_SECTION_TYPES.PRIVATE,!1]];return sections.forEach((function(args){var sectionRoot=args[0],sectionTypes=args[1],includeFavourites=args[2],totalCountPromise=allCounts.then((function(result){return filterCountsByTypes(result.total,sectionTypes,includeFavourites)})),unreadCountPromise=allCounts.then((function(result){return filterCountsByTypes(result.unread,sectionTypes,includeFavourites)}));Section.show(namespace,null,sectionRoot,null,sectionTypes,includeFavourites,totalCountPromise,unreadCountPromise,fromPanel)})),allCounts.then((function(result){return function(sections){sections.some((function(section){var sectionRoot=section[0];return Section.isVisible(sectionRoot)}))||(sections.sort((function(a,b){var aTotal=a[1],aUnread=a[2],bTotal=b[1],bUnread=b[2];return aUnread>0&&0==bUnread?-1:0==aUnread&&bUnread>0?1:aTotal>0&&0==bTotal?-1:0==aTotal&&bTotal>0?1:0})),sections[0][0].find(SELECTORS_SECTION_TOGGLE_BUTTON).click())}(sections.map((function(section){var sectionRoot=section[0],sectionTypes=section[1],includeFavourites=section[2];return[sectionRoot,filterCountsByTypes(result.total,sectionTypes,includeFavourites),filterCountsByTypes(result.unread,sectionTypes,includeFavourites)]})))}))},description:function(){return Str.get_string("messagedrawerviewoverview","core_message")}}})); /** * Controls a section of the overview page in the message drawer. * * @module core_message/message_drawer_view_overview_section * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_overview_section",["jquery","core/custom_interaction_events","core/notification","core/pubsub","core/str","core/pending","core/templates","core/user_date","core_message/message_repository","core_message/message_drawer_events","core_message/message_drawer_router","core_message/message_drawer_routes","core_message/message_drawer_lazy_load_list","core_message/message_drawer_view_conversation_constants"],(function($,CustomEvents,Notification,PubSub,Str,Pending,Templates,UserDate,MessageRepository,MessageDrawerEvents,MessageDrawerRouter,MessageDrawerRoutes,LazyLoadList,MessageDrawerViewConversationContants){var SELECTORS_TOGGLE='[data-region="toggle"]',SELECTORS_CONVERSATION="[data-conversation-id]",SELECTORS_BLOCKED_ICON_CONTAINER='[data-region="contact-icon-blocked"]',SELECTORS_MUTED_ICON_CONTAINER='[data-region="muted-icon-container"]',SELECTORS_UNREAD_COUNT='[data-region="unread-count"]',SELECTORS_SECTION_TOTAL_COUNT='[data-region="section-total-count"]',SELECTORS_SECTION_TOTAL_COUNT_CONTAINER='[data-region="section-total-count-container"]',SELECTORS_SECTION_UNREAD_COUNT='[data-region="section-unread-count"]',SELECTORS_PLACEHOLDER_CONTAINER='[data-region="placeholder-container"]',TEMPLATES_CONVERSATIONS_LIST="core_message/message_drawer_conversations_list",TEMPLATES_CONVERSATIONS_LIST_ITEMS_PLACEHOLDER="core_message/message_drawer_conversations_list_items_placeholder",loadedConversationsById={},deletedConversationsById={},loadedTotalCounts=!1,loadedUnreadCounts=!1,isVisible=function(root){return LazyLoadList.getRoot(root).hasClass("show")},setExpanded=function(root){root.addClass("expanded")},formatConversationFromEvent=function(conversation){var recursivelyLowercaseKeys=function(object){return Object.keys(object).reduce((function(carry,key){return $.isArray(object[key])?carry[key.toLowerCase()]=object[key].map(recursivelyLowercaseKeys):carry[key.toLowerCase()]=object[key],carry}),{})},formatted=recursivelyLowercaseKeys(conversation);return formatted.messages=formatted.messages.map((function(message){return message.useridfrom=message.userfrom.id,message})),formatted},render=function(conversations,userId){var pending=new Pending,mapPromises=conversations.map((function(conversation){var lastMessage=conversation.messages.length?conversation.messages[conversation.messages.length-1]:null;return async function(lastMessage){if(!lastMessage)return null;var tmpElement=document.createElement("element");if(tmpElement.innerHTML=lastMessage.text.replace(/<img /g,"<noimg "),!tmpElement.querySelector("[src]")){var messagePreview=$(lastMessage.text).text();if(messagePreview&&-1==messagePreview.indexOf("<"))return messagePreview}var pix="i/messagecontentmultimediageneral",label="messagecontentmultimediageneral";lastMessage.text.includes("<img")?(pix="i/messagecontentimage",label="messagecontentimage"):lastMessage.text.includes("<video")?(pix="i/messagecontentvideo",label="messagecontentvideo"):lastMessage.text.includes("<audio")&&(pix="i/messagecontentaudio",label="messagecontentaudio");try{var labelString=await Str.get_string(label,"core_message");return await Templates.renderPix(pix,"core",labelString)+" "+labelString}catch(error){return Notification.exception(error),null}}(lastMessage).then((function(messagePreview){var formattedConversation={id:conversation.id,imageurl:conversation.imageurl,name:conversation.name,subname:conversation.subname,unreadcount:conversation.unreadcount,ismuted:conversation.ismuted,lastmessagedate:lastMessage?lastMessage.timecreated:null,sentfromcurrentuser:lastMessage?lastMessage.useridfrom==userId:null,lastmessage:messagePreview},otherUser=null;return conversation.type==MessageDrawerViewConversationContants.CONVERSATION_TYPES.SELF?otherUser=conversation.members[0]:conversation.type==MessageDrawerViewConversationContants.CONVERSATION_TYPES.PRIVATE&&(otherUser=conversation.members.reduce((function(carry,member){return carry||member.id==userId||(carry=member),carry}),null)),null!==otherUser&&(formattedConversation.userid=otherUser.id,formattedConversation.showonlinestatus=otherUser.showonlinestatus,formattedConversation.isonline=otherUser.isonline,formattedConversation.isblocked=otherUser.isblocked),conversation.type==MessageDrawerViewConversationContants.CONVERSATION_TYPES.PUBLIC&&(formattedConversation.lastsendername=conversation.members.reduce((function(carry,member){return!carry&&lastMessage&&member.id==lastMessage.useridfrom&&(carry=member.fullname),carry}),null)),formattedConversation})).catch(Notification.exception)}));return Promise.all(mapPromises).then((function(formattedConversations){return formattedConversations.forEach((function(conversation){(new Date).toDateString()==new Date(1e3*conversation.lastmessagedate).toDateString()&&(conversation.istoday=!0)})),Templates.render(TEMPLATES_CONVERSATIONS_LIST,{conversations:formattedConversations})})).then((function(html,js){return pending.resolve(),$.Deferred().resolve(html,js)})).catch((function(error){pending.resolve(),Notification.exception(error)}))},getTotalConversationCountElement=function(root){return root.find(SELECTORS_SECTION_TOTAL_COUNT)},decrementTotalUnreadConversationCount=function(root){if(loadedUnreadCounts){var element=function(root){return root.find(SELECTORS_SECTION_UNREAD_COUNT)}(root),count=parseInt(element.text());count-=1,element.text(count),count<1&&element.addClass("hidden")}},getConversationElement=function(root,conversationId){return root.find('[data-conversation-id="'+conversationId+'"]')},getConversationElementFromUserId=function(root,userId){return root.find('[data-user-id="'+userId+'"]')},createNewConversationFromEvent=function(root,conversation,userId){if(!root.find(SELECTORS_CONVERSATION).length){var listRoot=LazyLoadList.getRoot(root);LazyLoadList.showContent(listRoot),LazyLoadList.hideEmptyMessage(listRoot)}return loadedConversationsById[conversation.id]=conversation,render([conversation],userId).then((function(html){return LazyLoadList.getContentContainer(root).prepend(html)})).then((function(){return function(root){if(loadedTotalCounts){var element=getTotalConversationCountElement(root),count=parseInt(element.text());count+=1,element.text(count)}}(root)})).catch(Notification.exception)},deleteConversation=function(root,conversationElement){if(conversationElement.remove(),function(root){if(loadedTotalCounts){var element=getTotalConversationCountElement(root),count=parseInt(element.text());count-=1,element.text(count)}}(root),!root.find(SELECTORS_CONVERSATION).length){var listRoot=LazyLoadList.getRoot(root);LazyLoadList.hideContent(listRoot),LazyLoadList.showEmptyMessage(listRoot)}},registerEventListeners=function(namespace,root,loadCallback,types,includeFavourites,fromPanel){var listRoot=LazyLoadList.getRoot(root),conversationBelongsToThisSection=function(conversation){var conversationType=parseInt(conversation.type,10);return!(types&&types.indexOf(conversationType)<0||includeFavourites&&!conversation.isFavourite||!includeFavourites&&conversation.isFavourite)},toggle=root.find(SELECTORS_TOGGLE);root.css("min-height",toggle.outerHeight()),root.on("show.bs.collapse",(function(){setExpanded(root),LazyLoadList.show(listRoot,loadCallback,(function(contentContainer,conversations,userId){return render(conversations,userId).then((function(html){return contentContainer.append(html),html})).catch(Notification.exception)}))})),root.on("hidden.bs.collapse",(function(){!function(root){root.removeClass("expanded")}(root)})),PubSub.subscribe(MessageDrawerEvents.CONTACT_BLOCKED,(function(userId){var conversationElement=getConversationElementFromUserId(root,userId);conversationElement.length&&function(conversationElement){conversationElement.find(SELECTORS_BLOCKED_ICON_CONTAINER).removeClass("hidden")}(conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONTACT_UNBLOCKED,(function(userId){var conversationElement=getConversationElementFromUserId(root,userId);conversationElement.length&&function(conversationElement){conversationElement.find(SELECTORS_BLOCKED_ICON_CONTAINER).addClass("hidden")}(conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_SET_MUTED,(function(conversation){var conversationId=conversation.id,conversationElement=getConversationElement(root,conversationId);conversationElement.length&&function(conversationElement){conversationElement.find(SELECTORS_MUTED_ICON_CONTAINER).removeClass("hidden")}(conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_UNSET_MUTED,(function(conversation){var conversationId=conversation.id,conversationElement=getConversationElement(root,conversationId);conversationElement.length&&function(conversationElement){conversationElement.find(SELECTORS_MUTED_ICON_CONTAINER).addClass("hidden")}(conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,(function(conversation){if(conversationBelongsToThisSection(conversation)){var pendingPromise=new Pending("core_message/message_drawer_view_overview_section:new"),loggedInUserId=conversation.loggedInUserId,conversationId=conversation.id,element=getConversationElement(root,conversationId);if(conversation=formatConversationFromEvent(conversation),element.length){var contentContainer=LazyLoadList.getContentContainer(root);render([conversation],loggedInUserId).then((function(html){deletedConversationsById[conversationId]&&conversation.messages[0].timeadded<deletedConversationsById[conversationId]||(contentContainer.prepend(html),element.remove())})).then(pendingPromise.resolve).catch(Notification.exception)}else conversation.messages.length?createNewConversationFromEvent(root,conversation,loggedInUserId).then(pendingPromise.resolve).catch():pendingPromise.resolve()}})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_DELETED,(function(conversationId){var conversationElement=getConversationElement(root,conversationId);delete loadedConversationsById[conversationId],deletedConversationsById[conversationId]=new Date,conversationElement.length&&deleteConversation(root,conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_READ,(function(conversationId){var conversationElement=getConversationElement(root,conversationId);conversationElement.length&&function(root,conversationElement){var unreadCount=conversationElement.find(SELECTORS_UNREAD_COUNT);unreadCount.text("0"),unreadCount.addClass("hidden"),decrementTotalUnreadConversationCount(root)}(root,conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_SET_FAVOURITE,(function(conversation){var conversationElement=null;conversationBelongsToThisSection(conversation)?(conversationElement=getConversationElement(root,conversation.id)).length||createNewConversationFromEvent(root,formatConversationFromEvent(conversation),conversation.loggedInUserId):(conversationElement=getConversationElement(root,conversation.id)).length&&deleteConversation(root,conversationElement)})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_UNSET_FAVOURITE,(function(conversation){var conversationElement=null;conversationBelongsToThisSection(conversation)?(conversationElement=getConversationElement(root,conversation.id)).length||createNewConversationFromEvent(root,formatConversationFromEvent(conversation),conversation.loggedInUserId):(conversationElement=getConversationElement(root,conversation.id)).length&&deleteConversation(root,conversationElement)})),CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_CONVERSATION,(function(e,data){var conversationId=$(e.target).closest(SELECTORS_CONVERSATION).attr("data-conversation-id"),conversation=loadedConversationsById[conversationId];MessageDrawerRouter.go(namespace,MessageDrawerRoutes.VIEW_CONVERSATION,conversation,fromPanel),data.originalEvent.preventDefault()}))};return{show:function(namespace,header,body,footer,types,includeFavourites,totalCountPromise,unreadCountPromise,fromPanel){var root=$(body);if(!root.attr("data-init")){var loadCallback=function(types,includeFavourites,offset){var type=null,includeSelfConversations=!0;if(types&&types.length){var nonSelfConversationTypes=types.filter((function(candidate){return candidate!=MessageDrawerViewConversationContants.CONVERSATION_TYPES.SELF}));includeSelfConversations=types.length!=nonSelfConversationTypes.length,type=nonSelfConversationTypes[0]}return function(root,userId){return MessageRepository.getConversations(userId,type,51,offset,includeFavourites,includeSelfConversations).then((function(response){var conversations=response.conversations;return conversations.length>50?conversations=conversations.slice(0,-1):LazyLoadList.setLoadedAll(root,!0),offset+=50,conversations.forEach((function(conversation){loadedConversationsById[conversation.id]=conversation})),conversations})).catch(Notification.exception)}}(types,includeFavourites,0);if(registerEventListeners(namespace,root,loadCallback,types,includeFavourites,fromPanel),isVisible(root)){setExpanded(root);var listRoot=LazyLoadList.getRoot(root);LazyLoadList.show(listRoot,loadCallback,(function(contentContainer,conversations,userId){return render(conversations,userId).then((function(html){return contentContainer.append(html),html})).catch(Notification.exception)}))}totalCountPromise.then((function(count){!function(root,count){var container=root.find(SELECTORS_SECTION_TOTAL_COUNT_CONTAINER);container.find(SELECTORS_SECTION_TOTAL_COUNT).text(count),container.removeClass("hidden"),Str.get_string("totalconversations","core_message",count).done((function(string){container.attr("aria-label",string)}));var numPlaceholders=count>20?20:count,placeholders=Array.apply(null,Array(numPlaceholders)).map((function(){return!0}));Templates.render(TEMPLATES_CONVERSATIONS_LIST_ITEMS_PLACEHOLDER,{placeholders:placeholders}).then((function(html){root.find(SELECTORS_PLACEHOLDER_CONTAINER).html(html)})).catch((function(){}))}(root,count),loadedTotalCounts=!0})).catch((function(){})),unreadCountPromise.then((function(count){!function(root,count){var countElement=root.find(SELECTORS_SECTION_UNREAD_COUNT);countElement.text(count),Str.get_string("unreadconversations","core_message",count).done((function(string){countElement.attr("aria-label",string)})),count>0&&countElement.removeClass("hidden")}(root,count),loadedUnreadCounts=!0})).catch((function(){})),root.attr("data-init",!0)}},isVisible:isVisible}})); /** * Controls the search page of the message drawer. * * @module core_message/message_drawer_view_search * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_search",["jquery","core/custom_interaction_events","core/notification","core/pubsub","core/str","core/templates","core_message/message_repository","core_message/message_drawer_events"],(function($,CustomEvents,Notification,PubSub,Str,Templates,Repository,Events){var SELECTORS_BLOCK_ICON_CONTAINER='[data-region="block-icon-container"]',SELECTORS_CANCEL_SEARCH_BUTTON='[data-action="cancel-search"]',SELECTORS_CONTACTS_CONTAINER='[data-region="contacts-container"]',SELECTORS_CONTACTS_LIST='[data-region="contacts-container"] [data-region="list"]',SELECTORS_EMPTY_MESSAGE_CONTAINER='[data-region="empty-message-container"]',SELECTORS_LIST='[data-region="list"]',SELECTORS_LOADING_ICON_CONTAINER='[data-region="loading-icon-container"]',SELECTORS_LOADING_PLACEHOLDER='[data-region="loading-placeholder"]',SELECTORS_MESSAGES_LIST='[data-region="messages-container"] [data-region="list"]',SELECTORS_MESSAGES_CONTAINER='[data-region="messages-container"]',SELECTORS_NON_CONTACTS_CONTAINER='[data-region="non-contacts-container"]',SELECTORS_NON_CONTACTS_LIST='[data-region="non-contacts-container"] [data-region="list"]',SELECTORS_SEARCH_ICON_CONTAINER='[data-region="search-icon-container"]',SELECTORS_SEARCH_ACTION='[data-action="search"]',SELECTORS_SEARCH_INPUT='[data-region="search-input"]',SELECTORS_SEARCH_RESULTS_CONTAINER='[data-region="search-results-container"]',SELECTORS_LOAD_MORE_USERS='[data-action="load-more-users"]',SELECTORS_LOAD_MORE_MESSAGES='[data-action="load-more-messages"]',SELECTORS_BUTTON_TEXT='[data-region="button-text"]',SELECTORS_NO_RESULTS_CONTAINTER='[data-region="no-results-container"]',SELECTORS_ALL_CONTACTS_CONTAINER='[data-region="all-contacts-container"]',TEMPLATES_CONTACTS_LIST="core_message/message_drawer_contacts_list",TEMPLATES_NON_CONTACTS_LIST="core_message/message_drawer_non_contacts_list",TEMPLATES_MESSAGES_LIST="core_message/message_drawer_messages_list",getLoggedInUserId=function(body){return body.attr("data-user-id")},getEmptyMessageContainer=function(body){return body.find(SELECTORS_EMPTY_MESSAGE_CONTAINER)},getLoadingIconContainer=function(header){return header.find(SELECTORS_LOADING_ICON_CONTAINER)},getLoadingPlaceholder=function(body){return body.find(SELECTORS_LOADING_PLACEHOLDER)},getSearchIconContainer=function(header){return header.find(SELECTORS_SEARCH_ICON_CONTAINER)},getSearchInput=function(header){return header.find(SELECTORS_SEARCH_INPUT)},getSearchResultsContainer=function(body){return body.find(SELECTORS_SEARCH_RESULTS_CONTAINER)},getContactsContainer=function(body){return body.find(SELECTORS_CONTACTS_CONTAINER)},getNonContactsContainer=function(body){return body.find(SELECTORS_NON_CONTACTS_CONTAINER)},hideEmptyMessage=function(body){getEmptyMessageContainer(body).addClass("hidden")},hideLoadingIcon=function(header){getLoadingIconContainer(header).addClass("hidden")},hideLoadingPlaceholder=function(body){getLoadingPlaceholder(body).addClass("hidden")},showSearchIcon=function(header){getSearchIconContainer(header).removeClass("hidden")},hideSearchResults=function(body){getSearchResultsContainer(body).addClass("hidden")},clearAllSearchResults=function(body){body.find(SELECTORS_CONTACTS_LIST).empty(),body.find(SELECTORS_NON_CONTACTS_LIST).empty(),body.find(SELECTORS_MESSAGES_LIST).empty(),function(body){var container=getSearchResultsContainer(body);container.find(SELECTORS_ALL_CONTACTS_CONTAINER).removeClass("hidden"),container.find(SELECTORS_MESSAGES_CONTAINER).removeClass("hidden"),container.find(SELECTORS_NO_RESULTS_CONTAINTER).addClass("hidden")}(body),function(body){getSearchResultsContainer(body).find(SELECTORS_ALL_CONTACTS_CONTAINER).removeClass("hidden")}(body),function(body){getSearchResultsContainer(body).find(SELECTORS_CONTACTS_CONTAINER).removeClass("hidden")}(body),function(body){getSearchResultsContainer(body).find(SELECTORS_NON_CONTACTS_CONTAINER).removeClass("hidden")}(body),function(body){getSearchResultsContainer(body).find(SELECTORS_MESSAGES_CONTAINER).removeClass("hidden")}(body),showLoadMoreUsersButton(body),showLoadMoreMessagesButton(body)},startLoading=function(header,body){!function(header){getSearchIconContainer(header).addClass("hidden")}(header),hideEmptyMessage(body),hideSearchResults(body),function(header){getLoadingIconContainer(header).removeClass("hidden")}(header),function(body){getLoadingPlaceholder(body).removeClass("hidden")}(body),function(header){getSearchInput(header).prop("disabled",!0)}(header)},stopLoading=function(header,body){showSearchIcon(header),hideEmptyMessage(body),function(body){getSearchResultsContainer(body).removeClass("hidden")}(body),hideLoadingIcon(header),hideLoadingPlaceholder(body),function(header){getSearchInput(header).prop("disabled",!1)}(header)},hideUsersLoadingIcon=function(root){var button=root.find(SELECTORS_LOAD_MORE_USERS);button.prop("disabled",!1),button.find(SELECTORS_BUTTON_TEXT).removeClass("hidden"),button.find(SELECTORS_LOADING_ICON_CONTAINER).addClass("hidden")},showLoadMoreUsersButton=function(root){root.find(SELECTORS_LOAD_MORE_USERS).removeClass("hidden")},hideMessagesLoadingIcon=function(root){var button=root.find(SELECTORS_LOAD_MORE_MESSAGES);button.prop("disabled",!1),button.find(SELECTORS_BUTTON_TEXT).removeClass("hidden"),button.find(SELECTORS_LOADING_ICON_CONTAINER).addClass("hidden")},showLoadMoreMessagesButton=function(root){root.find(SELECTORS_LOAD_MORE_MESSAGES).removeClass("hidden")},findContact=function(root,userId){return root.find('[data-contact-user-id="'+userId+'"]')},highlightSearch=function(content,searchText){if(!content)return"";var regex=new RegExp("("+searchText+")","gi");return content.replace(regex,'<span class="matchtext">$1</span>')},renderMessages=function(root,messages){var container=root.find(SELECTORS_MESSAGES_CONTAINER),frompanel=root.attr("data-in-panel"),list=container.find(SELECTORS_LIST);return Templates.render(TEMPLATES_MESSAGES_LIST,{messages:messages,frompanel:frompanel}).then((function(html){return list.append(html),html}))},loadMoreUsers=function(root,loggedInUserId,text,limit,offset){var loadedAll=!1;return function(root){var button=root.find(SELECTORS_LOAD_MORE_USERS);button.prop("disabled",!0),button.find(SELECTORS_BUTTON_TEXT).addClass("hidden"),button.find(SELECTORS_LOADING_ICON_CONTAINER).removeClass("hidden")}(root),Repository.searchUsers(loggedInUserId,text,limit+1,offset).then((function(results){var contacts=results.contacts,noncontacts=results.noncontacts;return contacts.length<=limit&&noncontacts.length<=limit?(loadedAll=!0,{contacts:contacts,noncontacts:noncontacts}):{contacts:contacts.slice(0,limit),noncontacts:noncontacts.slice(0,limit)}})).then((function(results){var contactsCount=results.contacts.length,nonContactsCount=results.noncontacts.length;return contactsCount&&results.contacts.forEach((function(contact){contact.highlight=highlightSearch(contact.fullname,text)})),nonContactsCount&&results.noncontacts.forEach((function(contact){contact.highlight=highlightSearch(contact.fullname,text)})),$.when(!contactsCount||function(root,contacts){var container=getContactsContainer(root),frompanel=root.attr("data-in-panel"),list=container.find(SELECTORS_LIST);return Templates.render(TEMPLATES_CONTACTS_LIST,{contacts:contacts,frompanel:frompanel}).then((function(html){return list.append(html),html}))}(root,results.contacts),!nonContactsCount||function(root,nonContacts){var container=getNonContactsContainer(root),frompanel=root.attr("data-in-panel"),list=container.find(SELECTORS_LIST);return Templates.render(TEMPLATES_NON_CONTACTS_LIST,{noncontacts:nonContacts,frompanel:frompanel}).then((function(html){return list.append(html),html}))}(root,results.noncontacts)).then((function(){return{contactsCount:contactsCount,nonContactsCount:nonContactsCount}}))})).then((function(counts){return hideUsersLoadingIcon(root),loadedAll&&function(root){root.find(SELECTORS_LOAD_MORE_USERS).addClass("hidden")}(root),counts})).catch((function(error){throw hideUsersLoadingIcon(root),error}))},loadMoreMessages=function(root,loggedInUserId,text,limit,offset){var loadedAll=!1;return function(root){var button=root.find(SELECTORS_LOAD_MORE_MESSAGES);button.prop("disabled",!0),button.find(SELECTORS_BUTTON_TEXT).addClass("hidden"),button.find(SELECTORS_LOADING_ICON_CONTAINER).removeClass("hidden")}(root),Repository.searchMessages(loggedInUserId,text,limit+1,offset).then((function(results){var messages=results.contacts;return messages.length<=limit?(loadedAll=!0,messages):messages.slice(0,limit)})).then((function(messages){return messages.length?(messages.forEach((function(message){message.lastmessage=highlightSearch(message.lastmessage,text)})),renderMessages(root,messages).then((function(){return messages.length}))):messages.length})).then((function(count){return hideMessagesLoadingIcon(root),loadedAll&&function(root){root.find(SELECTORS_LOAD_MORE_MESSAGES).addClass("hidden")}(root),count})).catch((function(error){throw hideMessagesLoadingIcon(root),error}))},search=function(header,body,searchText,usersLimit,usersOffset,messagesLimit,messagesOffset){var loggedInUserId=getLoggedInUserId(body);return startLoading(header,body),clearAllSearchResults(body),$.when(loadMoreUsers(body,loggedInUserId,searchText,usersLimit,usersOffset),loadMoreMessages(body,loggedInUserId,searchText,messagesLimit,messagesOffset)).then((function(userCounts,messagesCount){var contactsCount=userCounts.contactsCount,nonContactsCount=userCounts.nonContactsCount;stopLoading(header,body),contactsCount||nonContactsCount||messagesCount?(contactsCount||nonContactsCount?(contactsCount||function(body){getSearchResultsContainer(body).find(SELECTORS_CONTACTS_CONTAINER).addClass("hidden")}(body),nonContactsCount||function(body){getSearchResultsContainer(body).find(SELECTORS_NON_CONTACTS_CONTAINER).addClass("hidden")}(body)):function(body){getSearchResultsContainer(body).find(SELECTORS_ALL_CONTACTS_CONTAINER).addClass("hidden")}(body),messagesCount||function(body){getSearchResultsContainer(body).find(SELECTORS_MESSAGES_CONTAINER).addClass("hidden")}(body)):function(body){var container=getSearchResultsContainer(body);container.find(SELECTORS_ALL_CONTACTS_CONTAINER).addClass("hidden"),container.find(SELECTORS_MESSAGES_CONTAINER).addClass("hidden"),container.find(SELECTORS_NO_RESULTS_CONTAINTER).removeClass("hidden")}(body)}))},registerEventListeners=function(header,body){var loggedInUserId=getLoggedInUserId(body),searchInput=getSearchInput(header),searchText="",messagesOffset=0,usersOffset=0,searchEventHandler=function(e,data){""!==(searchText=searchInput.val().trim())&&search(header,body,searchText,3,usersOffset=0,50,messagesOffset=0).then((function(){searchInput.focus(),usersOffset+=3,messagesOffset+=50})).catch(Notification.exception),data.originalEvent.preventDefault()};CustomEvents.define(searchInput,[CustomEvents.events.enter]),CustomEvents.define(header,[CustomEvents.events.activate]),CustomEvents.define(body,[CustomEvents.events.activate]),searchInput.on(CustomEvents.events.enter,searchEventHandler),header.on(CustomEvents.events.activate,SELECTORS_SEARCH_ACTION,searchEventHandler),body.on(CustomEvents.events.activate,SELECTORS_LOAD_MORE_MESSAGES,(function(e,data){""!==searchText&&loadMoreMessages(body,loggedInUserId,searchText,50,messagesOffset).then((function(){messagesOffset+=50})).catch(Notification.exception),data.originalEvent.preventDefault()})),body.on(CustomEvents.events.activate,SELECTORS_LOAD_MORE_USERS,(function(e,data){""!==searchText&&loadMoreUsers(body,loggedInUserId,searchText,50,usersOffset).then((function(){usersOffset+=50})).catch(Notification.exception),data.originalEvent.preventDefault()})),header.on(CustomEvents.events.activate,SELECTORS_CANCEL_SEARCH_BUTTON,(function(){!function(header){getSearchInput(header).val("")}(header),function(body){getEmptyMessageContainer(body).removeClass("hidden")}(body),showSearchIcon(header),hideSearchResults(body),hideLoadingIcon(header),hideLoadingPlaceholder(body),usersOffset=0,messagesOffset=0})),PubSub.subscribe(Events.CONTACT_ADDED,(function(userId){!function(root,contact){var nonContactsContainer=getNonContactsContainer(root),nonContact=findContact(nonContactsContainer,contact.userid);if(nonContact.length){nonContact.remove();var contactsContainer=getContactsContainer(root);contactsContainer.removeClass("hidden"),contactsContainer.find(SELECTORS_LIST).append(nonContact)}nonContactsContainer.find(SELECTORS_LIST).children().length||nonContactsContainer.addClass("hidden")}(body,userId)})),PubSub.subscribe(Events.CONTACT_REMOVED,(function(userId){!function(root,userId){var contactsContainer=getContactsContainer(root),contact=findContact(contactsContainer,userId);if(contact.length){contact.remove();var nonContactsContainer=getNonContactsContainer(root);nonContactsContainer.removeClass("hidden"),nonContactsContainer.find(SELECTORS_LIST).append(contact)}contactsContainer.find(SELECTORS_LIST).children().length||contactsContainer.addClass("hidden")}(body,userId)})),PubSub.subscribe(Events.CONTACT_BLOCKED,(function(userId){!function(root,userId){var contact=findContact(root,userId);contact.length&&contact.find(SELECTORS_BLOCK_ICON_CONTAINER).removeClass("hidden")}(body,userId)})),PubSub.subscribe(Events.CONTACT_UNBLOCKED,(function(userId){!function(root,userId){var contact=findContact(root,userId);contact.length&&contact.find(SELECTORS_BLOCK_ICON_CONTAINER).addClass("hidden")}(body,userId)}))};return{show:function(namespace,header,body){return body.attr("data-init")||(registerEventListeners(header,body),body.attr("data-init",!0)),getSearchInput(header).focus(),$.Deferred().resolve().promise()},description:function(namespace,header){if("object"!=typeof header)return Str.get_string("messagedrawerviewsearch","core_message");var searchText=getSearchInput(header).val().trim();return Str.get_string("messagedrawerviewsearch","core_message",searchText)}}})); /** * Controls the settings page in the message drawer. * * @module core_message/message_drawer_view_settings * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_drawer_view_settings",["jquery","core/notification","core/str","core/pubsub","core/templates","core_message/message_repository","core/custom_interaction_events","core_message/message_drawer_events"],(function($,Notification,Str,PubSub,Templates,Repository,CustomEvents,MessageDrawerEvents){var SELECTORS_CHECKBOX='input[type="checkbox"]',SELECTORS_SETTINGS='[data-region="settings"]',SELECTORS_PRIVACY_PREFERENCE='[data-preference="blocknoncontacts"] input[type="radio"]',SELECTORS_NOTIFICATIONS_PREFERENCE='[data-preference="notifications"] input[type="checkbox"]',SELECTORS_ENTER_TO_SEND_PREFERENCE='[data-preference="entertosend"] input[type="checkbox"]',SELECTORS_NOTIFICATION_PREFERENCES_CONTAINER='[data-region="notification-preference-container"]',SELECTORS_CONTENT_CONTAINER='[data-region="content-container"]',SELECTORS_PLACEHOLDER_CONTAINER='[data-region="placeholder-container"]',TEMPLATES_NOTIFICATION_PREFERENCES="core_message/message_drawer_view_settings_body_content_notification_preferences",savePreferences=function(loggedInUserId,preferences){return Repository.savePreferences(loggedInUserId,preferences).then((function(){PubSub.publish(MessageDrawerEvents.PREFERENCES_UPDATED,preferences)})).catch(Notification.exception)},init=function(body,loggedInUserId){Repository.getUserMessagePreferences(loggedInUserId).then((function(response){!function(body,value){body.find(SELECTORS_PRIVACY_PREFERENCE).each((function(index,input){(input=$(input)).val()==value?input.prop("checked",!0):input.prop("checked",!1)}))}(body,response.blocknoncontacts),function(body,value){var checkbox=body.find(SELECTORS_ENTER_TO_SEND_PREFERENCE);value?checkbox.prop("checked",!0):checkbox.prop("checked",!1)}(body,response.entertosend);var notificationProcessors=[];response.preferences.components.length&&response.preferences.components.forEach((function(component){if(component.notifications.length&&component.notifications.filter((function(notification){return"message_provider_moodle_instantmessage"==notification.preferencekey})).length){var configuration=component.notifications[0];notificationProcessors=configuration.processors.map((function(processor){var checked=processor.enabled;return{displayname:processor.displayname,name:processor.name,checked:checked,locked:processor.locked,lockedmessage:processor.lockedmessage||null}}))}}));var container=body.find(SELECTORS_NOTIFICATION_PREFERENCES_CONTAINER);return!notificationProcessors.length||(container.removeClass("hidden"),Templates.render(TEMPLATES_NOTIFICATION_PREFERENCES,{processors:notificationProcessors}).then((function(html){return container.append(html),html})))})).then((function(){body.find(SELECTORS_CONTENT_CONTAINER).removeClass("hidden"),body.find(SELECTORS_PLACEHOLDER_CONTAINER).addClass("hidden"),function(body,loggedInUserId){var settingsContainer=body.find(SELECTORS_SETTINGS);CustomEvents.define(settingsContainer,[CustomEvents.events.activate]),settingsContainer.on(CustomEvents.events.activate,SELECTORS_NOTIFICATIONS_PREFERENCE,(function(e){var checkboxes=$(e.target).closest(SELECTORS_NOTIFICATION_PREFERENCES_CONTAINER).find(SELECTORS_CHECKBOX);if(checkboxes.length){var values=checkboxes.toArray().reduce((function(carry,checkbox){return(checkbox=$(checkbox)).prop("checked")&&carry.push(checkbox.attr("data-name")),carry}),[]),newValue=values.length?values.join(","):"none";savePreferences(loggedInUserId,[{type:"message_provider_moodle_instantmessage_enabled",value:newValue}])}})),settingsContainer.on("change",SELECTORS_PRIVACY_PREFERENCE,(function(e){var newValue=$(e.target).val();savePreferences(loggedInUserId,[{type:"message_blocknoncontacts",value:newValue}])})),settingsContainer.on(CustomEvents.events.activate,SELECTORS_ENTER_TO_SEND_PREFERENCE,(function(e){var newValue=$(e.target).prop("checked");savePreferences(loggedInUserId,[{type:"message_entertosend",value:newValue}])}))}(body,loggedInUserId)})).catch(Notification.exception)};return{show:function(namespace,header,body,footer,loggedInUserId){return body.attr("data-init")||(init(body,loggedInUserId),body.attr("data-init",!0)),$.Deferred().resolve().promise()},description:function(){return Str.get_string("messagedrawerviewsettings","core_message")}}})); /** * Controls the preference for an individual notification type on the * message preference page. * * @module core_message/message_notification_preference * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_notification_preference",["jquery","core_message/notification_preference"],(function($,NotificationPreference){var SELECTORS_PREFERENCE_KEY="[data-preference-key]",MessageNotificationPreference=function(element,userId){NotificationPreference.call(this,element,userId)};return(MessageNotificationPreference.prototype=Object.create(NotificationPreference.prototype)).constructor=MessageNotificationPreference,MessageNotificationPreference.prototype.getPreferenceKey=function(){return this.root.find(SELECTORS_PREFERENCE_KEY).attr("data-preference-key")},MessageNotificationPreference})); /** * Controls the message popover in the nav bar. * * @module core_message/message_popover * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_popover",["jquery","core/custom_interaction_events","core/pubsub","core_message/message_drawer_events"],(function($,CustomEvents,PubSub,MessageDrawerEvents){var SELECTORS_COUNT_CONTAINER='[data-region="count-container"]',handleDecrementConversationCount=function(button){return function(){var countContainer=button.find(SELECTORS_COUNT_CONTAINER),count=parseInt(countContainer.text(),10);isNaN(count)||!count||count<2?countContainer.addClass("hidden"):(count-=1,countContainer.text(count))}},registerEventListeners=function(button){CustomEvents.define(button,[CustomEvents.events.activate]),button.on(CustomEvents.events.activate,(function(e,data){var buttonid;buttonid=button.attr("id"),PubSub.publish(MessageDrawerEvents.TOGGLE_VISIBILITY,buttonid),button.focus(),data.originalEvent.preventDefault()})),PubSub.subscribe(MessageDrawerEvents.CONVERSATION_READ,handleDecrementConversationCount(button)),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,handleDecrementConversationCount(button)),PubSub.subscribe(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,handleDecrementConversationCount(button))};return{init:function(button){button=$(button),registerEventListeners(button)}}})); /** * Controls the message preference page. * * @module core_message/message_preferences * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_preferences",["jquery","core/ajax","core/notification","core_message/message_notification_preference","core/custom_interaction_events"],(function($,Ajax,Notification,MessageNotificationPreference,CustomEvents){var SELECTORS_PREFERENCE="[data-state]",SELECTORS_PREFERENCES_CONTAINER='[data-region="preferences-container"]',SELECTORS_CONTACTABLE_PRIVACY_CONTAINER='[data-region="privacy-setting-container"]',MessagePreferences=function(element){this.root=$(element),this.userId=this.root.find(SELECTORS_PREFERENCES_CONTAINER).attr("data-user-id"),this.registerEventListeners()};return MessagePreferences.prototype.preferencesDisabled=function(){return this.root.find(SELECTORS_PREFERENCES_CONTAINER).hasClass("disabled")},MessagePreferences.prototype.saveContactablePrivacySetting=function(){var container=this.root.find(SELECTORS_CONTACTABLE_PRIVACY_CONTAINER),value=$("input[type='radio']:checked").val();if(container.hasClass("loading"))return $.Deferred().resolve();container.addClass("loading");var request={methodname:"core_user_update_user_preferences",args:{userid:this.userId,preferences:[{type:container.attr("data-preference-key"),value:value}]}};return Ajax.call([request])[0].fail(Notification.exception).always((function(){container.removeClass("loading")}))},MessagePreferences.prototype.registerEventListeners=function(){CustomEvents.define(this.root,[CustomEvents.events.activate]),this.root.on("change",function(e){if("message_blocknoncontacts"==e.target.name)this.saveContactablePrivacySetting();else if(!this.preferencesDisabled()){var preferencesContainer=$(e.target).closest(SELECTORS_PREFERENCES_CONTAINER),preferenceElement=$(e.target).closest(SELECTORS_PREFERENCE),messagePreference=new MessageNotificationPreference(preferencesContainer,this.userId);preferenceElement.addClass("loading"),messagePreference.save().always((function(){preferenceElement.removeClass("loading")}))}}.bind(this))},MessagePreferences})); /** * Retrieves messages from the server. * * @module core_message/message_repository * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_repository",["jquery","core/ajax","core/notification","core_message/message_drawer_view_conversation_constants"],(function($,Ajax,Notification,Constants){var CONVERSATION_TYPES=Constants.CONVERSATION_TYPES,sendMessagesToUser=function(toUserId,messages){var request={methodname:"core_message_send_instant_messages",args:{messages:messages.map((function(message){return{touserid:toUserId,text:message}}))}};return Ajax.call([request])[0].then((function(results){var errors=results.reduce((function(carry,result){return result.errormessage&&carry.push(result.errormessage),carry}),[]);if(errors.length)throw new Error(errors.join("\n"));return results})).then((function(results){return results.map((function(result){return{id:result.msgid,text:result.text,timecreated:result.timecreated,useridfrom:result.useridfrom,conversationid:result.conversationid,candeletemessagesforallusers:result.candeletemessagesforallusers}}))}))},sendMessagesToConversation=function(conversationId,messages){var request={methodname:"core_message_send_messages_to_conversation",args:{conversationid:conversationId,messages:messages.map((function(message){return{text:message}}))}};return Ajax.call([request])[0]};return{countUnreadConversations:function(args){var request={methodname:"core_message_get_unread_conversations_count",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},getContacts:function(userId,limit,offset){var args={userid:userId};void 0!==limit&&(args.limitnum=limit),void 0!==offset&&(args.limitfrom=offset);var request={methodname:"core_message_get_user_contacts",args:args};return Ajax.call([request])[0]},blockUser:function(userId,blockedUserId){var requests=[{methodname:"core_message_block_user",args:{userid:userId,blockeduserid:blockedUserId}},{methodname:"core_message_get_member_info",args:{referenceuserid:userId,userids:[blockedUserId],includecontactrequests:!0,includeprivacyinfo:!0}}];return $.when.apply(null,Ajax.call(requests)).then((function(reponse1,profiles){return profiles.length?profiles[0]:{}}))},unblockUser:function(userId,unblockedUserId){var requests=[{methodname:"core_message_unblock_user",args:{userid:userId,unblockeduserid:unblockedUserId}},{methodname:"core_message_get_member_info",args:{referenceuserid:userId,userids:[unblockedUserId],includecontactrequests:!0,includeprivacyinfo:!0}}];return $.when.apply(null,Ajax.call(requests)).then((function(reponse1,profiles){return profiles.length?profiles[0]:{}}))},createContactRequest:function(userId,requestUserIds){var request={methodname:"core_message_create_contact_request",args:{userid:userId,requesteduserid:requestUserIds}};return Ajax.call([request])[0]},deleteContacts:function(userId,contactUserIds){var requests=[{methodname:"core_message_delete_contacts",args:{userid:userId,userids:contactUserIds}},{methodname:"core_message_get_member_info",args:{referenceuserid:userId,userids:contactUserIds,includecontactrequests:!0,includeprivacyinfo:!0}}];return $.when.apply(null,Ajax.call(requests)).then((function(response1,profiles){return profiles}))},getMessages:function(currentUserId,conversationId,limit,offset,newestFirst,timeFrom){var args={currentuserid:currentUserId,convid:conversationId,newest:!!newestFirst};void 0!==limit&&(args.limitnum=limit),void 0!==offset&&(args.limitfrom=offset),void 0!==timeFrom&&(args.timefrom=timeFrom);var request={methodname:"core_message_get_conversation_messages",args:args};return Ajax.call([request])[0]},searchUsers:function(userId,searchString,limit,offset){var args={userid:userId,search:searchString};void 0!==limit&&(args.limitnum=limit),void 0!==offset&&(args.limitfrom=offset);var request={methodname:"core_message_message_search_users",args:args};return Ajax.call([request])[0]},searchMessages:function(userId,searchString,limit,offset){var args={userid:userId,search:searchString};void 0!==limit&&(args.limitnum=limit),void 0!==offset&&(args.limitfrom=offset);var request={methodname:"core_message_data_for_messagearea_search_messages",args:args};return Ajax.call([request])[0]},sendMessagesToUser:sendMessagesToUser,sendMessageToUser:function(toUserId,text){return sendMessagesToUser(toUserId,[text]).then((function(results){return results[0]}))},sendMessagesToConversation:sendMessagesToConversation,sendMessageToConversation:function(conversationId,text){return sendMessagesToConversation(conversationId,[text]).then((function(result){return result[0]}))},savePreferences:function(userId,preferences){var request={methodname:"core_user_update_user_preferences",args:{userid:userId,preferences:preferences}};return Ajax.call([request])[0]},getPreferences:function(userId){var request={methodname:"core_user_get_user_preferences",args:{userid:userId}};return Ajax.call([request])[0]},deleteMessages:function(userId,messageIds){return $.when.apply(null,Ajax.call(messageIds.map((function(messageId){return{methodname:"core_message_delete_message",args:{messageid:messageId,userid:userId}}}))))},deleteMessagesForAllUsers:function(userId,messageIds){return $.when.apply(null,Ajax.call(messageIds.map((function(messageId){return{methodname:"core_message_delete_message_for_all_users",args:{messageid:messageId,userid:userId}}}))))},deleteConversation:function(userId,conversationId){var request={methodname:"core_message_delete_conversations_by_id",args:{userid:userId,conversationids:[conversationId]}};return Ajax.call([request])[0]},getContactRequests:function(userId){var request={methodname:"core_message_get_contact_requests",args:{userid:userId}};return Ajax.call([request])[0]},acceptContactRequest:function(sendingUserId,recipientUserId){var requests=[{methodname:"core_message_confirm_contact_request",args:{userid:sendingUserId,requesteduserid:recipientUserId}},{methodname:"core_message_get_member_info",args:{referenceuserid:recipientUserId,userids:[sendingUserId],includecontactrequests:!0,includeprivacyinfo:!0}}];return $.when.apply(null,Ajax.call(requests)).then((function(reponse1,profiles){return profiles.length?profiles[0]:{}}))},declineContactRequest:function(sendingUserId,recipientUserId){var requests=[{methodname:"core_message_decline_contact_request",args:{userid:sendingUserId,requesteduserid:recipientUserId}},{methodname:"core_message_get_member_info",args:{referenceuserid:recipientUserId,userids:[sendingUserId],includecontactrequests:!0,includeprivacyinfo:!0}}];return $.when.apply(null,Ajax.call(requests)).then((function(reponse1,profiles){return profiles.length?profiles[0]:{}}))},getConversation:function(loggedInUserId,conversationId,includeContactRequests,includePrivacyInfo,memberLimit,memberOffset,messageLimit,messageOffset,newestMessagesFirst){var args={userid:loggedInUserId,conversationid:conversationId};null!=includeContactRequests&&(args.includecontactrequests=includeContactRequests),null!=includePrivacyInfo&&(args.includeprivacyinfo=includePrivacyInfo),null!=memberLimit&&(args.memberlimit=memberLimit),null!=memberOffset&&(args.memberoffset=memberOffset),null!=messageLimit&&(args.messagelimit=messageLimit),null!=messageOffset&&(args.messageoffset=messageOffset),null!=newestMessagesFirst&&(args.newestmessagesfirst=newestMessagesFirst);var request={methodname:"core_message_get_conversation",args:args};return Ajax.call([request])[0]},getConversationBetweenUsers:function(loggedInUserId,otherUserId,includeContactRequests,includePrivacyInfo,memberLimit,memberOffset,messageLimit,messageOffset,newestMessagesFirst){var args={userid:loggedInUserId,otheruserid:otherUserId};null!=includeContactRequests&&(args.includecontactrequests=includeContactRequests),null!=includePrivacyInfo&&(args.includeprivacyinfo=includePrivacyInfo),null!=memberLimit&&(args.memberlimit=memberLimit),null!=memberOffset&&(args.memberoffset=memberOffset),null!=messageLimit&&(args.messagelimit=messageLimit),null!=messageOffset&&(args.messageoffset=messageOffset),null!=newestMessagesFirst&&(args.newestmessagesfirst=newestMessagesFirst);var request={methodname:"core_message_get_conversation_between_users",args:args};return Ajax.call([request])[0]},getSelfConversation:function(loggedInUserId,messageLimit,messageOffset,newestMessagesFirst){var args={userid:loggedInUserId};null!=messageLimit&&(args.messagelimit=messageLimit),null!=messageOffset&&(args.messageoffset=messageOffset),null!=newestMessagesFirst&&(args.newestmessagesfirst=newestMessagesFirst);var request={methodname:"core_message_get_self_conversation",args:args};return Ajax.call([request])[0]},getConversations:function(userId,type,limit,offset,favourites,mergeself){var args={userid:userId,type:type};null!=limit&&(args.limitnum=limit),null!=offset&&(args.limitfrom=offset),null!=favourites&&(args.favourites=favourites),null!=mergeself&&(args.mergeself=mergeself);var request={methodname:"core_message_get_conversations",args:args};return Ajax.call([request])[0].then((function(result){return result.conversations.length&&(result.conversations=result.conversations.map((function(conversation){if(conversation.type==CONVERSATION_TYPES.PRIVATE||conversation.type==CONVERSATION_TYPES.SELF){var otherUser=conversation.members.length?conversation.members[0]:null;otherUser&&(conversation.name=conversation.name?conversation.name:otherUser.fullname,conversation.imageurl=conversation.imageurl?conversation.imageurl:otherUser.profileimageurl)}return conversation}))),result}))},getConversationMembers:function(conversationId,loggedInUserId,limit,offset,includeContactRequests){var args={userid:loggedInUserId,conversationid:conversationId};null!=limit&&(args.limitnum=limit),null!=offset&&(args.limitfrom=offset),null!=includeContactRequests&&(args.includecontactrequests=includeContactRequests);var request={methodname:"core_message_get_conversation_members",args:args};return Ajax.call([request])[0]},setFavouriteConversations:function(userId,conversationIds){var request={methodname:"core_message_set_favourite_conversations",args:{userid:userId,conversations:conversationIds}};return Ajax.call([request])[0]},setMutedConversations:function(userId,conversationIds){var request={methodname:"core_message_mute_conversations",args:{userid:userId,conversationids:conversationIds}};return Ajax.call([request])[0]},unsetFavouriteConversations:function(userId,conversationIds){var request={methodname:"core_message_unset_favourite_conversations",args:{userid:userId,conversations:conversationIds}};return Ajax.call([request])[0]},unsetMutedConversations:function(userId,conversationIds){var request={methodname:"core_message_unmute_conversations",args:{userid:userId,conversationids:conversationIds}};return Ajax.call([request])[0]},getMemberInfo:function(referenceUserId,userIds,includeContactRequests,includePrivacyInfo){var args={referenceuserid:referenceUserId,userids:userIds};void 0!==includeContactRequests&&(args.includecontactrequests=includeContactRequests),void 0!==includePrivacyInfo&&(args.includeprivacyinfo=includePrivacyInfo);var request={methodname:"core_message_get_member_info",args:args};return Ajax.call([request])[0]},markAllConversationMessagesAsRead:function(userId,conversationId){var request={methodname:"core_message_mark_all_conversation_messages_as_read",args:{userid:userId,conversationid:conversationId}};return Ajax.call([request])[0]},getUserMessagePreferences:function(userId){var request={methodname:"core_message_get_user_message_preferences",args:{userid:userId}};return Ajax.call([request])[0]},getTotalConversationCounts:function(userId){var request={methodname:"core_message_get_conversation_counts",args:{userid:userId}};return Ajax.call([request])[0]},getUnreadConversationCounts:function(userId){var request={methodname:"core_message_get_unread_conversation_counts",args:{userid:userId}};return Ajax.call([request])[0]},getAllConversationCounts:function(userId){var requests=[{methodname:"core_message_get_conversation_counts",args:{userid:userId}},{methodname:"core_message_get_unread_conversation_counts",args:{userid:userId}}];return $.when.apply(null,Ajax.call(requests)).then((function(total,unread){return{total:total,unread:unread}}))}}})); define("core_message/message_send_bulk",["exports","core/str","core/modal_factory","core/templates","core/modal_events","core/ajax","core/notification"],(function(_exports,_str,_modal_factory,_templates,_modal_events,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Send bulk message to the given user ids. * * @module core_message/message_send_bulk * @copyright 2019 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.showModal=_exports.sendMessage=void 0,_modal_factory=_interopRequireDefault(_modal_factory),_templates=_interopRequireDefault(_templates),_modal_events=_interopRequireDefault(_modal_events),_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);_exports.showModal=function(users){let callback=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(!users.length)return Promise.resolve();let titlePromise=null;return titlePromise=1==users.length?(0,_str.get_string)("sendbulkmessagesingle","core_message"):(0,_str.get_string)("sendbulkmessage","core_message",users.length),_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,body:_templates.default.render("core_message/send_bulk_message",{}),title:titlePromise}).then((function(modal){return modal.setSaveButtonText(titlePromise),modal.getRoot().on(_modal_events.default.hidden,(function(){callback&&callback(),modal.getRoot().remove()})),modal.getRoot().on(_modal_events.default.save,(function(){let messageText=modal.getRoot().find("form textarea").val();sendMessage(messageText,users)})),modal.show(),modal}))};const sendMessage=(messageText,users)=>{let messages=[];return users.forEach((user=>{messages.push({touserid:user,text:messageText})})),_ajax.default.call([{methodname:"core_message_send_instant_messages",args:{messages:messages}}])[0].then((function(messageIds){return 1==messageIds.length?(0,_str.get_string)("sendbulkmessagesentsingle","core_message"):(0,_str.get_string)("sendbulkmessagesent","core_message",messageIds.length)})).then((function(msg){return _notification.default.addNotification({message:msg,type:"success"}),!0})).catch(_notification.default.exception)};_exports.sendMessage=sendMessage})); /** * Module to message a user from their profile page. * * @module core_message/message_user_button * @copyright 2019 Mark Nelson <markn@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/message_user_button",["jquery","core/custom_interaction_events","core_message/message_drawer_helper","core/templates"],(function($,CustomEvents,MessageDrawerHelper,Templates){var SELECTORS_MESSAGE_TEXTAREA='[data-region="send-message-txt"]',SELECTORS_MESSAGE_USER_BUTTON="#message-user-button",TEMPLATES_CONTENT="core_message/message_jumpto",getUserId=function(element){return parseInt(element.attr("data-userid"))},getConversationId=function(element){return parseInt(element.attr("data-conversationid"))};return{send:function(element){element=$(element);var args={conversationid:getConversationId(element),buttonid:$(element).attr("id"),userid:getUserId(element)};Templates.render(TEMPLATES_CONTENT,{}).then((function(html){element.after(html)})).then((function(){$(SELECTORS_MESSAGE_USER_BUTTON).next().focus((function(){$(SELECTORS_MESSAGE_TEXTAREA).focus()}))})),CustomEvents.define(element,[CustomEvents.events.activate]),element.on(CustomEvents.events.activate,(function(e,data){$(e.target).hasClass("active")?(MessageDrawerHelper.hide(),$(SELECTORS_MESSAGE_USER_BUTTON).next().attr("tabindex",-1)):($(SELECTORS_MESSAGE_USER_BUTTON).next().attr("tabindex",0),args.conversationid?MessageDrawerHelper.showConversation(args):MessageDrawerHelper.createConversationWithUser(args)),$(e.target).focus(),$(e.target).toggleClass("active"),e.preventDefault(),data.originalEvent.preventDefault()}))}}})); /** * Controls the preference for an individual notification type on the * message preference page. * * @module core_message/notification_preference * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/notification_preference",["jquery","core/ajax","core/notification","core_message/notification_processor"],(function($,Ajax,Notification,NotificationProcessor){const SELECTORS_PROCESSOR="[data-processor-name]",SELECTORS_STATE_INPUTS="[data-state] input",NotificationPreference=function(element,userId){this.root=$(element),this.userId=userId};return NotificationPreference.prototype.getPreferenceKey=function(){return this.root.attr("data-preference-key")},NotificationPreference.prototype.getEnabledPreferenceKey=function(){return this.getPreferenceKey()+"_enabled"},NotificationPreference.prototype.getProcessors=function(){return this.root.find(SELECTORS_PROCESSOR).map((function(index,element){return new NotificationProcessor($(element))}))},NotificationPreference.prototype.startLoading=function(){this.root.addClass("loading"),this.root.find(SELECTORS_STATE_INPUTS).prop("disabled",!0)},NotificationPreference.prototype.stopLoading=function(){this.root.removeClass("loading"),this.root.find(SELECTORS_STATE_INPUTS).prop("disabled",!1)},NotificationPreference.prototype.isLoading=function(){return this.root.hasClass("loading")},NotificationPreference.prototype.save=function(){if(this.isLoading())return $.Deferred().resolve();this.startLoading();let enabledValue="";this.getProcessors().each((function(index,processor){processor.isEnabled()&&(""===enabledValue?enabledValue=processor.getName():enabledValue+=","+processor.getName())})),""===enabledValue&&(enabledValue="none");const request={methodname:"core_user_update_user_preferences",args:{userid:this.userId,preferences:[{type:this.getEnabledPreferenceKey(),value:enabledValue}]}};return Ajax.call([request])[0].fail(Notification.exception).always(function(){this.stopLoading()}.bind(this))},NotificationPreference})); /** * Represents the notification processor (e.g. email, popup, jabber) * * @module core_message/notification_processor * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/notification_processor",["jquery"],(function($){const SELECTORS_STATE_INPUTS=".preference-state input.notification_enabled",NotificationProcessor=function(element){this.root=$(element)};return NotificationProcessor.prototype.getName=function(){return this.root.attr("data-processor-name")},NotificationProcessor.prototype.isEnabled=function(){return this.root.find(SELECTORS_STATE_INPUTS).prop("checked")},NotificationProcessor})); /** * Controls the preferences for the list of notification types on the * message preference page * * @module core_message/preferences_notifications_list_controller * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/preferences_notifications_list_controller",["jquery","core/ajax","core/notification","core/custom_interaction_events","core_message/notification_preference","core_message/notification_processor_settings","core/modal_factory"],(function($,Ajax,Notification,CustomEvents,NotificationPreference,NotificationProcessorSettings,ModalFactory){var SELECTORS_DISABLE_NOTIFICATIONS='[data-region="disable-notification-container"] [data-disable-notifications]',SELECTORS_DISABLE_NOTIFICATIONS_CONTAINER='[data-region="disable-notification-container"]',SELECTORS_PREFERENCE=".preference-state",SELECTORS_PREFERENCE_ROW='[data-region="preference-row"]',SELECTORS_PREFERENCE_INPUT=".preference-state input",SELECTORS_PROCESSOR_SETTING="[data-processor-setting]",PreferencesController=function(element){this.root=$(element),this.userId=this.root.attr("data-user-id"),this.registerEventListeners()};return PreferencesController.prototype.isDisabled=function(){return this.root.hasClass("disabled")},PreferencesController.prototype.setDisabled=function(){this.root.addClass("disabled"),this.root.find(SELECTORS_PREFERENCE_INPUT).prop("disabled",!0)},PreferencesController.prototype.setEnabled=function(){this.root.removeClass("disabled"),this.root.find(SELECTORS_PREFERENCE_INPUT).prop("disabled",!1)},PreferencesController.prototype.toggleDisableAllStatus=function(){var checkbox=$(SELECTORS_DISABLE_NOTIFICATIONS),container=$(SELECTORS_DISABLE_NOTIFICATIONS_CONTAINER),ischecked=checkbox.prop("checked");if(container.hasClass("loading"))return $.Deferred().resolve();container.addClass("loading");var request={methodname:"core_user_update_user_preferences",args:{userid:this.userId,emailstop:ischecked?1:0}};return Ajax.call([request])[0].done(function(){ischecked?this.setDisabled():this.setEnabled()}.bind(this)).always((function(){container.removeClass("loading")})).fail(Notification.exception)},PreferencesController.prototype.registerEventListeners=function(){var disabledNotificationsElement=$(SELECTORS_DISABLE_NOTIFICATIONS);CustomEvents.define(this.root,[CustomEvents.events.activate]),this.root.on("change",function(e){if(!this.isDisabled()){var preferenceElement=$(e.target).closest(SELECTORS_PREFERENCE),preferenceRow=$(e.target).closest(SELECTORS_PREFERENCE_ROW),preference=new NotificationPreference(preferenceRow,this.userId);preferenceElement.addClass("loading"),preference.save().always((function(){preferenceElement.removeClass("loading")}))}}.bind(this));var eventFormPromise=ModalFactory.create({type:NotificationProcessorSettings.TYPE});this.root.on(CustomEvents.events.activate,SELECTORS_PROCESSOR_SETTING,(function(e,data){var element=$(e.target).closest(SELECTORS_PROCESSOR_SETTING);data.originalEvent.preventDefault(),eventFormPromise.then((function(modal){modal.setUserId($(element).attr("data-user-id")),modal.setName($(element).attr("data-name")),modal.setContextId($(element).attr("data-context-id")),modal.setElement(element),modal.show(),e.stopImmediatePropagation()})).fail(Notification.exception)})),CustomEvents.define(disabledNotificationsElement,[CustomEvents.events.activate]),disabledNotificationsElement.on(CustomEvents.events.activate,function(){this.toggleDisableAllStatus()}.bind(this))},PreferencesController})); /** * Manages the processor form on the message preferences page. * * @module core_message/preferences_processor_form * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/preferences_processor_form",["jquery","core/ajax","core/notification"],(function($,Ajax,Notification){var ProcessorForm=function(element){this.root=$(element),this.userId=this.root.attr("data-user-id"),this.name=this.root.attr("data-processor-name"),this.root.find("form").on("submit",function(e){e.preventDefault(),this.save().done((function(){$(element).trigger("mpp:formsubmitted")}))}.bind(this))};return ProcessorForm.prototype.startLoading=function(){this.root.addClass("loading")},ProcessorForm.prototype.stopLoading=function(){this.root.removeClass("loading")},ProcessorForm.prototype.isLoading=function(){return this.root.hasClass("loading")},ProcessorForm.prototype.save=function(){if(this.isLoading())return $.Deferred();this.startLoading();var data=this.root.find("form").serializeArray(),request={methodname:"core_message_message_processor_config_form",args:{userid:this.userId,name:this.name,formvalues:data}};return Ajax.call([request])[0].fail(Notification.exception).always(function(){this.stopLoading()}.bind(this))},ProcessorForm})); /** * Module to add/remove contact using ajax. * * @module core_message/toggle_contact_button * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/toggle_contact_button",["jquery","core/ajax","core/templates","core/notification","core/custom_interaction_events"],(function($,Ajax,Templates,Notification,CustomEvents){var getUserId=function(element){return element.attr("data-userid")},getCurrentUserId=function(element){return element.attr("data-currentuserid")},displayTextLabel=function(element){return"1"==element.attr("data-display-text-label")},isLoading=function(element){return element.hasClass("loading")||element.attr("disabled")},sendRequest=function(element,request){return isLoading(element)?$.Deferred():(element.addClass("loading"),element.attr("disabled","disabled"),Ajax.call([request])[0].fail(Notification.exception).always((function(){element.removeClass("loading"),element.removeAttr("disabled")})))};return{enhance:function(element){(element=$(element)).children(".loading-icon").length||Templates.render("core/loading",{}).done((function(html,js){element.append(html,js)})),CustomEvents.define(element,[CustomEvents.events.activate]),element.on(CustomEvents.events.activate,(function(e,data){!function(element){return"1"==element.attr("data-is-contact")}(element)?function(element){if(!isLoading(element)){var request={methodname:"core_message_create_contact_request",args:{userid:getCurrentUserId(element),requesteduserid:getUserId(element)}};sendRequest(element,request).done((function(){!function(element){element.attr("data-is-contact","1")}(element);const templateContext={displaytextlabel:displayTextLabel(element)};Templates.render("message/remove_contact_button",templateContext).done((function(html,js){Templates.replaceNodeContents(element,html,js)}))}))}}(element):function(element){if(!isLoading(element)){var request={methodname:"core_message_delete_contacts",args:{userids:[getUserId(element)]}};sendRequest(element,request).done((function(){!function(element){element.attr("data-is-contact","0")}(element);const templateContext={displaytextlabel:displayTextLabel(element)};Templates.render("message/add_contact_button",templateContext).done((function(html,js){Templates.replaceNodeContents(element,html,js)}))}))}}(element),e.preventDefault(),data.originalEvent.preventDefault()}))}}})); /** * Load the settings for a message processor. * * @module core_message/notification_processor_settings * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_message/notification_processor_settings",["jquery","core/ajax","core/str","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/fragment"],(function($,Ajax,Str,Notification,CustomEvents,Modal,ModalRegistry,Fragment){var registered=!1,SELECTORS_SAVE_BUTTON='[data-action="save"]',SELECTORS_CANCEL_BUTTON='[data-action="cancel"]',SELECTORS_PROCESSOR="[data-processor-name]",SELECTORS_PREFERENCE_ROW='[data-region="preference-row"]',NotificationProcessorSettings=function(root){Modal.call(this,root),this.name=null,this.userId=null,this.contextId=null,this.element=null,this.saveButton=this.getFooter().find(SELECTORS_SAVE_BUTTON),this.cancelButton=this.getFooter().find(SELECTORS_CANCEL_BUTTON)};return NotificationProcessorSettings.TYPE="core_message-notification_processor_settings",(NotificationProcessorSettings.prototype=Object.create(Modal.prototype)).constructor=NotificationProcessorSettings,NotificationProcessorSettings.prototype.setUserId=function(id){this.userId=id},NotificationProcessorSettings.prototype.getUserId=function(){return this.userId},NotificationProcessorSettings.prototype.setElement=function(element){this.element=element},NotificationProcessorSettings.prototype.getElement=function(){return this.element},NotificationProcessorSettings.prototype.setName=function(name){this.name=name},NotificationProcessorSettings.prototype.getName=function(){return this.name},NotificationProcessorSettings.prototype.setContextId=function(id){this.contextId=id},NotificationProcessorSettings.prototype.getContextId=function(){return this.contextId},NotificationProcessorSettings.prototype.getForm=function(){return this.getBody().find("form")},NotificationProcessorSettings.prototype.disableButtons=function(){this.saveButton.prop("disabled",!0),this.cancelButton.prop("disabled",!0)},NotificationProcessorSettings.prototype.enableButtons=function(){this.saveButton.prop("disabled",!1),this.cancelButton.prop("disabled",!1)},NotificationProcessorSettings.prototype.loadTitleContent=function(){return this.titlePromise=Str.get_string("processorsettings","message"),this.setTitle(this.titlePromise),this.titlePromise},NotificationProcessorSettings.prototype.loadBodyContent=function(){this.disableButtons();var args={userid:this.getUserId(),type:this.getName()};return this.bodyPromise=Fragment.loadFragment("message","processor_settings",this.getContextId(),args),this.setBody(this.bodyPromise),this.bodyPromise.then(function(){this.enableButtons()}.bind(this)).fail(Notification.exception),this.bodyPromise},NotificationProcessorSettings.prototype.loadAllContent=function(){return $.when(this.loadTitleContent(),this.loadBodyContent())},NotificationProcessorSettings.prototype.show=function(){this.loadAllContent(),Modal.prototype.show.call(this)},NotificationProcessorSettings.prototype.hide=function(){Modal.prototype.hide.call(this),this.setContextId(null),this.setName(null),this.setUserId(null)},NotificationProcessorSettings.prototype.updateConfiguredStatus=function(){var processorHeader=$(this.getElement()).closest(SELECTORS_PROCESSOR);if(!processorHeader.hasClass("unconfigured"))return!1;var processorName=processorHeader.attr("data-processor-name"),request={methodname:"core_message_get_message_processor",args:{name:processorName,userid:this.userId}};return Ajax.call([request])[0].fail(Notification.exception).done((function(result){if(result.userconfigured){var notifications=$(SELECTORS_PREFERENCE_ROW+' [data-processor-name="'+processorName+'"]');processorHeader.removeClass("unconfigured"),notifications.removeClass("disabled")}}))},NotificationProcessorSettings.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_SAVE_BUTTON,function(e,data){this.getForm().submit(),data.originalEvent.preventDefault()}.bind(this)),this.getModal().on("mpp:formsubmitted",function(e){this.hide(),this.updateConfiguredStatus(),e.stopPropagation()}.bind(this)),this.getModal().on(CustomEvents.events.activate,SELECTORS_CANCEL_BUTTON,function(e,data){this.hide(),data.originalEvent.preventDefault(),e.stopPropagation()}.bind(this))},registered||(ModalRegistry.register(NotificationProcessorSettings.TYPE,NotificationProcessorSettings,"core/modal_save_cancel"),registered=!0),NotificationProcessorSettings})); define("core_payment/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={proceed:"core_payment-modal_gateways:proceed"},_exports.default})); define("core_payment/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Repository for payment subsystem. * * @module core_payment/repository * @copyright 2020 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getAvailableGateways=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.getAvailableGateways=(component,paymentArea,itemId)=>{const request={methodname:"core_payment_get_available_gateways",args:{component:component,paymentarea:paymentArea,itemid:itemId}};return _ajax.default.call([request])[0]}})); define("core_payment/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={elements:{gateways:'[data-region="gateways-container"] input[type="radio"]'},regions:{gatewaysContainer:'[data-region="gateways-container"]',costContainer:'[data-region="fee-breakdown-container"]'},values:{gateway:'[data-region="gateways-container"] input[type="radio"]:checked'}},_exports.default})); define("core_payment/gateways_modal",["exports","core/modal_factory","core/templates","core/str","./repository","./selectors","core/modal_events","core_payment/events","core/toast","core/notification","./modal_gateways"],(function(_exports,_modal_factory,_templates,_str,_repository,_selectors,_modal_events,_events,_toast,_notification,_modal_gateways){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modal_factory=_interopRequireDefault(_modal_factory),_templates=_interopRequireDefault(_templates),_selectors=_interopRequireDefault(_selectors),_modal_events=_interopRequireDefault(_modal_events),_events=_interopRequireDefault(_events),_notification=_interopRequireDefault(_notification),_modal_gateways=_interopRequireDefault(_modal_gateways);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const show=async function(rootNode){let{focusOnClose:focusOnClose=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const modal=await _modal_factory.default.create({type:_modal_gateways.default.TYPE,title:await(0,_str.get_string)("selectpaymenttype","core_payment"),body:await _templates.default.render("core_payment/gateways_modal",{})}),rootElement=modal.getRoot()[0];(0,_toast.addToastRegion)(rootElement),modal.show(),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy();try{focusOnClose.focus()}catch(e){}})),modal.getRoot().on(_events.default.proceed,(e=>{const gateway=(rootElement.querySelector(_selectors.default.values.gateway)||{value:""}).value;gateway?processPayment(gateway,rootNode.dataset.component,rootNode.dataset.paymentarea,rootNode.dataset.itemid,rootNode.dataset.description).then((message=>(modal.hide(),_notification.default.addNotification({message:message,type:"success"}),location.href=rootNode.dataset.successurl,message))).catch((message=>_notification.default.alert("",message))):(0,_str.get_string)("nogatewayselected","core_payment").then((message=>(0,_toast.add)(message,{type:"warning"}))).catch(),e.preventDefault()})),rootElement.addEventListener("change",(e=>{e.target.matches(_selectors.default.elements.gateways)&&updateCostRegion(rootElement,rootNode.dataset.cost)}));const gateways=await(0,_repository.getAvailableGateways)(rootNode.dataset.component,rootNode.dataset.paymentarea,rootNode.dataset.itemid),context={gateways:gateways},{html:html,js:js}=await _templates.default.renderForPromise("core_payment/gateways",context);_templates.default.replaceNodeContents(rootElement.querySelector(_selectors.default.regions.gatewaysContainer),html,js),selectSingleGateway(rootElement),await updateCostRegion(rootElement,rootNode.dataset.cost)},selectSingleGateway=root=>{const gateways=root.querySelectorAll(_selectors.default.elements.gateways);1==gateways.length&&(gateways[0].checked=!0)},updateCostRegion=async function(root){let defaultCost=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const gatewayElement=root.querySelector(_selectors.default.values.gateway),surcharge=parseInt((gatewayElement||{dataset:{surcharge:0}}).dataset.surcharge),cost=(gatewayElement||{dataset:{cost:defaultCost}}).dataset.cost,{html:html,js:js}=await _templates.default.renderForPromise("core_payment/fee_breakdown",{fee:cost,surcharge:surcharge});_templates.default.replaceNodeContents(root.querySelector(_selectors.default.regions.costContainer),html,js)},processPayment=async(gateway,component,paymentArea,itemId,description)=>(await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["paygw_".concat(gateway,"/gateways_modal")],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("paygw_".concat(gateway,"/gateways_modal"))):Promise.resolve(_systemImportTransformerGlobalIdentifier["paygw_".concat(gateway,"/gateways_modal")]))).process(component,paymentArea,itemId,description),init=()=>{init.initialised||(init.initialised=!0,document.addEventListener("click",(e=>{const gatewayTrigger=e.target.closest('[data-action="core_payment/triggerPayment"]');gatewayTrigger&&(e.preventDefault(),show(gatewayTrigger,{focusOnClose:e.target}))})))};_exports.init=init,init.initialised=!1})); define("core_payment/modal_gateways",["exports","jquery","core/custom_interaction_events","core/modal","core/modal_events","core_payment/events","core/modal_registry"],(function(_exports,_jquery,_custom_interaction_events,_modal,_modal_events,_events,_modal_registry){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Contain the logic for the gateways modal: A modal with proceed and cancel buttons. * * @module core_payment/modal_gateways * @copyright 2020 Shamim Rezaie <shamim@moodle.com> * @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),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_modal=_interopRequireDefault(_modal),_modal_events=_interopRequireDefault(_modal_events),_events=_interopRequireDefault(_events),_modal_registry=_interopRequireDefault(_modal_registry);let registered=!1;const SELECTORS_PROCEED_BUTTON='[data-action="proceed"]',SELECTORS_CANCEL_BUTTON='[data-action="cancel"]';class ModalGateways extends _modal.default{constructor(root){super(root)}registerEventListeners(){super.registerEventListeners(),this.getModal().on(_custom_interaction_events.default.events.activate,SELECTORS_PROCEED_BUTTON,((e,data)=>{var proceedEvent=_jquery.default.Event(_events.default.proceed);this.getRoot().trigger(proceedEvent,this),proceedEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())})),this.getModal().on(_custom_interaction_events.default.events.activate,SELECTORS_CANCEL_BUTTON,((e,data)=>{var cancelEvent=_jquery.default.Event(_modal_events.default.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}))}}return _exports.default=ModalGateways,ModalGateways.TYPE="core_payment-modal_gateways",registered||(_modal_registry.default.register(ModalGateways.TYPE,ModalGateways,"core_payment/modal_gateways"),registered=!0),_exports.default})); /** * A javascript module to handle question tags editing. * * @deprecated since Moodle 4.0 * @todo Final deprecation on Moodle 4.4 MDL-72438 * @module core_question/edit_tags * @copyright 2018 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_question/edit_tags",["jquery","core/fragment","core/str","core/modal_events","core/modal_factory","core/notification","core/custom_interaction_events","core_question/repository","core_question/selectors"],(function($,Fragment,Str,ModalEvents,ModalFactory,Notification,CustomEvents,Repository,QuestionSelectors){var enableSaveButton=function(root){root.find(QuestionSelectors.actions.save).prop("disabled",!1)},disableSaveButton=function(root){root.find(QuestionSelectors.actions.save).prop("disabled",!0)},startLoading=function(root){root.find(QuestionSelectors.containers.loadingIcon).removeClass("hidden")},stopLoading=function(root){root.find(QuestionSelectors.containers.loadingIcon).addClass("hidden")},save=function(modal,root){disableSaveButton(root),startLoading(root);var formData=function(modal){return modal.getBody().find("form").serialize()}(modal),questionId=function(modal){return modal.getBody().data("questionid")}(modal),contextId=function(modal){return modal.getBody().data("contextid")}(modal);return Repository.submitTagCreateUpdateForm(questionId,contextId,formData).always((function(){stopLoading(root),enableSaveButton(root)})).fail(Notification.exception)};return{init:function(root){window.console.warn("warn: The core_question/repository has been deprecated.Please use qbank_tagquestion/repository instead."),function(root){var modalPromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,large:!1},[root,QuestionSelectors.actions.edittags]).then((function(modal){return Str.get_string("questiontags","question").then((function(string){return modal.setTitle(string),string})).fail(Notification.exception),modal.getRoot().on(ModalEvents.save,(function(e){modal.getBody().find("form").submit(),e.preventDefault()})),modal.getRoot().on("submit","form",(function(e){save(modal,root).then((function(){modal.hide(),location.reload()})).fail(Notification.exception),e.preventDefault(),e.stopPropagation()})),modal}));root.on(CustomEvents.events.activate,QuestionSelectors.actions.edittags,(function(e){var currentTarget=$(e.currentTarget),questionId=currentTarget.data("questionid"),canTag=!!currentTarget.data("cantag"),contextId=currentTarget.data("contextid");modalPromise.then((function(modal){disableSaveButton(root),startLoading(root);var args={id:questionId},tagsFragment=Fragment.loadFragment("question","tags_form",contextId,args);return modal.setBody(tagsFragment),tagsFragment.then((function(){enableSaveButton(root)})).always((function(){stopLoading(root)})).fail(Notification.exception),canTag?modal.getRoot().find(QuestionSelectors.actions.save).show():modal.getRoot().find(QuestionSelectors.actions.save).hide(),function(modal,questionId){modal.getBody().attr("data-questionid",questionId)}(modal,questionId),function(modal,contextId){modal.getBody().attr("data-contextid",contextId)}(modal,contextId),modal})).fail(Notification.exception),e.preventDefault()}))}(root=$(root))}}})); /** * A javascript module to handle question ajax actions. * * @deprecated since Moodle 4.0 * @todo Final deprecation on Moodle 4.4 MDL-72438 * @module core_question/repository * @copyright 2017 Simey Lameze <lameze@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_question/repository",["jquery","core/ajax"],(function($,Ajax){return{submitTagCreateUpdateForm:function(questionId,contextId,formdata){window.console.warn("warn: The core_question/repository has been deprecated.Please use qbank_tagquestion/repository instead.");var request={methodname:"core_question_submit_tags_form",args:{questionid:questionId,contextid:contextId,formdata:formdata}};return Ajax.call([request])[0]}}})); /** * The purpose of this module is to centralize selectors related to question. * * @deprecated since Moodle 4.0 * @todo Final deprecation on Moodle 4.4 MDL-72438 * @module core_question/question_selectors * @copyright 2018 Simey Lameze <lameze@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_question/selectors",[],(function(){return window.console.warn("warn: The core_question/selectors has been deprecated. Please use qbank_tagquestion/selectors instead."),{actions:{save:'[data-action="save"]',edittags:'[data-action="edittags"]'},containers:{loadingIcon:'[data-region="overlay-icon-container"]'}}})); define("core_reportbuilder/local/editor/card_view",["exports","core_form/dynamicform","core/toast","core/str","core/pubsub","core/notification","core_reportbuilder/local/events","core_reportbuilder/local/selectors"],(function(_exports,_dynamicform,_toast,_str,_pubsub,_notification,reportEvents,reportSelectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_dynamicform=_interopRequireDefault(_dynamicform),_notification=_interopRequireDefault(_notification),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);let cardViewForm=null;_exports.init=initialized=>{(()=>{const cardViewFormContainer=document.querySelector(reportSelectors.regions.settingsCardView);cardViewFormContainer&&(cardViewForm=new _dynamicform.default(cardViewFormContainer,"\\core_reportbuilder\\form\\card_view"),cardViewForm.addEventListener(cardViewForm.events.FORM_SUBMITTED,(event=>{event.preventDefault(),(0,_str.get_string)("cardviewsettingssaved","core_reportbuilder").then(_toast.add).catch(_notification.default.exception)})))})(),initialized||(0,_pubsub.subscribe)(reportEvents.publish.reportColumnsUpdated,(()=>{const reportElement=document.querySelector(reportSelectors.regions.report);cardViewForm.load({reportid:reportElement.dataset.reportId})}))}})); define("core_reportbuilder/local/editor/columns",["exports","jquery","core/event_dispatcher","core/inplace_editable","core/local/inplace_editable/events","core/notification","core/pending","core/prefetch","core/pubsub","core/sortable_list","core/str","core/toast","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/columns","core_reportbuilder/local/repository/sorting"],(function(_exports,_jquery,_event_dispatcher,_inplace_editable,_events,_notification,_pending,_prefetch,_pubsub,_sortable_list,_str,_toast,reportEvents,reportSelectors,_columns,_sorting){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_sortable_list=_interopRequireDefault(_sortable_list),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);_exports.init=initialized=>{((0,_prefetch.prefetchStrings)("core_reportbuilder",["columnadded","columnaggregated","columndeleted","columnmoved","deletecolumn","deletecolumnconfirm"]),(0,_prefetch.prefetchStrings)("core",["delete"]),initialized)||(document.addEventListener("click",(event=>{const reportAddColumn=event.target.closest(reportSelectors.actions.reportAddColumn);if(reportAddColumn){event.preventDefault();const pendingPromise=new _pending.default("core_reportbuilder/columns:add"),reportElement=reportAddColumn.closest(reportSelectors.regions.report);(0,_columns.addColumn)(reportElement.dataset.reportId,reportAddColumn.dataset.uniqueIdentifier).then((data=>(0,_pubsub.publish)(reportEvents.publish.reportColumnsUpdated,data))).then((()=>(0,_str.get_string)("columnadded","core_reportbuilder",reportAddColumn.dataset.name))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)}const reportRemoveColumn=event.target.closest(reportSelectors.actions.reportRemoveColumn);if(reportRemoveColumn){event.preventDefault();const reportElement=reportRemoveColumn.closest(reportSelectors.regions.report),columnHeader=reportRemoveColumn.closest(reportSelectors.regions.columnHeader),columnName=columnHeader.dataset.columnName;_notification.default.saveCancelPromise((0,_str.get_string)("deletecolumn","core_reportbuilder",columnName),(0,_str.get_string)("deletecolumnconfirm","core_reportbuilder",columnName),(0,_str.get_string)("delete","core"),{triggerElement:reportRemoveColumn}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/columns:remove");return(0,_columns.deleteColumn)(reportElement.dataset.reportId,columnHeader.dataset.columnId).then((data=>(0,_pubsub.publish)(reportEvents.publish.reportColumnsUpdated,data))).then((()=>(0,_toast.add)((0,_str.get_string)("columndeleted","core_reportbuilder",columnName)))).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)})).catch((()=>{}))}})),new _sortable_list.default("".concat(reportSelectors.regions.reportTable," thead tr"),{isHorizontal:!0}).getElementName=element=>Promise.resolve(element.data("columnName")),(0,_jquery.default)(document).on(_sortable_list.default.EVENTS.DRAG,"".concat(reportSelectors.regions.report," th[data-column-id]"),((event,info)=>{const reportElement=event.target.closest(reportSelectors.regions.report),columnPosition=info.element.data("columnPosition"),targetColumnPosition=info.targetNextElement.data("columnPosition");(0,_jquery.default)(reportElement).find("tbody tr").each((function(){const cell=(0,_jquery.default)(this).children("td.c".concat(columnPosition-1))[0];if(targetColumnPosition){var beforeCell=(0,_jquery.default)(this).children("td.c".concat(targetColumnPosition-1))[0];this.insertBefore(cell,beforeCell)}else this.appendChild(cell)}))})),(0,_jquery.default)(document).on(_sortable_list.default.EVENTS.DROP,"".concat(reportSelectors.regions.report," th[data-column-id]"),((event,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_reportbuilder/columns:reorder"),reportElement=event.target.closest(reportSelectors.regions.report),columnId=info.element.data("columnId"),columnName=info.element.data("columnName"),columnPosition=info.element.data("columnPosition");let targetColumnPosition=info.targetNextElement.data("columnPosition")||info.element.siblings().length+2;targetColumnPosition>columnPosition&&targetColumnPosition--,(0,_columns.reorderColumn)(reportElement.dataset.reportId,columnId,targetColumnPosition).then((()=>(0,_str.get_string)("columnmoved","core_reportbuilder",columnName))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)}})),document.addEventListener(_events.eventTypes.elementUpdated,(event=>{const columnAggregation=event.target.closest('[data-itemtype="columnaggregation"]');if(columnAggregation){const pendingPromise=new _pending.default("core_reportbuilder/columns:aggregate"),reportElement=columnAggregation.closest(reportSelectors.regions.report),columnHeader=columnAggregation.closest(reportSelectors.regions.columnHeader);(0,_str.get_string)("columnaggregated","core_reportbuilder",columnHeader.dataset.columnName).then(_toast.add).then((()=>{const columnAggregationLink='[data-itemtype="columnaggregation"][data-itemid="'+"".concat(columnAggregation.dataset.itemid,'"] > a');return(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preserveTriggerElement:columnAggregationLink},reportElement),(0,_sorting.getColumnSorting)(reportElement.dataset.reportId)})).then((data=>(0,_pubsub.publish)(reportEvents.publish.reportColumnsUpdated,data))).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)}})))}})); define("core_reportbuilder/local/editor/conditions",["exports","jquery","core/custom_interaction_events","core/event_dispatcher","core/inplace_editable","core/notification","core/pending","core/prefetch","core/sortable_list","core/str","core/templates","core/toast","core_form/dynamicform","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/conditions"],(function(_exports,_jquery,_custom_interaction_events,_event_dispatcher,_inplace_editable,_notification,_pending,_prefetch,_sortable_list,_str,_templates,_toast,_dynamicform,reportEvents,reportSelectors,_conditions){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_sortable_list=_interopRequireDefault(_sortable_list),_templates=_interopRequireDefault(_templates),_dynamicform=_interopRequireDefault(_dynamicform),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);const reloadSettingsConditionsRegion=(reportElement,templateContext)=>{const pendingPromise=new _pending.default("core_reportbuilder/conditions:reload"),settingsConditionsRegion=reportElement.querySelector(reportSelectors.regions.settingsConditions);return _templates.default.renderForPromise("core_reportbuilder/local/settings/conditions",{conditions:templateContext}).then((_ref=>{let{html:html,js:js}=_ref;const conditionsjs=_jquery.default.parseHTML(templateContext.javascript,null,!0).map((node=>node.innerHTML)).join("\n");_templates.default.replaceNode(settingsConditionsRegion,html,js+conditionsjs),initConditionsForm();const reportAddCondition=reportElement.querySelector(reportSelectors.actions.reportAddCondition);return null==reportAddCondition||reportAddCondition.focus(),pendingPromise.resolve()}))},initConditionsForm=()=>{_custom_interaction_events.default.define(reportSelectors.actions.reportAddCondition,[_custom_interaction_events.default.events.accessibleChange]);const reportElement=document.querySelector(reportSelectors.regions.report),conditionFormContainer=reportElement.querySelector(reportSelectors.regions.settingsConditions);if(!conditionFormContainer)return;const conditionForm=new _dynamicform.default(conditionFormContainer,"\\core_reportbuilder\\form\\condition");conditionForm.addEventListener(conditionForm.events.FORM_SUBMITTED,(event=>{event.preventDefault(),(0,_str.get_string)("conditionsapplied","core_reportbuilder").then(_toast.add).catch(_notification.default.exception),(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement)})),conditionForm.addEventListener(conditionForm.events.NOSUBMIT_BUTTON_PRESSED,(event=>{event.preventDefault(),_notification.default.saveCancelPromise((0,_str.get_string)("resetconditions","core_reportbuilder"),(0,_str.get_string)("resetconditionsconfirm","core_reportbuilder"),(0,_str.get_string)("resetall","core_reportbuilder"),{triggerElement:event.detail}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/conditions:reset");return(0,_conditions.resetConditions)(reportElement.dataset.reportId).then((data=>reloadSettingsConditionsRegion(reportElement,data))).then((()=>(0,_toast.add)((0,_str.get_string)("conditionsreset","core_reportbuilder")))).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)})).catch((()=>{}))}))};_exports.init=initialized=>{((0,_prefetch.prefetchStrings)("core_reportbuilder",["conditionadded","conditiondeleted","conditionmoved","conditionsapplied","conditionsreset","deletecondition","deleteconditionconfirm","resetall","resetconditions","resetconditionsconfirm"]),(0,_prefetch.prefetchStrings)("core",["delete"]),initConditionsForm(),initialized)||((0,_jquery.default)(document).on(_custom_interaction_events.default.events.accessibleChange,reportSelectors.actions.reportAddCondition,(event=>{const reportAddCondition=event.target.closest(reportSelectors.actions.reportAddCondition);if(reportAddCondition){if(event.preventDefault(),0===reportAddCondition.selectedIndex)return;const reportElement=reportAddCondition.closest(reportSelectors.regions.report),pendingPromise=new _pending.default("core_reportbuilder/conditions:add");(0,_conditions.addCondition)(reportElement.dataset.reportId,reportAddCondition.value).then((data=>reloadSettingsConditionsRegion(reportElement,data))).then((()=>(0,_str.get_string)("conditionadded","core_reportbuilder",reportAddCondition.options[reportAddCondition.selectedIndex].text))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)}})),document.addEventListener("click",(event=>{const reportRemoveCondition=event.target.closest(reportSelectors.actions.reportRemoveCondition);if(reportRemoveCondition){event.preventDefault();const reportElement=reportRemoveCondition.closest(reportSelectors.regions.report),conditionContainer=reportRemoveCondition.closest(reportSelectors.regions.activeCondition),conditionName=conditionContainer.dataset.conditionName;_notification.default.saveCancelPromise((0,_str.get_string)("deletecondition","core_reportbuilder",conditionName),(0,_str.get_string)("deleteconditionconfirm","core_reportbuilder",conditionName),(0,_str.get_string)("delete","core"),{triggerElement:reportRemoveCondition}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/conditions:remove");return(0,_conditions.deleteCondition)(reportElement.dataset.reportId,conditionContainer.dataset.conditionId).then((data=>reloadSettingsConditionsRegion(reportElement,data))).then((()=>(0,_toast.add)((0,_str.get_string)("conditiondeleted","core_reportbuilder",conditionName)))).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)})).catch((()=>{}))}})),new _sortable_list.default("".concat(reportSelectors.regions.activeConditions),{isHorizontal:!1}).getElementName=element=>Promise.resolve(element.data("conditionName")),(0,_jquery.default)(document).on(_sortable_list.default.EVENTS.DROP,reportSelectors.regions.activeCondition,((event,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_reportbuilder/conditions:reorder"),reportElement=event.target.closest(reportSelectors.regions.report),conditionId=info.element.data("conditionId"),conditionPosition=info.element.data("conditionPosition");let targetConditionPosition=info.targetNextElement.data("conditionPosition")||info.element.siblings().length+2;targetConditionPosition>conditionPosition&&targetConditionPosition--,(0,_conditions.reorderCondition)(reportElement.dataset.reportId,conditionId,targetConditionPosition).then((data=>reloadSettingsConditionsRegion(reportElement,data))).then((()=>(0,_str.get_string)("conditionmoved","core_reportbuilder",info.element.data("conditionName")))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)}})))}})); define("core_reportbuilder/local/editor/filters",["exports","jquery","core/custom_interaction_events","core/inplace_editable","core/notification","core/pending","core/prefetch","core/sortable_list","core/str","core/templates","core/toast","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/filters"],(function(_exports,_jquery,_custom_interaction_events,_inplace_editable,_notification,_pending,_prefetch,_sortable_list,_str,_templates,_toast,reportSelectors,_filters){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_sortable_list=_interopRequireDefault(_sortable_list),_templates=_interopRequireDefault(_templates),reportSelectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(reportSelectors);const reloadSettingsFiltersRegion=(reportElement,templateContext)=>{const pendingPromise=new _pending.default("core_reportbuilder/filters:reload"),settingsFiltersRegion=reportElement.querySelector(reportSelectors.regions.settingsFilters);return _templates.default.renderForPromise("core_reportbuilder/local/settings/filters",{filters:templateContext}).then((_ref=>{let{html:html,js:js}=_ref;_templates.default.replaceNode(settingsFiltersRegion,html,js),initFiltersForm();const reportAddFilter=reportElement.querySelector(reportSelectors.actions.reportAddFilter);return null==reportAddFilter||reportAddFilter.focus(),pendingPromise.resolve()}))},initFiltersForm=()=>{_custom_interaction_events.default.define(reportSelectors.actions.reportAddFilter,[_custom_interaction_events.default.events.accessibleChange])};_exports.init=initialized=>{((0,_prefetch.prefetchStrings)("core_reportbuilder",["deletefilter","deletefilterconfirm","filteradded","filterdeleted","filtermoved"]),(0,_prefetch.prefetchStrings)("core",["delete"]),initFiltersForm(),initialized)||((0,_jquery.default)(document).on(_custom_interaction_events.default.events.accessibleChange,reportSelectors.actions.reportAddFilter,(event=>{const reportAddFilter=event.target.closest(reportSelectors.actions.reportAddFilter);if(reportAddFilter){if(event.preventDefault(),0===reportAddFilter.selectedIndex)return;const reportElement=reportAddFilter.closest(reportSelectors.regions.report),pendingPromise=new _pending.default("core_reportbuilder/filters:add");(0,_filters.addFilter)(reportElement.dataset.reportId,reportAddFilter.value).then((data=>reloadSettingsFiltersRegion(reportElement,data))).then((()=>(0,_str.get_string)("filteradded","core_reportbuilder",reportAddFilter.options[reportAddFilter.selectedIndex].text))).then(_toast.add).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)}})),document.addEventListener("click",(event=>{const reportRemoveFilter=event.target.closest(reportSelectors.actions.reportRemoveFilter);if(reportRemoveFilter){event.preventDefault();const reportElement=reportRemoveFilter.closest(reportSelectors.regions.report),filterContainer=reportRemoveFilter.closest(reportSelectors.regions.activeFilter),filterName=filterContainer.dataset.filterName;_notification.default.saveCancelPromise((0,_str.get_string)("deletefilter","core_reportbuilder",filterName),(0,_str.get_string)("deletefilterconfirm","core_reportbuilder",filterName),(0,_str.get_string)("delete","core"),{triggerElement:reportRemoveFilter}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/filters:remove");return(0,_filters.deleteFilter)(reportElement.dataset.reportId,filterContainer.dataset.filterId).then((data=>reloadSettingsFiltersRegion(reportElement,data))).then((()=>(0,_toast.add)((0,_str.get_string)("filterdeleted","core_reportbuilder",filterName)))).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)})).catch((()=>{}))}})),new _sortable_list.default("".concat(reportSelectors.regions.activeFilters," ul"),{isHorizontal:!1}).getElementName=element=>Promise.resolve(element.data("filterName")),(0,_jquery.default)(document).on(_sortable_list.default.EVENTS.DROP,"".concat(reportSelectors.regions.report," li[data-filter-id]"),((event,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_reportbuilder/filters:reorder"),reportElement=event.target.closest(reportSelectors.regions.report),filterId=info.element.data("filterId"),filterPosition=info.element.data("filterPosition");let targetFilterPosition=info.targetNextElement.data("filterPosition")||info.element.siblings().length+2;targetFilterPosition>filterPosition&&targetFilterPosition--,(0,_filters.reorderFilter)(reportElement.dataset.reportId,filterId,targetFilterPosition).then((data=>reloadSettingsFiltersRegion(reportElement,data))).then((()=>(0,_str.get_string)("filtermoved","core_reportbuilder",info.element.data("filterName")))).then(_toast.add).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)}})))}})); define("core_reportbuilder/local/editor/sorting",["exports","jquery","core/inplace_editable","core/notification","core/pending","core/pubsub","core/sortable_list","core/str","core/toast","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/sorting","core/templates","core/event_dispatcher","core_reportbuilder/local/events"],(function(_exports,_jquery,_inplace_editable,_notification,_pending,_pubsub,_sortable_list,_str,_toast,reportSelectors,_sorting,_templates,_event_dispatcher,reportEvents){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_sortable_list=_interopRequireDefault(_sortable_list),reportSelectors=_interopRequireWildcard(reportSelectors),_templates=_interopRequireDefault(_templates),reportEvents=_interopRequireWildcard(reportEvents);const SORTORDER_ASCENDING=4,SORTORDER_DESCENDING=3,reloadSettingsSortingRegion=context=>{const pendingPromise=new _pending.default("core_reportbuilder/sorting:reload"),settingsSortingRegion=document.querySelector(reportSelectors.regions.settingsSorting);return _templates.default.renderForPromise("core_reportbuilder/local/settings/sorting",{sorting:context}).then((_ref=>{let{html:html,js:js}=_ref;return _templates.default.replaceNode(settingsSortingRegion,html,js),pendingPromise.resolve()}))},updateSorting=(reportElement,element,sortenabled,sortdirection)=>{const reportId=reportElement.dataset.reportId,listElement=element.closest("li"),columnId=listElement.dataset.columnSortId,columnName=listElement.dataset.columnSortName;return(0,_sorting.toggleColumnSorting)(reportId,columnId,sortenabled,sortdirection).then(reloadSettingsSortingRegion).then((()=>(0,_str.get_string)("columnsortupdated","core_reportbuilder",columnName))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),null)))};_exports.init=initialized=>{initialized||((0,_pubsub.subscribe)(reportEvents.publish.reportColumnsUpdated,(data=>reloadSettingsSortingRegion(data).catch(_notification.default.exception))),document.addEventListener("click",(event=>{const toggleSorting=event.target.closest(reportSelectors.actions.reportToggleColumnSort);if(toggleSorting){event.preventDefault();const pendingPromise=new _pending.default("core_reportbuilder/sorting:toggle"),reportElement=toggleSorting.closest(reportSelectors.regions.report),sortdirection=parseInt(toggleSorting.closest("li").dataset.columnSortDirection);updateSorting(reportElement,toggleSorting,toggleSorting.checked,sortdirection).then((()=>{const toggleSortingElement=document.getElementById(toggleSorting.id);return null==toggleSortingElement||toggleSortingElement.focus(),pendingPromise.resolve()})).catch(_notification.default.exception)}const toggleSortDirection=event.target.closest(reportSelectors.actions.reportToggleColumnSortDirection);if(toggleSortDirection){event.preventDefault();const pendingPromise=new _pending.default("core_reportbuilder/sorting:direction"),reportElement=toggleSortDirection.closest(reportSelectors.regions.report),listElement=toggleSortDirection.closest("li"),toggleSorting=listElement.querySelector(reportSelectors.actions.reportToggleColumnSort);let sortdirection=parseInt(listElement.dataset.columnSortDirection);sortdirection===SORTORDER_ASCENDING?sortdirection=SORTORDER_DESCENDING:sortdirection===SORTORDER_DESCENDING&&(sortdirection=SORTORDER_ASCENDING),updateSorting(reportElement,toggleSortDirection,toggleSorting.checked,sortdirection).then((()=>{const toggleSortDirectionElement=document.getElementById(toggleSortDirection.id);return null==toggleSortDirectionElement||toggleSortDirectionElement.focus(),pendingPromise.resolve()})).catch(_notification.default.exception)}})),new _sortable_list.default("".concat(reportSelectors.regions.settingsSorting," ul"),{isHorizontal:!1}).getElementName=element=>Promise.resolve(element.data("columnSortName")),(0,_jquery.default)(document).on(_sortable_list.default.EVENTS.DROP,"".concat(reportSelectors.regions.report," li[data-column-sort-id]"),((event,info)=>{if(info.positionChanged){const pendingPromise=new _pending.default("core_reportbuilder/sorting:reorder"),reportElement=event.target.closest(reportSelectors.regions.report),columnId=info.element.data("columnSortId"),columnPosition=info.element.data("columnSortPosition");let targetColumnSortPosition=info.targetNextElement.data("columnSortPosition")||info.element.siblings().length+2;targetColumnSortPosition>columnPosition&&targetColumnSortPosition--,(0,_sorting.reorderColumnSorting)(reportElement.dataset.reportId,columnId,targetColumnSortPosition).then(reloadSettingsSortingRegion).then((()=>(0,_str.get_string)("columnsortupdated","core_reportbuilder",info.element.data("columnSortName")))).then(_toast.add).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),null))).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)}})))}})); define("core_reportbuilder/local/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={tableReload:"core_reportbuilder_table_reload",publish:{reportColumnsUpdated:"core_reportbuilder_report_columns_updated"}},_exports.default})); define("core_reportbuilder/local/repository/audiences",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle audiences AJAX requests * * @module core_reportbuilder/local/repository/audiences * @copyright 2021 David Matamoros <davidmc@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.deleteAudience=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.deleteAudience=(reportId,instanceId)=>{const request={methodname:"core_reportbuilder_audiences_delete",args:{reportid:reportId,instanceid:instanceId}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/columns",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle column AJAX requests * * @module core_reportbuilder/local/repository/columns * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.reorderColumn=_exports.deleteColumn=_exports.addColumn=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.addColumn=(reportId,uniqueIdentifier)=>{const request={methodname:"core_reportbuilder_columns_add",args:{reportid:reportId,uniqueidentifier:uniqueIdentifier}};return _ajax.default.call([request])[0]};_exports.deleteColumn=(reportId,columnId)=>{const request={methodname:"core_reportbuilder_columns_delete",args:{reportid:reportId,columnid:columnId}};return _ajax.default.call([request])[0]};_exports.reorderColumn=(reportId,columnId,position)=>{const request={methodname:"core_reportbuilder_columns_reorder",args:{reportid:reportId,columnid:columnId,position:position}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/conditions",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle condition AJAX requests * * @module core_reportbuilder/local/repository/conditions * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.resetConditions=_exports.reorderCondition=_exports.deleteCondition=_exports.addCondition=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.resetConditions=reportId=>{const request={methodname:"core_reportbuilder_conditions_reset",args:{reportid:reportId}};return _ajax.default.call([request])[0]};_exports.addCondition=(reportId,uniqueIdentifier)=>{const request={methodname:"core_reportbuilder_conditions_add",args:{reportid:reportId,uniqueidentifier:uniqueIdentifier}};return _ajax.default.call([request])[0]};_exports.deleteCondition=(reportId,conditionId)=>{const request={methodname:"core_reportbuilder_conditions_delete",args:{reportid:reportId,conditionid:conditionId}};return _ajax.default.call([request])[0]};_exports.reorderCondition=(reportId,conditionId,position)=>{const request={methodname:"core_reportbuilder_conditions_reorder",args:{reportid:reportId,conditionid:conditionId,position:position}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/filters",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle filter AJAX requests * * @module core_reportbuilder/local/repository/filters * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setFilters=_exports.resetFilters=_exports.reorderFilter=_exports.deleteFilter=_exports.addFilter=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.resetFilters=(reportId,reportParameters)=>{const request={methodname:"core_reportbuilder_filters_reset",args:{reportid:reportId,parameters:reportParameters}};return _ajax.default.call([request])[0]};_exports.setFilters=(reportId,reportParameters,filterValues)=>{const request={methodname:"core_reportbuilder_set_filters",args:{reportid:reportId,parameters:reportParameters,values:filterValues}};return _ajax.default.call([request])[0]};_exports.addFilter=(reportId,uniqueIdentifier)=>{const request={methodname:"core_reportbuilder_filters_add",args:{reportid:reportId,uniqueidentifier:uniqueIdentifier}};return _ajax.default.call([request])[0]};_exports.deleteFilter=(reportId,filterId)=>{const request={methodname:"core_reportbuilder_filters_delete",args:{reportid:reportId,filterid:filterId}};return _ajax.default.call([request])[0]};_exports.reorderFilter=(reportId,filterId,position)=>{const request={methodname:"core_reportbuilder_filters_reorder",args:{reportid:reportId,filterid:filterId,position:position}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/schedules",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle schedule AJAX requests * * @module core_reportbuilder/local/repository/schedules * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.toggleSchedule=_exports.sendSchedule=_exports.deleteSchedule=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.deleteSchedule=(reportId,scheduleId)=>{const request={methodname:"core_reportbuilder_schedules_delete",args:{reportid:reportId,scheduleid:scheduleId}};return _ajax.default.call([request])[0]};_exports.sendSchedule=(reportId,scheduleId)=>{const request={methodname:"core_reportbuilder_schedules_send",args:{reportid:reportId,scheduleid:scheduleId}};return _ajax.default.call([request])[0]};_exports.toggleSchedule=(reportId,scheduleId,scheduleEnabled)=>{const request={methodname:"core_reportbuilder_schedules_toggle",args:{reportid:reportId,scheduleid:scheduleId,enabled:scheduleEnabled}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/sorting",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle column sorting AJAX requests * * @module core_reportbuilder/local/repository/sorting * @copyright 2021 David Matamoros <davidmc@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.toggleColumnSorting=_exports.reorderColumnSorting=_exports.getColumnSorting=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.getColumnSorting=reportId=>{const request={methodname:"core_reportbuilder_columns_sort_get",args:{reportid:reportId}};return _ajax.default.call([request])[0]};_exports.reorderColumnSorting=(reportId,columnId,position)=>{const request={methodname:"core_reportbuilder_columns_sort_reorder",args:{reportid:reportId,columnid:columnId,position:position}};return _ajax.default.call([request])[0]};_exports.toggleColumnSorting=(reportId,columnId,enabled,direction)=>{const request={methodname:"core_reportbuilder_columns_sort_toggle",args:{reportid:reportId,columnid:columnId,enabled:enabled,direction:direction}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/repository/modals",["exports","core_form/modalform","core/str"],(function(_exports,_modalform,_str){var obj; /** * Module to handle modal form requests * * @module core_reportbuilder/local/repository/modals * @copyright 2021 David Matamoros <davidmc@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.createScheduleModal=_exports.createReportModal=void 0,_modalform=(obj=_modalform)&&obj.__esModule?obj:{default:obj};const createModalForm=(triggerElement,modalTitle,formClass,formArgs)=>new _modalform.default({modalConfig:{title:modalTitle},formClass:formClass,args:formArgs,saveButtonText:(0,_str.get_string)("save","moodle"),returnFocus:triggerElement});_exports.createReportModal=function(triggerElement,modalTitle){let reportId=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return createModalForm(triggerElement,modalTitle,"core_reportbuilder\\form\\report",{id:reportId})};_exports.createScheduleModal=function(triggerElement,modalTitle,reportId){let scheduleId=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return createModalForm(triggerElement,modalTitle,"core_reportbuilder\\form\\schedule",{reportid:reportId,id:scheduleId})}})); define("core_reportbuilder/local/repository/reports",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Module to handle report AJAX requests * * @module core_reportbuilder/local/repository/reports * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getReport=_exports.deleteReport=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.deleteReport=reportId=>{const request={methodname:"core_reportbuilder_reports_delete",args:{reportid:reportId}};return _ajax.default.call([request])[0]};_exports.getReport=(reportId,editMode)=>{const request={methodname:"core_reportbuilder_reports_get",args:{reportid:reportId,editmode:editMode}};return _ajax.default.call([request])[0]}})); define("core_reportbuilder/local/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Report builder selectors * * @module core_reportbuilder/local/selectors * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS={regions:{report:'[data-region="core_reportbuilder/report"]',reportTable:'[data-region="reportbuilder-table"]',columnHeader:'[data-region="column-header"]',filterButtonLabel:'[data-region="filter-button-label"]',filtersForm:'[data-region="filters-form"]',sidebarMenu:'[data-region="sidebar-menu"]',sidebarCard:'[data-region="sidebar-card"]',sidebarItem:'[data-region="sidebar-item"]',settingsConditions:'[data-region="settings-conditions"]',activeConditions:'[data-region="active-conditions"]',activeCondition:'[data-region="active-condition"]',settingsFilters:'[data-region="settings-filters"]',activeFilters:'[data-region="active-filters"]',activeFilter:'[data-region="active-filter"]',settingsSorting:'[data-region="settings-sorting"]',audiencesContainer:'[data-region="audiences"]',audienceFormContainer:'[data-region="audience-form-container"]',audienceCard:'[data-region="audience-card"]',audienceHeading:'[data-region="audience-heading"]',audienceForm:'[data-region="audience-form"]',audienceEmptyMessage:"[data-region=no-instances-message]",audienceDescription:"[data-region=audience-description]",audienceNotSavedLabel:"[data-region=audience-not-saved]",settingsCardView:'[data-region="settings-cardview"]'},actions:{reportActionPopup:'[data-action="report-action-popup"]',reportCreate:'[data-action="report-create"]',reportEdit:'[data-action="report-edit"]',reportDelete:'[data-action="report-delete"]',reportAddColumn:'[data-action="report-add-column"]',reportRemoveColumn:'[data-action="report-remove-column"]',reportAddCondition:'[data-action="report-add-condition"]',reportRemoveCondition:'[data-action="report-remove-condition"]',reportAddFilter:'[data-action="report-add-filter"]',reportRemoveFilter:'[data-action="report-remove-filter"]',reportToggleColumnSort:'[data-action="report-toggle-column-sorting"]',reportToggleColumnSortDirection:'[data-action="report-toggle-sort-direction"]',sidebarSearch:'[data-action="sidebar-search"]',toggleEditPreview:'[data-action="toggle-edit-preview"]',audienceAdd:'[data-action="add-audience"]',audienceEdit:'[data-action="edit-audience"]',audienceDelete:'[data-action="delete-audience"]',toggleCardView:'[data-action="toggle-card"]',scheduleCreate:'[data-action="schedule-create"]',scheduleToggle:'[data-action="schedule-toggle"]',scheduleEdit:'[data-action="schedule-edit"]',scheduleSend:'[data-action="schedule-send"]',scheduleDelete:'[data-action="schedule-delete"]'},forReport:reportId=>"".concat(SELECTORS.regions.report,'[data-report-id="').concat(reportId,'"]')};var _default=SELECTORS;return _exports.default=_default,_exports.default})); define("core_reportbuilder/report",["exports","core/notification","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_table/dynamic","core_table/local/dynamic/selectors"],(function(_exports,_notification,reportEvents,reportSelectors,_dynamic,tableSelectors){var obj; /** * Report builder report management * * @module core_reportbuilder/report * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj},reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors),tableSelectors=_interopRequireWildcard(tableSelectors);const CLASSES_COLLAPSED="collapsed",CLASSES_EXPANDED="show",CLASSES_ICONUP="fa-angle-up",CLASSES_ICONDOWN="fa-angle-down";let initialized=!1;_exports.init=()=>{initialized||(document.addEventListener(reportEvents.tableReload,(async event=>{var _event$detail;const reportElement=event.target.closest(reportSelectors.regions.report);if(null===reportElement)return;const tableRoot=reportElement.querySelector(tableSelectors.main.region),pageNumber=null!==(_event$detail=event.detail)&&void 0!==_event$detail&&_event$detail.preservePagination?null:1;await(0,_dynamic.setPageNumber)(tableRoot,pageNumber,!1).then(_dynamic.refreshTableContent).then((()=>{var _event$detail2;const preserveTriggerElement=null===(_event$detail2=event.detail)||void 0===_event$detail2?void 0:_event$detail2.preserveTriggerElement;var _reportElement$queryS;preserveTriggerElement&&(null===(_reportElement$queryS=reportElement.querySelector(preserveTriggerElement))||void 0===_reportElement$queryS||_reportElement$queryS.focus())})).catch(_notification.default.exception)})),document.addEventListener("click",(event=>{const reportActionPopup=event.target.closest(reportSelectors.actions.reportActionPopup);if(null===reportActionPopup)return;event.preventDefault();const popupAction=JSON.parse(reportActionPopup.dataset.popupAction);window.openpopup(event,popupAction.jsfunctionargs)})),document.addEventListener("click",(event=>{const toggleCard=event.target.closest(reportSelectors.actions.toggleCardView);if(toggleCard){const tableCard=toggleCard.closest("tr"),toggleIcon=toggleCard.querySelector("i");event.preventDefault(),toggleCard.classList.contains(CLASSES_COLLAPSED)?(tableCard.classList.add(CLASSES_EXPANDED),toggleIcon.classList.replace(CLASSES_ICONDOWN,CLASSES_ICONUP),toggleCard.classList.remove(CLASSES_COLLAPSED),toggleCard.setAttribute("aria-expanded","true")):(tableCard.classList.remove(CLASSES_EXPANDED),toggleIcon.classList.replace(CLASSES_ICONUP,CLASSES_ICONDOWN),toggleCard.classList.add(CLASSES_COLLAPSED),toggleCard.removeAttribute("aria-expanded"))}})),initialized=!0)}})); define("core_reportbuilder/sidebar",["exports","core/pending","core/utils","core_reportbuilder/local/selectors"],(function(_exports,_pending,_utils,reportSelectors){var obj; /** * Report builder sidebar component * * @module core_reportbuilder/sidebar * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj},reportSelectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(reportSelectors);const CLASSES_EXPANDED="show",CLASSES_COLLAPSED="collapsed",CLASSES_HIDE="d-none",sidebarCardFilter=(event,sidebarMenu)=>{const pendingPromise=new _pending.default("core_reportbuilder/sidebar:cardFilter"),sidebarCards=sidebarMenu.querySelectorAll(reportSelectors.regions.sidebarCard),sidebarItems=sidebarMenu.querySelectorAll(reportSelectors.regions.sidebarItem),searchTerm=event.target.value.toLowerCase();sidebarItems.forEach((item=>{const itemContent=item.textContent.toLowerCase();item.classList.toggle(CLASSES_HIDE,!itemContent.includes(searchTerm))})),sidebarCards.forEach((card=>{const visibleItems=card.querySelectorAll("".concat(reportSelectors.regions.sidebarItem,":not(.").concat(CLASSES_HIDE,")"));card.classList.toggle(CLASSES_HIDE,!visibleItems.length),expandCard(card)})),pendingPromise.resolve()},expandCard=card=>{let cardButton=card.querySelector('[data-toggle="collapse"]');if(cardButton.classList.contains(CLASSES_COLLAPSED)){cardButton.classList.remove(CLASSES_COLLAPSED),cardButton.setAttribute("aria-expanded","true"),card.querySelector(cardButton.dataset.target).classList.add(CLASSES_EXPANDED)}};_exports.init=selectorId=>{const sidebarMenu=document.querySelector(selectorId+reportSelectors.regions.sidebarMenu),sidebarSearch=sidebarMenu.querySelector(reportSelectors.actions.sidebarSearch),sidebarSearchDebounce=(0,_utils.debounce)(sidebarCardFilter,250);sidebarSearch.addEventListener("keyup",(event=>{const pendingPromise=new _pending.default("core_reportbuilder/sidebar:keyup");sidebarSearchDebounce(event,sidebarMenu),setTimeout((()=>{pendingPromise.resolve()}),250)}))}})); define("core_reportbuilder/audience",["exports","core/inplace_editable","core/templates","core/notification","core/pending","core/prefetch","core/str","core_form/dynamicform","core/toast","core_reportbuilder/local/repository/audiences","core_reportbuilder/local/selectors","core/fragment","core_form/changechecker"],(function(_exports,_inplace_editable,_templates,_notification,_pending,_prefetch,_str,_dynamicform,_toast,_audiences,reportSelectors,_fragment,_changechecker){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_templates=_interopRequireDefault(_templates),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_dynamicform=_interopRequireDefault(_dynamicform),reportSelectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(reportSelectors);let reportId=0,contextId=0;const initAudienceCardForm=audienceCard=>{const audienceFormContainer=audienceCard.querySelector(reportSelectors.regions.audienceFormContainer),audienceForm=new _dynamicform.default(audienceFormContainer,"\\core_reportbuilder\\form\\audience");return audienceForm.addEventListener(audienceForm.events.FORM_SUBMITTED,(data=>{const audienceHeading=audienceCard.querySelector(reportSelectors.regions.audienceHeading),audienceDescription=audienceCard.querySelector(reportSelectors.regions.audienceDescription);return audienceCard.dataset.instanceid=data.detail.instanceid,audienceHeading.innerHTML=data.detail.heading,audienceDescription.innerHTML=data.detail.description,closeAudienceCardForm(audienceCard),(0,_str.get_string)("audiencesaved","core_reportbuilder").then(_toast.add)})),audienceForm.addEventListener(audienceForm.events.FORM_CANCELLED,(()=>{audienceCard.dataset.instanceid>0?closeAudienceCardForm(audienceCard):removeAudienceCard(audienceCard)})),audienceForm},closeAudienceCardForm=audienceCard=>{const audienceFormContainer=audienceCard.querySelector(reportSelectors.regions.audienceFormContainer),NewAudienceFormContainer=audienceFormContainer.cloneNode(!1);audienceCard.querySelector(reportSelectors.regions.audienceForm).replaceChild(NewAudienceFormContainer,audienceFormContainer),audienceCard.querySelector(reportSelectors.regions.audienceDescription).classList.remove("hidden"),audienceCard.querySelector(reportSelectors.actions.audienceEdit).disabled=!1,audienceCard.querySelector(reportSelectors.actions.audienceDelete).disabled=!1},removeAudienceCard=audienceCard=>{audienceCard.remove();const audienceCards=document.querySelector(reportSelectors.regions.audiencesContainer).querySelectorAll(reportSelectors.regions.audienceCard);if(0===audienceCards.length){document.querySelector(reportSelectors.regions.audienceEmptyMessage).classList.remove("hidden")}else{const audienceFirstCardSeparator=audienceCards[0].querySelector(".audience-separator");null==audienceFirstCardSeparator||audienceFirstCardSeparator.remove()}};let initialized=!1;_exports.init=(id,contextid)=>{(0,_prefetch.prefetchStrings)("core_reportbuilder",["audienceadded","audiencedeleted","audiencesaved","deleteaudience","deleteaudienceconfirm"]),(0,_prefetch.prefetchStrings)("core",["delete"]),reportId=id,contextId=contextid,initialized||(document.addEventListener("click",(event=>{const audienceAdd=event.target.closest(reportSelectors.actions.audienceAdd);audienceAdd&&(event.preventDefault(),((className,title)=>{const pendingPromise=new _pending.default("core_reportbuilder/audience:add"),audiencesContainer=document.querySelector(reportSelectors.regions.audiencesContainer),audienceCardLength=audiencesContainer.querySelectorAll(reportSelectors.regions.audienceCard).length,params={classname:className,reportid:reportId,showormessage:audienceCardLength>0,title:title};(0,_fragment.loadFragment)("core_reportbuilder","audience_form",contextId,params).then(((html,js)=>{const audienceCard=_templates.default.appendNodeContents(audiencesContainer,html,js)[0],audienceEmptyMessage=audiencesContainer.querySelector(reportSelectors.regions.audienceEmptyMessage),audienceForm=initAudienceCardForm(audienceCard);return(0,_changechecker.markFormAsDirty)(audienceForm.getFormNode()),audienceEmptyMessage.classList.add("hidden"),(0,_str.get_string)("audienceadded","core_reportbuilder",title)})).then(_toast.add).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)})(audienceAdd.dataset.uniqueIdentifier,audienceAdd.dataset.name));const audienceEdit=event.target.closest(reportSelectors.actions.audienceEdit);if(audienceEdit){const audienceEditCard=audienceEdit.closest(reportSelectors.regions.audienceCard);event.preventDefault(),(audienceCard=>{const pendingPromise=new _pending.default("core_reportbuilder/audience:edit");initAudienceCardForm(audienceCard).load({id:audienceCard.dataset.instanceid}).then((()=>{const audienceFormContainer=audienceCard.querySelector(reportSelectors.regions.audienceFormContainer),audienceDescription=audienceCard.querySelector(reportSelectors.regions.audienceDescription),audienceEdit=audienceCard.querySelector(reportSelectors.actions.audienceEdit);return audienceFormContainer.classList.remove("hidden"),audienceDescription.classList.add("hidden"),audienceEdit.disabled=!0,pendingPromise.resolve()})).catch(_notification.default.exception)})(audienceEditCard)}const audienceDelete=event.target.closest(reportSelectors.actions.audienceDelete);audienceDelete&&(event.preventDefault(),(audienceDelete=>{const audienceCard=audienceDelete.closest(reportSelectors.regions.audienceCard),audienceTitle=audienceCard.dataset.title;_notification.default.saveCancelPromise((0,_str.get_string)("deleteaudience","core_reportbuilder",audienceTitle),(0,_str.get_string)("deleteaudienceconfirm","core_reportbuilder",audienceTitle),(0,_str.get_string)("delete","core"),{triggerElement:audienceDelete}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/audience:delete");return(0,_audiences.deleteAudience)(reportId,audienceCard.dataset.instanceid).then((()=>(0,_toast.add)((0,_str.get_string)("audiencedeleted","core_reportbuilder",audienceTitle)))).then((()=>(removeAudienceCard(audienceCard),pendingPromise.resolve()))).catch(_notification.default.exception)})).catch((()=>{}))})(audienceDelete))})),initialized=!0)}})); define("core_reportbuilder/editor",["exports","jquery","core/inplace_editable","core/loadingicon","core/notification","core/pending","core/templates","core/str","core/toast","core_reportbuilder/local/selectors","core_reportbuilder/local/editor/columns","core_reportbuilder/local/editor/conditions","core_reportbuilder/local/editor/filters","core_reportbuilder/local/editor/sorting","core_reportbuilder/local/editor/card_view","core_reportbuilder/local/repository/reports","core_reportbuilder/local/repository/modals"],(function(_exports,_jquery,_inplace_editable,_loadingicon,_notification,_pending,_templates,_str,_toast,reportSelectors,_columns,_conditions,_filters,_sorting,_card_view,_reports,_modals){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_templates=_interopRequireDefault(_templates),reportSelectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(reportSelectors);let initialized=!1;_exports.init=()=>{(0,_columns.init)(initialized),(0,_conditions.init)(initialized),(0,_filters.init)(initialized),(0,_sorting.init)(initialized),(0,_card_view.init)(initialized),initialized||(document.addEventListener("click",(event=>{const toggleEditViewMode=event.target.closest(reportSelectors.actions.toggleEditPreview);if(toggleEditViewMode){event.preventDefault();const reportElement=event.target.closest(reportSelectors.regions.report),pendingPromise=new _pending.default("core_reportbuilder/reports:get"),toggledEditMode="1"!==toggleEditViewMode.dataset.editMode;(0,_loadingicon.addIconToContainer)(toggleEditViewMode).then((()=>(0,_reports.getReport)(reportElement.dataset.reportId,toggledEditMode))).then((response=>Promise.all([_jquery.default.parseHTML(response.javascript,null,!0).map((node=>node.innerHTML)).join("\n"),_templates.default.renderForPromise("core_reportbuilder/local/dynamictabs/editor",response)]))).then((_ref=>{let[responseJs,{html:html,js:js}]=_ref;return _templates.default.replaceNode(reportElement,html,js+responseJs)})).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)}const reportEdit=event.target.closest(reportSelectors.actions.reportEdit);if(reportEdit){event.preventDefault();const reportModal=(0,_modals.createReportModal)(event.target,(0,_str.get_string)("editreportdetails","core_reportbuilder"),reportEdit.dataset.reportId);reportModal.addEventListener(reportModal.events.FORM_SUBMITTED,(()=>{(0,_str.get_string)("reportupdated","core_reportbuilder").then(_toast.add).then((()=>window.location.reload())).catch(_notification.default.exception)})),reportModal.show()}})),initialized=!0)}})); define("core_reportbuilder/filters",["exports","core/event_dispatcher","core/fragment","core/notification","core/pending","core/str","core/templates","core/toast","core_form/dynamicform","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/filters"],(function(_exports,_event_dispatcher,_fragment,_notification,_pending,_str,_templates,_toast,_dynamicform,reportEvents,reportSelectors,_filters){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Report builder filter management * * @module core_reportbuilder/filters * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_templates=_interopRequireDefault(_templates),_dynamicform=_interopRequireDefault(_dynamicform),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);const setFilterButtonCount=async(reportElement,filterCount)=>{const filterButtonLabel=reportElement.querySelector(reportSelectors.regions.filterButtonLabel);filterButtonLabel.textContent=filterCount>0?await(0,_str.get_string)("filtersappliedx","core_reportbuilder",filterCount):await(0,_str.get_string)("filters","moodle")};_exports.init=(reportId,contextId)=>{const reportElement=document.querySelector(reportSelectors.forReport(reportId)),filterFormContainer=reportElement.querySelector(reportSelectors.regions.filtersForm);if(filterFormContainer.dataset.initialized)return;filterFormContainer.dataset.initialized=!0;const filterForm=new _dynamicform.default(filterFormContainer,"\\core_reportbuilder\\form\\filter");filterForm.addEventListener(filterForm.events.FORM_SUBMITTED,(event=>{event.preventDefault(),(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),setFilterButtonCount(reportElement,event.detail),(0,_str.get_string)("filtersapplied","core_reportbuilder").then(_toast.add).catch(_notification.default.exception)})),filterForm.addEventListener(filterForm.events.NOSUBMIT_BUTTON_PRESSED,(event=>{event.preventDefault();const pendingPromise=new _pending.default("core_reportbuilder/filters:reset"),reportParameters=reportElement.dataset.parameter;(0,_filters.resetFilters)(reportId,reportParameters).then((()=>(0,_str.get_string)("filtersreset","core_reportbuilder"))).then(_toast.add).then((()=>(0,_fragment.loadFragment)("core_reportbuilder","filters_form",contextId,{reportid:reportId,parameters:reportParameters}))).then(((html,js)=>(_templates.default.replaceNodeContents(filterFormContainer,html,js),(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement),setFilterButtonCount(reportElement,0),pendingPromise.resolve()))).catch(_notification.default.exception)})),document.querySelector("#region-main").style.overflowX="visible"}})); define("core_reportbuilder/reports_list",["exports","core/event_dispatcher","core/notification","core/pending","core/prefetch","core/str","core/toast","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/reports","core_reportbuilder/local/repository/modals"],(function(_exports,_event_dispatcher,_notification,_pending,_prefetch,_str,_toast,reportEvents,reportSelectors,_reports,_modals){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);_exports.init=()=>{(0,_prefetch.prefetchStrings)("core_reportbuilder",["deletereport","deletereportconfirm","editreportdetails","newreport","reportdeleted","reportupdated"]),(0,_prefetch.prefetchStrings)("core",["delete"]),document.addEventListener("click",(event=>{if(event.target.closest(reportSelectors.actions.reportCreate)){event.preventDefault();const reportModal=(0,_modals.createReportModal)(event.target,(0,_str.get_string)("newreport","core_reportbuilder"));reportModal.addEventListener(reportModal.events.FORM_SUBMITTED,(event=>{window.location.href=event.detail})),reportModal.show()}const reportEdit=event.target.closest(reportSelectors.actions.reportEdit);if(reportEdit){event.preventDefault();const triggerElement=reportEdit.closest(".dropdown").querySelector(".dropdown-toggle"),reportModal=(0,_modals.createReportModal)(triggerElement,(0,_str.get_string)("editreportdetails","core_reportbuilder"),reportEdit.dataset.reportId);reportModal.addEventListener(reportModal.events.FORM_SUBMITTED,(()=>{const reportElement=event.target.closest(reportSelectors.regions.report);(0,_str.get_string)("reportupdated","core_reportbuilder").then(_toast.add).then((()=>{(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement)})).catch(_notification.default.exception)})),reportModal.show()}const reportDelete=event.target.closest(reportSelectors.actions.reportDelete);if(reportDelete){event.preventDefault();const triggerElement=reportDelete.closest(".dropdown").querySelector(".dropdown-toggle");_notification.default.saveCancelPromise((0,_str.get_string)("deletereport","core_reportbuilder"),(0,_str.get_string)("deletereportconfirm","core_reportbuilder",reportDelete.dataset.reportName),(0,_str.get_string)("delete","core"),{triggerElement:triggerElement}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/reports:delete"),reportElement=event.target.closest(reportSelectors.regions.report);return(0,_reports.deleteReport)(reportDelete.dataset.reportId).then((()=>(0,_toast.add)((0,_str.get_string)("reportdeleted","core_reportbuilder")))).then((()=>((0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement),pendingPromise.resolve()))).catch(_notification.default.exception)})).catch((()=>{}))}}))}})); define("core_reportbuilder/schedules",["exports","core/event_dispatcher","core/inplace_editable","core/notification","core/pending","core/prefetch","core/str","core/toast","core_reportbuilder/local/events","core_reportbuilder/local/selectors","core_reportbuilder/local/repository/modals","core_reportbuilder/local/repository/schedules"],(function(_exports,_event_dispatcher,_inplace_editable,_notification,_pending,_prefetch,_str,_toast,reportEvents,reportSelectors,_modals,_schedules){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),reportEvents=_interopRequireWildcard(reportEvents),reportSelectors=_interopRequireWildcard(reportSelectors);let initialized=!1;_exports.init=reportId=>{(0,_prefetch.prefetchStrings)("core_reportbuilder",["deleteschedule","deletescheduleconfirm","disableschedule","editscheduledetails","enableschedule","newschedule","schedulecreated","scheduledeleted","schedulesent","scheduleupdated","sendschedule","sendscheduleconfirm"]),(0,_prefetch.prefetchStrings)("core",["confirm","delete"]),initialized||(document.addEventListener("click",(event=>{if(event.target.closest(reportSelectors.actions.scheduleCreate)){event.preventDefault();const scheduleModal=(0,_modals.createScheduleModal)(event.target,(0,_str.get_string)("newschedule","core_reportbuilder"),reportId);scheduleModal.addEventListener(scheduleModal.events.FORM_SUBMITTED,(()=>{(0,_str.get_string)("schedulecreated","core_reportbuilder").then(_toast.add).then((()=>{const reportElement=document.querySelector(reportSelectors.regions.report);(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement)})).catch(_notification.default.exception)})),scheduleModal.show()}const scheduleToggle=event.target.closest(reportSelectors.actions.scheduleToggle);if(scheduleToggle){const pendingPromise=new _pending.default("core_reportbuilder/schedules:toggle"),scheduleStateToggle=+!Number(scheduleToggle.dataset.state);(0,_schedules.toggleSchedule)(reportId,scheduleToggle.dataset.id,scheduleStateToggle).then((()=>{scheduleToggle.closest("tr").classList.toggle("text-muted"),scheduleToggle.dataset.state=scheduleStateToggle;const stringKey=scheduleStateToggle?"disableschedule":"enableschedule";return(0,_str.get_string)(stringKey,"core_reportbuilder")})).then((toggleLabel=>(scheduleToggle.parentElement.querySelector('label[for="'.concat(scheduleToggle.id,'"] > span')).innerHTML=toggleLabel,pendingPromise.resolve()))).catch(_notification.default.exception)}const scheduleEdit=event.target.closest(reportSelectors.actions.scheduleEdit);if(scheduleEdit){event.preventDefault();const triggerElement=scheduleEdit.closest(".dropdown").querySelector(".dropdown-toggle"),scheduleModal=(0,_modals.createScheduleModal)(triggerElement,(0,_str.get_string)("editscheduledetails","core_reportbuilder"),reportId,scheduleEdit.dataset.scheduleId);scheduleModal.addEventListener(scheduleModal.events.FORM_SUBMITTED,(()=>{(0,_str.get_string)("scheduleupdated","core_reportbuilder").then(_toast.add).then((()=>{const reportElement=scheduleEdit.closest(reportSelectors.regions.report);(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{},reportElement)})).catch(_notification.default.exception)})),scheduleModal.show()}const scheduleSend=event.target.closest(reportSelectors.actions.scheduleSend);if(scheduleSend){event.preventDefault();const triggerElement=scheduleSend.closest(".dropdown").querySelector(".dropdown-toggle");_notification.default.saveCancelPromise((0,_str.get_string)("sendschedule","core_reportbuilder"),(0,_str.get_string)("sendscheduleconfirm","core_reportbuilder",scheduleSend.dataset.scheduleName),(0,_str.get_string)("confirm","core"),{triggerElement:triggerElement}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/schedules:send");return(0,_schedules.sendSchedule)(reportId,scheduleSend.dataset.scheduleId).then((0,_toast.add)((0,_str.get_string)("schedulesent","core_reportbuilder"))).then((()=>pendingPromise.resolve())).catch(_notification.default.exception)})).catch((()=>{}))}const scheduleDelete=event.target.closest(reportSelectors.actions.scheduleDelete);if(scheduleDelete){event.preventDefault();const triggerElement=scheduleDelete.closest(".dropdown").querySelector(".dropdown-toggle");_notification.default.saveCancelPromise((0,_str.get_string)("deleteschedule","core_reportbuilder"),(0,_str.get_string)("deletescheduleconfirm","core_reportbuilder",scheduleDelete.dataset.scheduleName),(0,_str.get_string)("delete","core"),{triggerElement:triggerElement}).then((()=>{const pendingPromise=new _pending.default("core_reportbuilder/schedules:delete");return(0,_schedules.deleteSchedule)(reportId,scheduleDelete.dataset.scheduleId).then((0,_toast.add)((0,_str.get_string)("scheduledeleted","core_reportbuilder"))).then((()=>{const reportElement=scheduleDelete.closest(reportSelectors.regions.report);return(0,_event_dispatcher.dispatchEvent)(reportEvents.tableReload,{preservePagination:!0},reportElement),pendingPromise.resolve()})).catch(_notification.default.exception)})).catch((()=>{}))}})),initialized=!0)}})); /** * Search user selector module. * * @module core_search/form-search-user-selector * @copyright 2017 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("core_search/form-search-user-selector",["jquery","core/ajax","core/templates"],(function($,Ajax,Templates){return{processResults:function(selector,results){var users=[];return $.each(results,(function(index,user){users.push({value:user.id,label:user._label})})),users},transport:function(selector,query,success,failure){var args={query:query},courseid=$(selector).attr("withincourseid");void 0!==courseid&&""!==$("#id_searchwithin").val()?args.courseid=courseid:args.courseid=0,Ajax.call([{methodname:"core_search_get_relevant_users",args:args}])[0].then((function(results){var promises=[];return $.each(results,(function(index,user){promises.push(Templates.render("core_search/form-user-selector-suggestion",user))})),$.when.apply($.when,promises).then((function(){var args=arguments,i=0;$.each(results,(function(index,user){user._label=args[i++]})),success(results)}))})).fail(failure)}}})); define("core_table/dynamic",["exports","core_table/local/dynamic/selectors","./local/dynamic/events","core/pending","core/loadingicon","core_table/local/dynamic/repository","core/notification"],(function(_exports,Selectors,_events,_pending,_loadingicon,_repository,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Events",{enumerable:!0,get:function(){return _events.default}}),_exports.updateTable=_exports.showColumn=_exports.setSortOrder=_exports.setPageSize=_exports.setPageNumber=_exports.setLastInitial=_exports.setFirstInitial=_exports.setFilters=_exports.refreshTableContent=_exports.init=_exports.hideColumn=_exports.getTableFromId=_exports.getPageSize=_exports.getPageNumber=_exports.getLastInitial=_exports.getFirstInitial=_exports.getFilters=void 0,Selectors=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Module to handle dynamic table features. * * @module core_table/dynamic * @copyright 2020 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(Selectors),_events=_interopRequireDefault(_events),_pending=_interopRequireDefault(_pending),_notification=_interopRequireDefault(_notification);let watching=!1;const checkTableIsDynamic=tableRoot=>{if(!tableRoot)throw new Error("The table specified is not a dynamic table and cannot be updated");if(!tableRoot.matches(Selectors.main.region))throw new Error("The table specified is not a dynamic table and cannot be updated");return!0},getFiltersetFromTable=tableRoot=>JSON.parse(tableRoot.dataset.tableFilters),refreshTableContent=function(tableRoot){let resetContent=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const filterset=getFiltersetFromTable(tableRoot);(0,_loadingicon.addIconToContainer)(tableRoot);const pendingPromise=new _pending.default("core_table/dynamic:refreshTableContent");return(0,_repository.fetch)(tableRoot.dataset.tableComponent,tableRoot.dataset.tableHandler,tableRoot.dataset.tableUniqueid,{sortData:JSON.parse(tableRoot.dataset.tableSortData),joinType:filterset.jointype,filters:filterset.filters,firstinitial:tableRoot.dataset.tableFirstInitial,lastinitial:tableRoot.dataset.tableLastInitial,pageNumber:tableRoot.dataset.tablePageNumber,pageSize:tableRoot.dataset.tablePageSize,hiddenColumns:JSON.parse(tableRoot.dataset.tableHiddenColumns)},resetContent).then((data=>{const placeholder=document.createElement("div");return placeholder.innerHTML=data.html,tableRoot.replaceWith(...placeholder.childNodes),getTableFromId(tableRoot.dataset.tableUniqueid)})).then((tableRoot=>(tableRoot.dispatchEvent(new CustomEvent(_events.default.tableContentRefreshed,{bubbles:!0})),tableRoot))).then((tableRoot=>(pendingPromise.resolve(),tableRoot)))};_exports.refreshTableContent=refreshTableContent;const updateTable=function(tableRoot){let{sortBy:sortBy=null,sortOrder:sortOrder=null,filters:filters=null,firstInitial:firstInitial=null,lastInitial:lastInitial=null,pageNumber:pageNumber=null,pageSize:pageSize=null,hiddenColumns:hiddenColumns=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];checkTableIsDynamic(tableRoot);const pendingPromise=new _pending.default("core_table/dynamic:updateTable");let tableConfigChanged=!1;if(sortBy&&sortOrder){tableConfigChanged=!0;const sortData=JSON.parse(tableRoot.dataset.tableSortData);sortData.unshift({sortby:sortBy,sortorder:parseInt(sortOrder,10)}),tableRoot.dataset.tableSortData=JSON.stringify(sortData)}if(null!==firstInitial&&(tableRoot.dataset.tableFirstInitial!==firstInitial&&(tableConfigChanged=!0),tableRoot.dataset.tableFirstInitial=firstInitial),null!==lastInitial&&(tableRoot.dataset.tableLastInitial!==lastInitial&&(tableConfigChanged=!0),tableRoot.dataset.tableLastInitial=lastInitial),null!==pageSize&&(tableRoot.dataset.tablePageSize!=pageSize&&(tableConfigChanged=!0),tableRoot.dataset.tablePageSize=pageSize),filters){const filterJson=JSON.stringify(filters);tableRoot.dataset.tableFilters!==filterJson&&(tableConfigChanged=!0),tableRoot.dataset.tableFilters=filterJson}if(tableConfigChanged&&(pageNumber=1),hiddenColumns){const columnJson=JSON.stringify(hiddenColumns);tableRoot.dataset.tableHiddenColumns!==columnJson&&(tableConfigChanged=!0),tableRoot.dataset.tableHiddenColumns=columnJson}return null!==pageNumber&&(tableRoot.dataset.tablePageNumber!=pageNumber&&(tableConfigChanged=!0),tableRoot.dataset.tablePageNumber=pageNumber),refreshContent&&tableConfigChanged?refreshTableContent(tableRoot).then((tableRoot=>(pendingPromise.resolve(),tableRoot))):(pendingPromise.resolve(),Promise.resolve(tableRoot))};_exports.updateTable=updateTable;const getTableData=tableRoot=>(checkTableIsDynamic(tableRoot),tableRoot.dataset);_exports.setFilters=function(tableRoot,filters){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return updateTable(tableRoot,{filters:filters},refreshContent)};_exports.getFilters=tableRoot=>(checkTableIsDynamic(tableRoot),getFiltersetFromTable(tableRoot));const setSortOrder=function(tableRoot,sortBy,sortOrder){let refreshContent=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return updateTable(tableRoot,{sortBy:sortBy,sortOrder:sortOrder},refreshContent)};_exports.setSortOrder=setSortOrder;const setPageNumber=function(tableRoot,pageNumber){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return updateTable(tableRoot,{pageNumber:pageNumber},refreshContent)};_exports.setPageNumber=setPageNumber;_exports.getPageNumber=tableRoot=>getTableData(tableRoot).tablePageNumber;const setPageSize=function(tableRoot,pageSize){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return updateTable(tableRoot,{pageSize:pageSize,pageNumber:1},refreshContent)};_exports.setPageSize=setPageSize;_exports.getPageSize=tableRoot=>getTableData(tableRoot).tablePageSize;const setFirstInitial=function(tableRoot,firstInitial){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return updateTable(tableRoot,{firstInitial:firstInitial},refreshContent)};_exports.setFirstInitial=setFirstInitial;_exports.getFirstInitial=tableRoot=>getTableData(tableRoot).tableFirstInitial;const setLastInitial=function(tableRoot,lastInitial){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return updateTable(tableRoot,{lastInitial:lastInitial},refreshContent)};_exports.setLastInitial=setLastInitial;_exports.getLastInitial=tableRoot=>getTableData(tableRoot).tableLastInitial;const hideColumn=function(tableRoot,columnToHide){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const hiddenColumns=JSON.parse(tableRoot.dataset.tableHiddenColumns);return hiddenColumns.push(columnToHide),updateTable(tableRoot,{hiddenColumns:hiddenColumns},refreshContent)};_exports.hideColumn=hideColumn;const showColumn=function(tableRoot,columnToShow){let refreshContent=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],hiddenColumns=JSON.parse(tableRoot.dataset.tableHiddenColumns);return hiddenColumns=hiddenColumns.filter((columnName=>columnName!==columnToShow)),updateTable(tableRoot,{hiddenColumns:hiddenColumns},refreshContent)};_exports.showColumn=showColumn;_exports.init=()=>{watching||(watching=!0,document.addEventListener("click",(e=>{const tableRoot=e.target.closest(Selectors.main.region);if(!tableRoot)return;const sortableLink=e.target.closest(Selectors.table.links.sortableColumn);sortableLink&&(e.preventDefault(),setSortOrder(tableRoot,sortableLink.dataset.sortby,sortableLink.dataset.sortorder).catch(_notification.default.exception));const firstInitialLink=e.target.closest(Selectors.initialsBar.links.firstInitial);null!==firstInitialLink&&(e.preventDefault(),setFirstInitial(tableRoot,firstInitialLink.dataset.initial).catch(_notification.default.exception));const lastInitialLink=e.target.closest(Selectors.initialsBar.links.lastInitial);null!==lastInitialLink&&(e.preventDefault(),setLastInitial(tableRoot,lastInitialLink.dataset.initial).catch(_notification.default.exception));const pageItem=e.target.closest(Selectors.paginationBar.links.pageItem);pageItem&&(e.preventDefault(),setPageNumber(tableRoot,pageItem.dataset.pageNumber).catch(_notification.default.exception));const hide=e.target.closest(Selectors.table.links.hide);hide&&(e.preventDefault(),hideColumn(tableRoot,hide.dataset.column).catch(_notification.default.exception));const show=e.target.closest(Selectors.table.links.show);show&&(e.preventDefault(),showColumn(tableRoot,show.dataset.column).catch(_notification.default.exception));e.target.closest(".resettable a")&&(e.preventDefault(),(tableRoot=>refreshTableContent(tableRoot,!0))(tableRoot).catch(_notification.default.exception));const showCountLink=e.target.closest(Selectors.showCount.links.toggle);showCountLink&&(e.preventDefault(),setPageSize(tableRoot,showCountLink.dataset.targetPageSize).catch(_notification.default.exception))})))};const getTableFromId=tableRegionId=>{const tableRoot=document.querySelector(Selectors.main.fromRegionId(tableRegionId));if(!tableRoot)throw new Error("The table specified is not a dynamic table and cannot be updated");return tableRoot};_exports.getTableFromId=getTableFromId})); define("core_table/local/dynamic/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var eventName,_default={tableContentRefreshed:(eventName="tableContentRefreshed","core_table/dynamic:".concat(eventName))};return _exports.default=_default,_exports.default})); define("core_table/local/dynamic/repository",["exports","core/ajax"],(function(_exports,_ajax){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.fetch=void 0;_exports.fetch=function(component,handler,uniqueid){let{sortData:sortData=[],joinType:joinType=null,filters:filters={},firstinitial:firstinitial=null,lastinitial:lastinitial=null,pageNumber:pageNumber=null,pageSize:pageSize=null,hiddenColumns:hiddenColumns={}}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},resetPreferences=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return(0,_ajax.call)([{methodname:"core_table_get_dynamic_table_content",args:{component:component,handler:handler,uniqueid:uniqueid,sortdata:sortData,jointype:joinType,filters:filters,firstinitial:firstinitial,lastinitial:lastinitial,pagenumber:pageNumber,pagesize:pageSize,hiddencolumns:hiddenColumns,resetpreferences:resetPreferences}}])[0]}})); define("core_table/local/dynamic/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={main:{region:'[data-region="core_table/dynamic"]',fromRegionId:regionId=>'[data-region="core_table/dynamic"][data-table-uniqueid="'.concat(regionId,'"]')},table:{links:{sortableColumn:'a[data-sortable="1"]',hide:'a[data-action="hide"]',show:'a[data-action="show"]'}},initialsBar:{links:{firstInitial:".firstinitial [data-initial]",lastInitial:".lastinitial [data-initial]"}},paginationBar:{links:{pageItem:".pagination [data-page-number]"}},showCount:{links:{toggle:'[data-action="showcount"]'}}},_exports.default})); define("core_user/local/participants/bulkactions",["exports","core_user/repository","core/str","core/modal_events","core/modal_factory","core/notification","core/templates","core/toast"],(function(_exports,Repository,Str,_modal_events,_modal_factory,_notification,_templates,_toast){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Bulk actions for lists of participants. * * @module core_user/local/participants/bulkactions * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.showSendMessage=_exports.showAddNote=void 0,Repository=_interopRequireWildcard(Repository),Str=_interopRequireWildcard(Str),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates);_exports.showAddNote=(courseid,users,noteStateNames,stateHelpIcon)=>{if(!users.length)return Promise.resolve();const states=[];for(let key in noteStateNames)switch(key){case"draft":states.push({value:"personal",label:noteStateNames[key]});break;case"public":states.push({value:"course",label:noteStateNames[key],selected:1});break;case"site":states.push({value:key,label:noteStateNames[key]})}const context={stateNames:states,stateHelpIcon:stateHelpIcon.innerHTML};let titlePromise=null;return titlePromise=1===users.length?Str.get_string("addbulknotesingle","core_notes"):Str.get_string("addbulknote","core_notes",users.length),_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,body:_templates.default.render("core_user/add_bulk_note",context),title:titlePromise,buttons:{save:titlePromise},removeOnClose:!0}).then((modal=>(modal.getRoot().on(_modal_events.default.save,(()=>submitAddNote(courseid,users,modal))),modal.show(),modal)))};const submitAddNote=(courseid,users,modal)=>{const text=modal.getRoot().find("form textarea").val(),publishstate=modal.getRoot().find("form select").val(),notes=users.map((userid=>({userid:userid,text:text,courseid:courseid,publishstate:publishstate})));return Repository.createNotesForUsers(notes).then((noteIds=>1===noteIds.length?Str.get_string("addbulknotedonesingle","core_notes"):Str.get_string("addbulknotedone","core_notes",noteIds.length))).then((msg=>(0,_toast.add)(msg))).catch(_notification.default.exception)};_exports.showSendMessage=users=>{if(!users.length)return Promise.resolve();let titlePromise;return titlePromise=1===users.length?Str.get_string("sendbulkmessagesingle","core_message"):Str.get_string("sendbulkmessage","core_message",users.length),_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,body:_templates.default.render("core_user/send_bulk_message",{}),title:titlePromise,buttons:{save:titlePromise},removeOnClose:!0}).then((modal=>(modal.getRoot().on(_modal_events.default.save,(e=>{const text=modal.getRoot().find("form textarea").val();if(""===text.trim())return modal.getRoot().find('[data-role="messagetextrequired"]').removeAttr("hidden"),void e.preventDefault();submitSendMessage(modal,users,text)})),modal.show(),modal)))};const submitSendMessage=(modal,users,text)=>{const messages=users.map((touserid=>({touserid:touserid,text:text})));return Repository.sendMessagesToUsers(messages).then((messageIds=>1==messageIds.length?Str.get_string("sendbulkmessagesentsingle","core_message"):Str.get_string("sendbulkmessagesent","core_message",messageIds.length))).then((msg=>(0,_toast.add)(msg))).catch(_notification.default.exception)}})); define("core_user/participants",["exports","core_table/dynamic","core/str","core/checkbox-toggleall","core/custom_interaction_events","core_table/local/dynamic/selectors","core/modal_events","core/notification","core/pending","jquery","core_user/local/participants/bulkactions","core/inplace_editable"],(function(_exports,DynamicTable,Str,_checkboxToggleall,_custom_interaction_events,_selectors,_modal_events,_notification,_pending,_jquery,_bulkactions,_inplace_editable){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Some UI stuff for participants page. * This is also used by the report/participants/index.php because it has the same functionality. * * @module core_user/participants * @copyright 2017 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,DynamicTable=_interopRequireWildcard(DynamicTable),Str=_interopRequireWildcard(Str),_checkboxToggleall=_interopRequireDefault(_checkboxToggleall),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_selectors=_interopRequireDefault(_selectors),_modal_events=_interopRequireDefault(_modal_events),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending),_jquery=_interopRequireDefault(_jquery);const Selectors_bulkActionSelect="#formactionid",Selectors_bulkUserSelectedCheckBoxes="input[data-togglegroup='participants-table'][data-toggle='slave']:checked",Selectors_checkCountButton="#checkall",Selectors_showCountText='[data-region="participant-count"]',Selectors_stateHelpIcon='[data-region="state-help-icon"]',Selectors_tableForm=uniqueId=>'form[data-table-unique-id="'.concat(uniqueId,'"]');_exports.init=_ref=>{let{uniqueid:uniqueid,noteStateNames:noteStateNames={}}=_ref;const root=document.querySelector(Selectors_tableForm(uniqueid)),getTableFromUniqueId=uniqueId=>root.querySelector(_selectors.default.main.fromRegionId(uniqueId)),resetBulkAction=bulkActionSelect=>{bulkActionSelect.value=""};_custom_interaction_events.default.define(Selectors_bulkActionSelect,[_custom_interaction_events.default.events.accessibleChange]),(0,_jquery.default)(Selectors_bulkActionSelect).on(_custom_interaction_events.default.events.accessibleChange,(e=>{const bulkActionSelect=e.target.closest("select"),action=bulkActionSelect.value,checkboxes=getTableFromUniqueId(uniqueid).querySelectorAll(Selectors_bulkUserSelectedCheckBoxes),pendingPromise=new _pending.default("core_user/participants:bulkActionSelect");if(-1!==action.indexOf("#")){e.preventDefault();const ids=[];let bulkAction;if(checkboxes.forEach((checkbox=>{ids.push(checkbox.getAttribute("name").replace("user",""))})),"#messageselect"===action?bulkAction=(0,_bulkactions.showSendMessage)(ids):"#addgroupnote"===action&&(bulkAction=(0,_bulkactions.showAddNote)(root.dataset.courseId,ids,noteStateNames,root.querySelector(Selectors_stateHelpIcon))),bulkAction){const pendingBulkAction=new _pending.default("core_user/participants:bulkActionSelected");bulkAction.then((modal=>(modal.getRoot().on(_modal_events.default.hidden,(()=>{bulkActionSelect.focus()})),pendingBulkAction.resolve(),modal))).catch(_notification.default.exception)}}else""!==action&&checkboxes.length&&bulkActionSelect.form.submit();resetBulkAction(bulkActionSelect),pendingPromise.resolve()})),root.addEventListener("click",(e=>{const checkCountButton=root.querySelector(Selectors_checkCountButton);if(checkCountButton&&checkCountButton.contains(e.target)){e.preventDefault();const tableRoot=getTableFromUniqueId(uniqueid);DynamicTable.setPageSize(tableRoot,checkCountButton.dataset.targetPageSize).then((tableRoot=>(_checkboxToggleall.default.setGroupState(root,"participants-table",!0),tableRoot))).catch(_notification.default.exception)}})),root.addEventListener(DynamicTable.Events.tableContentRefreshed,(e=>{const checkCountButton=root.querySelector(Selectors_checkCountButton),tableRoot=e.target,defaultPageSize=parseInt(tableRoot.dataset.tableDefaultPerPage,10),currentPageSize=parseInt(tableRoot.dataset.tablePageSize,10),totalRowCount=parseInt(tableRoot.dataset.tableTotalRows,10);_checkboxToggleall.default.updateSlavesFromMasterState(root,"participants-table");const pageCountStrings=[{key:"countparticipantsfound",component:"core_user",param:totalRowCount}];totalRowCount<=defaultPageSize?checkCountButton&&checkCountButton.classList.add("hidden"):totalRowCount<=currentPageSize?(pageCountStrings.push({key:"selectalluserswithcount",component:"core",param:defaultPageSize}),checkCountButton&&checkCountButton.classList.add("hidden")):(pageCountStrings.push({key:"selectalluserswithcount",component:"core",param:totalRowCount}),checkCountButton&&checkCountButton.classList.remove("hidden")),Str.get_strings(pageCountStrings).then((_ref2=>{let[showingParticipantCountString,selectCountString]=_ref2;root.querySelector(Selectors_showCountText).innerHTML=showingParticipantCountString,selectCountString&&checkCountButton&&(checkCountButton.value=selectCountString)})).catch(_notification.default.exception)}))}})); define("core_user/participants_filter",["exports","core/datafilter","core_table/dynamic","core/datafilter/selectors","core/notification","core/pending"],(function(_exports,_datafilter,DynamicTable,_selectors,_notification,_pending){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Participants filter management. * * @module core_user/participants_filter * @copyright 2021 Tomo Tsuyuki <tomotsuyuki@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_datafilter=_interopRequireDefault(_datafilter),DynamicTable=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(DynamicTable),_selectors=_interopRequireDefault(_selectors),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);_exports.init=filterRegionId=>{const filterSet=document.getElementById(filterRegionId),coreFilter=new _datafilter.default(filterSet,(function(filters,pendingPromise){DynamicTable.setFilters(DynamicTable.getTableFromId(filterSet.dataset.tableRegion),{jointype:parseInt(filterSet.querySelector(_selectors.default.filterset.fields.join).value,10),filters:filters}).then((result=>(pendingPromise.resolve(),result))).catch(_notification.default.exception)}));coreFilter.init();const tableRoot=DynamicTable.getTableFromId(filterSet.dataset.tableRegion),initialFilters=DynamicTable.getFilters(tableRoot);if(initialFilters){const initialFilterPromise=new _pending.default("core/filter:setFilterFromConfig");(config=>{const filterConfig=Object.entries(config.filters);if(!filterConfig.length)return Promise.resolve();filterSet.querySelector(_selectors.default.filterset.fields.join).value=config.jointype;const filterPromises=filterConfig.map((_ref=>{let[filterType,filterData]=_ref;if("courseid"===filterType)return!1;const filterValues=filterData.values;return!!filterValues.length&&coreFilter.addFilterRow().then((_ref2=>{let[filterRow]=_ref2;coreFilter.addFilter(filterRow,filterType,filterValues)}))})).filter((promise=>promise));return filterPromises.length?Promise.all(filterPromises).then((()=>coreFilter.removeEmptyFilters())).then((()=>{coreFilter.updateFiltersOptions()})).then((()=>{coreFilter.updateTableFromFilter()})):Promise.resolve()})(initialFilters).then((()=>initialFilterPromise.resolve())).catch()}}})); define("core_user/status_field",["exports","core_table/dynamic","./repository","core/str","core_table/local/dynamic/selectors","core/fragment","core/modal_events","core/modal_factory","core/notification","core/templates","core/toast"],(function(_exports,DynamicTable,Repository,Str,_selectors,_fragment,_modal_events,_modal_factory,_notification,_templates,_toast){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * AMD module for the user enrolment status field in the course participants page. * * @module core_user/status_field * @copyright 2017 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,DynamicTable=_interopRequireWildcard(DynamicTable),Repository=_interopRequireWildcard(Repository),Str=_interopRequireWildcard(Str),_selectors=_interopRequireDefault(_selectors),_fragment=_interopRequireDefault(_fragment),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates);const Selectors_editEnrolment='[data-action="editenrolment"]',Selectors_showDetails='[data-action="showdetails"]',Selectors_unenrol='[data-action="unenrol"]',Selectors_statusElement="[data-status]",getDynamicTableFromLink=link=>link.closest(_selectors.default.main.region),getStatusContainer=link=>link.closest(Selectors_statusElement),getUserEnrolmentIdFromLink=link=>link.getAttribute("rel"),showEditDialogue=(link,getBody)=>{const container=getStatusContainer(link),userEnrolmentId=getUserEnrolmentIdFromLink(link);_modal_factory.default.create({large:!0,title:Str.get_string("edituserenrolment","enrol",container.dataset.fullname),type:_modal_factory.default.types.SAVE_CANCEL,body:getBody(userEnrolmentId)}).then((modal=>(modal.getRoot().on(_modal_events.default.save,(e=>{e.preventDefault(),submitEditFormAjax(link,getBody,modal,userEnrolmentId,container.dataset)})),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy()})),modal.show(),modal))).catch(_notification.default.exception)},showUnenrolConfirmation=link=>{const container=getStatusContainer(link),userEnrolmentId=getUserEnrolmentIdFromLink(link);_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL}).then((modal=>{modal.getRoot().on(_modal_events.default.save,(e=>{e.preventDefault(),submitUnenrolFormAjax(link,modal,{ueid:userEnrolmentId},container.dataset)})),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy()})),modal.show();const stringData=[{key:"unenrol",component:"enrol"},{key:"unenrolconfirm",component:"enrol",param:{user:container.dataset.fullname,course:container.dataset.coursename,enrolinstancename:container.dataset.enrolinstancename}}];return Promise.all([Str.get_strings(stringData),modal])})).then((_ref=>{let[strings,modal]=_ref;return modal.setTitle(strings[0]),modal.setSaveButtonText(strings[0]),modal.setBody(strings[1]),modal})).catch(_notification.default.exception)},showStatusDetails=link=>{const container=getStatusContainer(link),context={editenrollink:"",statusclass:container.querySelector("span.badge").getAttribute("class"),...container.dataset},editEnrolLink=container.querySelector(Selectors_editEnrolment);editEnrolLink&&(context.editenrollink=editEnrolLink.outerHTML),_modal_factory.default.create({large:!0,type:_modal_factory.default.types.CANCEL,title:Str.get_string("enroldetails","enrol"),body:_templates.default.render("core_user/status_details",context)}).then((modal=>(editEnrolLink&&modal.getRoot().on("click",Selectors_editEnrolment,(e=>{e.preventDefault(),modal.hide(),editEnrolLink.click()})),modal.show(),modal.getRoot().on(_modal_events.default.hidden,(()=>modal.destroy())),modal))).catch(_notification.default.exception)},submitEditFormAjax=(clickedLink,getBody,modal,userEnrolmentId,userData)=>{const form=modal.getRoot().find("form");Repository.submitUserEnrolmentForm(form.serialize()).then((data=>{if(!data.result)throw data.result;return modal.hide(),modal.destroy(),data})).then((()=>(DynamicTable.refreshTableContent(getDynamicTableFromLink(clickedLink)).catch(_notification.default.exception),Str.get_string("enrolmentupdatedforuser","core_enrol",userData)))).then((notificationString=>{(0,_toast.add)(notificationString)})).catch((()=>(modal.setBody(getBody(userEnrolmentId,JSON.stringify(form.serialize()))),modal)))},submitUnenrolFormAjax=(clickedLink,modal,args,userData)=>{Repository.unenrolUser(args.ueid).then((data=>data.result?(modal.hide(),modal.destroy(),data):(_notification.default.alert(data.errors[0].key,data.errors[0].message),data))).then((()=>(DynamicTable.refreshTableContent(getDynamicTableFromLink(clickedLink)).catch(_notification.default.exception),Str.get_string("unenrolleduser","core_enrol",userData)))).then((notificationString=>{(0,_toast.add)(notificationString)})).catch(_notification.default.exception)},getBody=function(contextId,ueid){let formdata=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return _fragment.default.loadFragment("enrol","user_enrolment_form",contextId,{ueid:ueid,formdata:formdata})};_exports.init=_ref2=>{let{contextid:contextid,uniqueid:uniqueid}=_ref2;((contextId,uniqueId)=>{const getBodyFunction=(userEnrolmentId,formData)=>getBody(contextId,userEnrolmentId,formData);document.addEventListener("click",(e=>{if(!e.target.closest(_selectors.default.main.fromRegionId(uniqueId)))return;const editLink=e.target.closest(Selectors_editEnrolment);editLink&&(e.preventDefault(),showEditDialogue(editLink,getBodyFunction));const unenrolLink=e.target.closest(Selectors_unenrol);unenrolLink&&(e.preventDefault(),showUnenrolConfirmation(unenrolLink));const showDetailsLink=e.target.closest(Selectors_showDetails);showDetailsLink&&(e.preventDefault(),showStatusDetails(showDetailsLink))}))})(contextid,uniqueid)}})); define("core_user/edit_profile_fields",["exports","core_form/modalform","core/str"],(function(_exports,_modalform,_str){var obj; /** * User profile fields editor * * @module core_user/edit_profile_fields * @copyright 2021 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=(obj=_modalform)&&obj.__esModule?obj:{default:obj};const Selectors_actions={editCategory:'[data-action="editcategory"]',editField:'[data-action="editfield"]',createField:'[data-action="createfield"]'};_exports.init=()=>{document.addEventListener("click",(function(e){let element=e.target.closest(Selectors_actions.editCategory);if(element){e.preventDefault();const title=element.getAttribute("data-id")?(0,_str.get_string)("profileeditcategory","admin",element.getAttribute("data-name")):(0,_str.get_string)("profilecreatenewcategory","admin"),form=new _modalform.default({formClass:"core_user\\form\\profile_category_form",args:{id:element.getAttribute("data-id")},modalConfig:{title:title},returnFocus:element});form.addEventListener(form.events.FORM_SUBMITTED,(()=>window.location.reload())),form.show()}if(element=e.target.closest(Selectors_actions.editField),element){e.preventDefault();const form=new _modalform.default({formClass:"core_user\\form\\profile_field_form",args:{id:element.getAttribute("data-id")},modalConfig:{title:(0,_str.get_string)("profileeditfield","admin",element.getAttribute("data-name"))},returnFocus:element});form.addEventListener(form.events.FORM_SUBMITTED,(()=>window.location.reload())),form.show()}if(element=e.target.closest(Selectors_actions.createField),element){e.preventDefault();const form=new _modalform.default({formClass:"core_user\\form\\profile_field_form",args:{datatype:element.getAttribute("data-datatype"),categoryid:element.getAttribute("data-categoryid")},modalConfig:{title:(0,_str.get_string)("profilecreatenewfield","admin",element.getAttribute("data-datatypename"))},returnFocus:element});form.addEventListener(form.events.FORM_SUBMITTED,(()=>window.location.reload())),form.show()}}))}})); define("core_user/form_user_selector",["exports","core/ajax","core/templates","core/str"],(function(_exports,_ajax,_templates,_str){var obj; /** * Provides the required functionality for an autocomplete element to select a user. * * @module core_user/form_user_selector * @copyright 2020 David Mudrák <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.processResults=function(selector,results){return Array.isArray(results)?results.map((result=>({value:result.id,label:result.label}))):results},_exports.transport=async function(selector,query,callback,failure){const request={methodname:"core_user_search_identity",args:{query:query}};try{const response=await _ajax.default.call([request])[0];if(response.overflow){const msg=await(0,_str.get_string)("toomanyuserstoshow","core",">"+response.maxusersperpage);callback(msg)}else{let labels=[];response.list.forEach((user=>{labels.push((0,_templates.render)("core_user/form_user_selector_suggestion",user))})),labels=await Promise.all(labels),response.list.forEach(((user,index)=>{user.label=labels[index]})),callback(response.list)}}catch(e){failure(e)}},_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj}})); define("core_user/private_files",["exports","core_form/dynamicform","core_form/modalform","core/str","core/toast"],(function(_exports,_dynamicform,_modalform,_str,_toast){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Module to handle AJAX interactions with user private files * * @module core_user/private_files * @copyright 2020 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initModal=_exports.initDynamicForm=void 0,_dynamicform=_interopRequireDefault(_dynamicform),_modalform=_interopRequireDefault(_modalform);_exports.initDynamicForm=(containerSelector,formClass)=>{const form=new _dynamicform.default(document.querySelector(containerSelector),formClass);form.addEventListener(form.events.FORM_SUBMITTED,(()=>{form.load(),(0,_str.get_string)("changessaved").then(_toast.add).catch(null)})),form.addEventListener(form.events.CANCEL_BUTTON_PRESSED,(()=>window.location.reload()))};_exports.initModal=(elementSelector,formClass)=>{document.querySelector(elementSelector).addEventListener("click",(function(e){e.preventDefault();const form=new _modalform.default({formClass:formClass,args:{nosubmit:!0},modalConfig:{title:(0,_str.get_string)("privatefilesmanage")},returnFocus:e.target});form.addEventListener(form.events.FORM_SUBMITTED,(()=>window.location.reload())),form.show()}))}})); define("core_user/repository",["exports","core/ajax"],(function(_exports,_ajax){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.unenrolUser=_exports.submitUserEnrolmentForm=_exports.sendMessagesToUsers=_exports.createNotesForUsers=void 0;_exports.unenrolUser=userEnrolmentId=>(0,_ajax.call)([{methodname:"core_enrol_unenrol_user_enrolment",args:{ueid:userEnrolmentId}}])[0];_exports.submitUserEnrolmentForm=formdata=>(0,_ajax.call)([{methodname:"core_enrol_submit_user_enrolment_form",args:{formdata:formdata}}])[0];_exports.createNotesForUsers=notes=>(0,_ajax.call)([{methodname:"core_notes_create_notes",args:{notes:notes}}])[0];_exports.sendMessagesToUsers=messages=>(0,_ajax.call)([{methodname:"core_message_send_instant_messages",args:{messages:messages}}])[0]})); /** * JavaScript for filling in the question text with the contents of one * of the question's support files. Intended primarily for program contest * problems, where the support file is a single domjudge or ICPC problem zip, * with the problem spec within it. * * @module qtype_coderunner/ajaxquestionloader * @copyright Richard Lobb, 2019, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ajaxquestionloader",["jquery"],(function($){return{loadQuestionText:function(qid,divId,questionFilename){var questionTextDiv=$("#"+divId),errorDiv='<div style="colour:red">Failed to load problem spec<div>';1==questionTextDiv.length?$.getJSON(M.cfg.wwwroot+"/question/type/coderunner/problemspec.php",{questionid:qid,sesskey:M.cfg.sesskey,filename:questionFilename},(function(response){response.filecontentsb64?questionTextDiv.append('<div><a download href="data:application/pdf;base64,'+response.filecontentsb64+'">Problem spec</a></div>'):questionTextDiv.append(errorDiv)})).fail((function(){questionTextDiv.append(errorDiv)})):questionTextDiv.append(errorDiv)}}})); /** * Implementation of the gapfiller_ui user interface plugin. For overall details * of the UI plugin architecture, see userinterfacewrapper.js. * * This plugin replaces the usual textarea answer box with a div * consisting of pre-formatted text supplied by the question author in either the * "globalextra" field or the testcode field of the first test case, according * to the ui parameter ui_source (default: globalextra). HTML * entry or textarea elements are then inserted at * specified points. It is intended primarily for use with coding questions * where the answerbox presents the students with code that has smallish bits * missing. * * The locations within the globalextra text at which the input elements are * to be inserted are denoted by "tags" of the form * * {[ size ]} * * for an HTML input element * * or * * {[ rows, columns ]} * * for a textarea element * * where size, rows and column are integer literals. These respectively * inject an HTML input element or a textarea element of the * specified size. * * The serialisation of the answer box contents, i.e. the text that * copied back into the textarea for submissions * as the answer, is simply a list of all the field values (strings), in order. * * As a special case of the serialisation, if the value list is empty, the * serialisation itself is the empty string. * * The delimiters for the input element insertion tags are by default '{[' and * ']}', but can be changed by an optional ui parameter gap_filler_delimiters, * which must be a 2-element array of strings. For example: * * {"gap_filler_delimiters": ["{{", "}}"]} * * Note that the double-brace delimiters in that example are the same as those * used by Twig, so using them instead of the default would prevent you from * ever adding Twig expansion (e.g. for randomisation) to the question. * * @module qtype_coderunner/ui_gapfiller * @copyright Richard Lobb, 2019, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_gapfiller",["jquery"],(function($){function GapfillerUi(textareaId,width,height,uiParams){var html;this.textArea=$(document.getElementById(textareaId)),this.readOnly=this.textArea.prop("readonly"),this.uiParams=uiParams,this.fail=!1,this.htmlDiv=null,this.source=uiParams.ui_source||"globalextra","globalextra"!==this.source&&"test0"!==this.source&&(alert("Invalid source for HTML in ui_gapfiller"),this.source="globalextra"),html="globalextra"==this.source?this.textArea.attr("data-globalextra"):this.textArea.attr("data-test0"),this.html=html.replace("<","<"),this.reload()}return GapfillerUi.prototype.failed=function(){return this.fail},GapfillerUi.prototype.sync=function(){var serialisation=[],empty=!0;this.getFields().each((function(){var value;"cr_gapfiller_field"!==$(this).attr("name")?alert("Unexpected UI element found in answer box"):(value=$(this).val(),serialisation.push(value),""!==value&&(empty=!1))})),empty?this.textArea.val(""):this.textArea.val(JSON.stringify(serialisation))},GapfillerUi.prototype.getElement=function(){return this.htmlDiv},GapfillerUi.prototype.getFields=function(){return $(this.htmlDiv).find(".coderunner-ui-element")},GapfillerUi.prototype.setField=function(field,value){"checkbox"===field.attr("type")||"radio"===field.attr("type")?field.prop("checked",field.val()===value):field.val(value)},GapfillerUi.prototype.markedUpHtml=function(){function reEscape(s){for(var c,result="",i=0;i<s.length;i++){c=s[i];for(var j=0;j<"{[(*+\\".length;j++)c==="{[(*+\\"[j]&&(c="\\"+c);result+=c}return result}var i,sepLeft=reEscape("{["),sepRight=reEscape("]}"),splitter=new RegExp(sepLeft+" *((?:\\d+)|(?:\\d+, *\\d+)) *"+sepRight),bits=this.html.split(splitter),result="<pre>"+bits[0];for(i=1;i<bits.length;i+=2)result+=this.markUp(bits[i]),i+1<bits.length&&(result+=bits[i+1]);return result+="</pre>"},GapfillerUi.prototype.markUp=function(tagContents){var numbers,rows,cols,result="";return 1==(numbers=tagContents.split(",")).length?result='<input name="cr_gapfiller_field" class="coderunner-ui-element" size="'+parseInt(numbers[0])+'">':(rows=parseInt(numbers[0]),cols=parseInt(numbers[1]),result='<textarea name="cr_gapfiller_field" class ="coderunner-ui-element" rows="'+rows+'" cols="'+cols+'" style="width:auto;"></textarea>'),result},GapfillerUi.prototype.reload=function(){var value,values,i,fields,content=$(this.textArea).val();if(this.htmlDiv=$("<div style='height:fit-content' class='qtype-coderunner-html-outer-div'>"+this.markedUpHtml()+"</div>"),content)try{for(values=JSON.parse(content),fields=this.getFields(),i=0;i<fields.length;i++)value=i<values.length?values[i]:"???",this.setField($(fields[i]),value)}catch(e){}},GapfillerUi.prototype.resize=function(){},GapfillerUi.prototype.hasFocus=function(){var focused=!1;return this.getFields().each((function(){this===document.activeElement&&(focused=!0)})),focused},GapfillerUi.prototype.destroy=function(){this.sync(),$(this.htmlDiv).remove(),this.htmlDiv=null},{Constructor:GapfillerUi}})); /** * Implementation of the ace_gapfiller_ui user interface plugin. For overall details * of the UI plugin architecture, see userinterfacewrapper.js. * * This plugin uses the usual ace editor but only makes some portions of the text editable. * The pre-formatted text is supplied by the question author in either the * "globalextra" field or the testcode field of the first test case, according * to the ui parameter ui_source (default: globalextra). * Editable "gaps" are inserted into the ace editor at specified points. * It is intended primarily for use with coding questions where the answerbox presents * the students with code that has smallish bits missing. * * The locations within the globalextra text at which the gaps are * to be inserted are denoted by "tags" of the form * * {[ size ]} * * or * * {[ size-maxSize ]} * * where size and maxSize are integer literals. These respectively inject a "gap" into * the editor of the specified size and maxSize. If maxSize is not specified then the * "gap" has no maximum size and can grow without bound. * * The serialisation of the answer box contents, i.e. the text that * copied back into the textarea for submissions * as the answer, is simply a list of all the field values (strings), in order. * * As a special case of the serialisation, if the value list is empty, the * serialisation itself is the empty string. * * The delimiters for the gap tags are by default '{[' and * ']}'. * * @module qtype_coderunner/ui_ace_gapfiller * @copyright Richard Lobb, 2019, The University of Canterbury * @copyright Matthew Toohey, 2021, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_ace_gapfiller",["jquery"],(function($){var Range;const validChars=/[ !"#$%&'()*+,`\-./0-9:;<=>?@A-Z\[\]\\^_a-z{}|~]/;function AceGapfillerUi(textareaId,w,h,uiParams){this.textArea=$(document.getElementById(textareaId));var wrapper=$(document.getElementById(textareaId+"_wrapper")),focused=this.textArea[0]===document.activeElement,lang=uiParams.lang,t=this;let code="";this.uiParams=uiParams,this.gaps=[],this.source=uiParams.ui_source||"globalextra",this.nextGapIndex=0,"globalextra"!==this.source&&"test0"!==this.source&&(alert("Invalid source for code in ui_ace_gapfiller"),this.source="globalextra"),code="globalextra"==this.source?this.textArea.attr("data-globalextra"):this.textArea.attr("data-test0");try{window.ace.require("ace/ext/language_tools"),Range=window.ace.require("ace/range").Range,this.modelist=window.ace.require("ace/ext/modelist"),this.enabled=!1,this.contents_changed=!1,this.capturingTab=!1,this.clickInProgress=!1,this.editNode=$("<div></div>"),this.editNode.css({resize:"none",height:h,width:"100%"}),this.editor=window.ace.edit(this.editNode.get(0)),this.textArea.prop("readonly")&&this.editor.setReadOnly(!0),this.editor.setOptions({displayIndentGuides:!1,dragEnabled:!1,enableBasicAutocompletion:!0,newLineMode:"unix"}),this.editor.$blockScrolling=1/0,uiParams.theme?this.editor.setTheme("ace/theme/"+uiParams.theme):this.editor.setTheme("ace/theme/textmate"),this.setLanguage(lang),this.setEventHandlers(this.textArea),this.captureTab(),this.editor.renderer.on("afterRender",(function(){var gutter=wrapper.find(".ace_gutter");gutter.hasClass("moodle-has-zindex")||(gutter.addClass("moodle-has-zindex"),focused&&(t.editor.focus(),t.editor.navigateFileEnd()),t.aceLabel=wrapper.find(".answerprompt"),t.aceLabel.attr("for","ace_"+textareaId),t.aceTextarea=wrapper.find(".ace_text-input"),t.aceTextarea.attr("id","ace_"+textareaId))})),this.createGaps(code),this.editor.commands.on("exec",(function(e){let cursor=t.editor.selection.getCursor(),commandName=e.command.name,selectionRange=t.editor.getSelectionRange(),gap=t.findCursorGap(cursor);if(commandName.startsWith("go")){if(null===gap||"gotoright"!==commandName||cursor.column!==gap.range.start.column+gap.textSize)return;t.editor.moveCursorTo(cursor.row,gap.range.end.column+1)}if(null===gap)"selectall"===commandName&&t.editor.selection.selectAll();else if("indent"===commandName){let nextGap=t.gaps[(gap.index+1)%t.gaps.length];t.editor.moveCursorTo(nextGap.range.start.row,nextGap.range.start.column+nextGap.textSize),t.editor.selection.clearSelection()}else if("selectall"===commandName)t.editor.selection.setSelectionRange(new Range(gap.range.start.row,gap.range.start.column,gap.range.start.row,gap.range.end.column),!1);else if(t.editor.selection.isEmpty()){if("insertstring"===commandName){let char=e.args;validChars.test(char)&&gap.insertChar(t.gaps,cursor,char)}else"backspace"===commandName?cursor.column>gap.range.start.column&&gap.textSize>0&&gap.deleteChar(t.gaps,{row:cursor.row,column:cursor.column-1}):"del"===commandName&&cursor.column<gap.range.start.column+gap.textSize&&gap.textSize>0&&gap.deleteChar(t.gaps,cursor);t.editor.selection.clearSelection()}else if(!t.editor.selection.isEmpty()&&gap.cursorInGap(selectionRange.start)&&gap.cursorInGap(selectionRange.end)&&("insertstring"!==commandName&&"backspace"!==commandName&&"del"!==commandName&&"paste"!==commandName&&"cut"!==commandName||(gap.deleteRange(t.gaps,selectionRange.start.column,selectionRange.end.column),t.editor.selection.clearSelection()),"insertstring"===commandName)){let char=e.args;validChars.test(char)&&gap.insertChar(t.gaps,selectionRange.start,char)}null!==gap&&"paste"===commandName&&gap.insertText(t.gaps,selectionRange.start.column,e.args.text),e.preventDefault(),e.stopPropagation()})),t.editor.selection.on("changeCursor",(function(){let cursor=t.editor.selection.getCursor(),gap=t.findCursorGap(cursor);null!==gap&&cursor.column>gap.range.start.column+gap.textSize&&t.editor.moveCursorTo(gap.range.start.row,gap.range.start.column+gap.textSize)})),this.gapToSelect=null,this.editor.on("tripleclick",(function(e){let cursor=t.editor.selection.getCursor(),gap=t.findCursorGap(cursor);null!==gap&&(t.editor.selection.setSelectionRange(new Range(gap.range.start.row,gap.range.start.column,gap.range.start.row,gap.range.end.column),!1),t.gapToSelect=gap,e.preventDefault(),e.stopPropagation())})),this.editor.on("click",(function(e){t.gapToSelect&&(t.editor.moveCursorTo(t.gapToSelect.range.start.row,t.gapToSelect.range.start.column+t.gapToSelect.textSize),t.gapToSelect=null,e.preventDefault(),e.stopPropagation())})),this.fail=!1,this.reload()}catch(err){this.fail=!0}}function Gap(editor,row,column,minWidth){let maxWidth=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1/0;this.editor=editor,this.minWidth=minWidth,this.maxWidth=maxWidth,this.range=new Range(row,column,row,column+minWidth),this.textSize=0,this.editor.session.addMarker(this.range,"ace-gap-outline","text",!0),this.editor.session.addMarker(this.range,"ace-gap-background","text",!1)}return AceGapfillerUi.prototype.createGaps=function(code){function reEscape(s){for(var c,result="",i=0;i<s.length;i++){c=s[i];for(var j=0;j<"{[(*+\\".length;j++)c==="{[(*+\\"[j]&&(c="\\"+c);result+=c}return result}this.gaps=[];let lines=code.split(/\r?\n/),sepLeft=reEscape("{["),sepRight=reEscape("]}"),splitter=new RegExp(sepLeft+" *((?:\\d+)|(?:\\d+- *\\d+)) *"+sepRight),editorContent="";for(let i=0;i<lines.length;i++){let bits=lines[i].split(splitter);editorContent+=bits[0];let columnPos=bits[0].length;for(let j=1;j<bits.length;j+=2){let values=bits[j].split("-"),minWidth=parseInt(values[0]),maxWidth=values.length>1?parseInt(values[1]):1/0,gap=new Gap(this.editor,i,columnPos,minWidth,maxWidth);gap.index=this.nextGapIndex,this.nextGapIndex+=1,this.gaps.push(gap),columnPos+=minWidth,editorContent+=" ".repeat(minWidth),j+1<bits.length&&(editorContent+=bits[j+1],columnPos+=bits[j+1].length)}i<lines.length-1&&(editorContent+="\n")}this.editor.session.setValue(editorContent)},AceGapfillerUi.prototype.findCursorGap=function(cursor){for(let i=0;i<this.gaps.length;i++){let gap=this.gaps[i];if(gap.cursorInGap(cursor))return gap}return null},AceGapfillerUi.prototype.failed=function(){return this.fail},AceGapfillerUi.prototype.failMessage=function(){return"ace_ui_notready"},AceGapfillerUi.prototype.sync=function(){if(this.fail)return;let serialisation=[],empty=!0;for(let i=0;i<this.gaps.length;i++){let value=this.gaps[i].getText();serialisation.push(value),""!==value&&(empty=!1)}empty?this.textArea.val(""):this.textArea.val(JSON.stringify(serialisation))},AceGapfillerUi.prototype.syncIntervalSecs=()=>2,AceGapfillerUi.prototype.reload=function(){let content=this.textArea.val();if(content)try{let values=JSON.parse(content);for(let i=0;i<this.gaps.length;i++){let value=i<values.length?values[i]:"???";this.gaps[i].insertText(this.gaps,this.gaps[i].range.start.column,value)}}catch(e){}},AceGapfillerUi.prototype.setLanguage=function(language){var session=this.editor.getSession(),mode=this.findMode(language);mode&&session.setMode(mode.mode)},AceGapfillerUi.prototype.getElement=function(){return this.editNode},AceGapfillerUi.prototype.captureTab=function(){this.capturingTab=!0,this.editor.commands.bindKeys({Tab:"indent","Shift-Tab":"outdent"})},AceGapfillerUi.prototype.releaseTab=function(){this.capturingTab=!1,this.editor.commands.bindKeys({Tab:null,"Shift-Tab":null})},AceGapfillerUi.prototype.setEventHandlers=function(){var t=this;this.editor.getSession().on("change",(function(){t.contents_changed=!0})),this.editor.on("blur",(function(){t.contents_changed&&t.textArea.trigger("change")})),this.editor.on("mousedown",(function(){t.clickInProgress=!0})),this.editor.on("focus",(function(){t.clickInProgress?t.captureTab():t.releaseTab()})),this.editor.on("click",(function(){t.clickInProgress=!1})),this.editor.container.addEventListener("keydown",(function(e){void 0!==e.which&&0===e.which||(77===e.keyCode&&e.ctrlKey&&!e.altKey?(t.capturingTab?t.releaseTab():t.captureTab(),e.preventDefault()):27===e.keyCode?t.releaseTab():e.shiftKey||e.ctrlKey||e.altKey||9==e.keyCode||t.captureTab())}),!0)},AceGapfillerUi.prototype.destroy=function(){var focused;this.sync(),this.fail||(focused=this.editor.isFocused(),this.editor.destroy(),$(this.editNode).remove(),focused&&(this.textArea.focus(),this.textArea[0].selectionStart=this.textArea[0].value.length))},AceGapfillerUi.prototype.hasFocus=function(){return this.editor.isFocused()},AceGapfillerUi.prototype.findMode=function(language){var candidate,filename,result,candidates,nameMap={octave:"matlab",nodejs:"javascript","c#":"cs"};if("string"==typeof language){language.toLowerCase()in nameMap&&(language=nameMap[language.toLowerCase()]),candidates=[language,language.replace(/\d+$/,"")];for(var i=0;i<candidates.length;i++)if(filename="input."+(candidate=candidates[i]),(result=this.modelist.modesByName[candidate]||this.modelist.modesByName[candidate.toLowerCase()]||this.modelist.getModeForPath(filename)||this.modelist.getModeForPath(filename.toLowerCase()))&&"text"!==result.name)return result}},AceGapfillerUi.prototype.resize=function(w,h){this.editNode.outerHeight(h),this.editNode.outerWidth(w),this.editor.resize()},Gap.prototype.cursorInGap=function(cursor){return cursor.row>=this.range.start.row&&cursor.column>=this.range.start.column&&cursor.row<=this.range.end.row&&cursor.column<=this.range.end.column},Gap.prototype.getWidth=function(){return this.range.end.column-this.range.start.column},Gap.prototype.changeWidth=function(gaps,delta){this.range.end.column+=delta;for(let i=0;i<gaps.length;i++){let other=gaps[i];other.range.start.row===this.range.start.row&&other.range.start.column>this.range.end.column&&(other.range.start.column+=delta,other.range.end.column+=delta)}this.editor.$onChangeBackMarker(),this.editor.$onChangeFrontMarker()},Gap.prototype.insertChar=function(gaps,pos,char){this.textSize===this.getWidth()&&this.getWidth()<this.maxWidth?(this.changeWidth(gaps,1),this.textSize+=1,this.editor.session.insert(pos,char)):this.textSize<this.maxWidth&&(this.editor.session.remove(new Range(pos.row,this.range.end.column-1,pos.row,this.range.end.column)),this.textSize+=1,this.editor.session.insert(pos,char))},Gap.prototype.deleteChar=function(gaps,pos){this.textSize-=1,this.editor.session.remove(new Range(pos.row,pos.column,pos.row,pos.column+1)),this.textSize>=this.minWidth?this.changeWidth(gaps,-1):this.editor.session.insert({row:pos.row,column:this.range.end.column-1}," ")},Gap.prototype.deleteRange=function(gaps,start,end){for(let i=start;i<end;i++)start<this.range.start.column+this.textSize&&this.deleteChar(gaps,{row:this.range.start.row,column:start})},Gap.prototype.insertText=function(gaps,start,text){for(let i=0;i<text.length;i++)start+i<this.range.start.column+this.maxWidth&&this.insertChar(gaps,{row:this.range.start.row,column:start+i},text[i])},Gap.prototype.getText=function(){return this.editor.session.getTextRange(new Range(this.range.start.row,this.range.start.column,this.range.end.row,this.range.start.column+this.textSize))},{Constructor:AceGapfillerUi}})); /** * JavaScript for handling UI actions in the question authoring form. * * @module qtype_coderunner/authorform * @copyright Richard Lobb, 2015, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/authorform",["jquery","qtype_coderunner/userinterfacewrapper","core/str"],(function($,ui,str){let currentQtype="";var JSON_TO_FORM_MAP={template:["#id_template","value",""],iscombinatortemplate:["#id_iscombinatortemplate","checked","",function(value){return"1"===value}],cputimelimitsecs:["#id_cputimelimitsecs","value",""],memlimitmb:["#id_memlimitmb","value",""],sandbox:["#id_sandbox","value","DEFAULT"],sandboxparams:["#id_sandboxparams","value",""],testsplitterre:["#id_testsplitterre","value","",function(splitter){return splitter.replace("\n","\\n")}],allowmultiplestdins:["#id_allowmultiplestdins","checked","",function(value){return"1"===value}],grader:["#id_grader","value","EqualityGrader"],resultcolumns:["#id_resultcolumns","value",""],language:["#id_language","value",""],acelang:["#id_acelang","value",""],uiplugin:["#id_uiplugin","value","ace"]};return{initEditForm:function(){var typeCombo=$("#id_coderunnertype"),prototypeDisplay=$("#id_isprototype"),template=$("#id_template"),evaluatePerStudent=$("#id_templateparamsevalpertry"),globalextra=$("#id_globalextra"),prototypeextra=$("#id_prototypeextra"),useace=$("#id_useace"),language=$("#id_language"),acelang=$("#id_acelang"),customise=$("#id_customise"),isCombinator=$("#id_iscombinatortemplate"),testSplitterRe=$("#id_testsplitterre"),allowMultipleStdins=$("#id_allowmultiplestdins"),customisationFieldSet=$("#id_customisationheader"),advancedCustomisation=$("#id_advancedcustomisationheader"),isCustomised=customise.prop("checked"),prototypeType=$("#id_prototypetype"),preloadHdr=$("#id_answerpreloadhdr"),courseId=$('input[name="courseid"]').prop("value"),questiontypeHelpDiv=$("#qtype-help"),precheck=$("select#id_precheck"),testtypedivs=$("div.testtype"),testsection=$("#id_testcasehdr"),brokenQuestion=$("#id_broken_question"),badQuestionLoad=$("#id_bad_question_load"),uiplugin=$("#id_uiplugin"),uiparameters=$("#id_uiparameters");function setUi(taId,uiname){var lang,uiWrapper,ta=$(document.getElementById(taId)),currentLang=ta.attr("data-lang"),paramsJson=ta.attr("data-params"),params={};ta.attr("data-prototypeextra",prototypeextra.val()),ta.attr("data-globalextra",globalextra.val()),ta.attr("data-test0",$("#id_testcode_0").val());try{params=JSON.parse(paramsJson)}catch(err){}"none"===(uiname=uiname.toLowerCase())&&(uiname=""),"id_templateparams"==taId||"id_uiparameters"==taId?lang="":(lang=language.prop("value"),"id_template"!==taId&&acelang.prop("value")&&(lang=function(acelang){var langs,i;if(acelang.indexOf(",")<0)return acelang;for(langs=acelang.split(","),i=0;i<langs.length;i++)if(langs[i].endsWith("*"))return langs[i].substr(0,langs[i].length-1);return langs.length>0?langs[0]:""}(acelang.prop("value")))),(uiWrapper=ta.data("current-ui-wrapper"))&&uiWrapper.uiname===uiname&¤tLang==lang||(ta.attr("data-lang",lang),uiWrapper?(params.lang=lang,uiWrapper.loadUi(uiname,params)):uiWrapper=new ui.InterfaceWrapper(uiname,taId))}function setUis(){let uiname=uiplugin.val(),answer=$("#id_answer"),enableUi=!0;if("html"===uiname&&""!==answer.attr("data-params"))try{!1===JSON.parse(answer.attr("data-params")).enable_in_editor&&(enableUi=!1)}catch(error){alert("Invalid UI parameters.")}enableUi&&(setUi("id_answer",uiname),setUi("id_answerpreload",uiname))}function setCustomisationVisibility(isVisible){var display=isVisible?"block":"none";customisationFieldSet.css("display",display),advancedCustomisation.css("display",display),isVisible&&useace.prop("checked")&&setUi("id_template","ace")}function copyFieldsFromQuestionType(newType,response){var formspecifier,attrval,isCombinatorEnabled;for(var key in function(stateOn){var uiWrapper,taIds=["id_template","id_uiparameters"];if(useace.prop("checked"))for(var i=0;i<taIds.length;i++)(uiWrapper=$(document.getElementById(taIds[i])).data("current-ui-wrapper"))&&stateOn?uiWrapper.restart():uiWrapper&&!stateOn&&uiWrapper.stop()}(!1),JSON_TO_FORM_MAP)formspecifier=JSON_TO_FORM_MAP[key],attrval=response[key]?response[key]:formspecifier[2],formspecifier.length>3&&(attrval=(0,formspecifier[3])(attrval)),$(formspecifier[0]).prop(formspecifier[1],attrval);customise.prop("checked",!1),str.get_string("coderunner_question_type","qtype_coderunner").then((function(s){var title,coderunner_descr,html,resultHtml;questiontypeHelpDiv.html((title=newType,coderunner_descr=s,html=response.questiontext,resultHtml='<p class="question-type-details-header">',resultHtml+=coderunner_descr,resultHtml+=title+"</p>\n"+html))})),setCustomisationVisibility(!1),isCombinatorEnabled=isCombinator.prop("checked"),testSplitterRe.prop("disabled",!isCombinatorEnabled),allowMultipleStdins.prop("disabled",!isCombinatorEnabled)}function langStringAlert(key,extra){window.hasOwnProperty("behattesting")&&window.behattesting||str.get_string(key,"qtype_coderunner").then((function(s){var message=s.replace(/\n/g," ");extra&&(message+="\n"+extra),alert(message)}))}function loadCustomisationFields(){let newType=typeCombo.children("option:selected").text();""!==newType&&"Undefined"!==newType&&(typeCombo.children("option:first-child").prop("disabled","disabled"),$.getJSON(M.cfg.wwwroot+"/question/type/coderunner/ajax.php",{qtype:newType,courseid:courseId,sesskey:M.cfg.sesskey},(function(outcome){if($("#id_qtype_coderunner_warning_div").empty(),outcome.success)copyFieldsFromQuestionType(newType,outcome),setUis(),loadUiParametersDescription(),currentQtype=newType,$("#id_qtype_coderunner_error_div").empty();else{const errorObject=function(questionType,error){const errorObject=JSON.parse(error);return str.get_string("prototype_error","qtype_coderunner").then((function(s){str.get_string(errorObject.alert,"qtype_coderunner",questionType).then((function(str){langStringAlert("prototype_load_failure",str);let errorMessage=s+"\n";errorMessage+=str+"\n",errorMessage+="CourseId: "+courseId+", qtype: "+questionType,template.prop("value",errorMessage)}))})),errorObject}(newType,outcome.error);currentQtype!==newType&&"duplicateprototype"===errorObject.error&&(!function(currentType,errorObject,newType){str.get_string("loadprototypeerror","qtype_coderunner",{oldtype:currentType,crtype:newType,outputstring:errorObject.extras}).then((function(str){$("#id_qtype_coderunner_warning_div").append($("<p>"+str+"</p>"))}))}(currentQtype,errorObject,newType),$("#id_coderunnertype").val(currentQtype))}})).fail((function(){langStringAlert("error_loading_prototype"),template.prop("value","*** AJAX ERROR. DON'T SAVE THIS! ***"),str.get_string("ajax_error","qtype_coderunner").then((function(s){template.prop("value",s)}))})))}function loadUiParametersDescription(){let newUi=uiplugin.children("option:selected").text();$.getJSON(M.cfg.wwwroot+"/question/type/coderunner/ajax.php",{uiplugin:newUi,courseid:courseId,sesskey:M.cfg.sesskey},(function(uiInfo){var table,currentuiparameters=uiparameters.val(),paramDescriptionDiv=$(".ui_parameters_descr"),showhidebutton=$('<button type="button" class="toggleuidetails">'+uiInfo.showdetails+"</button>");paramDescriptionDiv.empty(),paramDescriptionDiv.append(uiInfo.header),0==uiInfo.uiparamstable.length&&""===currentuiparameters.trim()?(uiparameters.val(""),$("#fgroup_id_uiparametergroup").hide()):(0!=uiInfo.uiparamstable.length&&(paramDescriptionDiv.append(showhidebutton),table=$(function(uiParamInfo){var param,i,html='<div class="uiparamtablediv"><table class="uiparamtable">\n',hdrs=uiParamInfo.columnheaders;for(html+="<tr><th>"+hdrs[0]+"</th><th>"+hdrs[1]+"</th><th>"+hdrs[2]+"</th></tr>\n",i=0;i<uiParamInfo.uiparamstable.length;i++)html+="<tr><td>"+(param=uiParamInfo.uiparamstable[i])[0]+"</td><td>"+param[1]+"</td><td>"+param[2]+"</td></tr>\n";return html+"</table></div>\n"}(uiInfo)),paramDescriptionDiv.append(table),table.hide(),showhidebutton.click((function(){showhidebutton.html()==uiInfo.showdetails?(table.show(),showhidebutton.html(uiInfo.hidedetails)):(table.hide(),showhidebutton.html(uiInfo.showdetails))}))),$("#fgroup_id_uiparametergroup").show(),useace.prop("checked")&&setUi("id_uiparameters","ace"))})).fail((function(){langStringAlert("error_loading_ui_descr")}))}function set_testtype_visibilities(){"3"===precheck.val()?testtypedivs.show():testtypedivs.hide()}function check_ace_lang(){"ace"===uiplugin.val()&&setUis()}0!=prototypeType.prop("value")&&(testsection.css("display","none"),prototypeDisplay.removeAttr("hidden"),1==prototypeType.prop("value")&&(str.get_string("proceed_at_own_risk","qtype_coderunner").then((function(s){alert(s)})),prototypeType.prop("disabled",!0),customise.prop("disabled",!0))),function(){let messagePara=null;""!==brokenQuestion.prop("value")&&(messagePara=$("<p>"+brokenQuestion.prop("value")+"</p>"),$("#id_qtype_coderunner_error_div").append(messagePara))}(),badQuestionLoad.prop("hidden"),currentQtype=typeCombo.children("option:selected").text(),setCustomisationVisibility(isCustomised),isCustomised?(setUis(),str.get_string("info_unavailable","qtype_coderunner").then((function(s){questiontypeHelpDiv.html("<p>"+s+"</p>")}))):loadCustomisationFields(),set_testtype_visibilities(),useace.prop("checked")&&(setUi("id_templateparams","ace"),setUi("id_uiparameters","ace")),loadUiParametersDescription(),customise.on("change",(function(){customise.prop("checked")?setCustomisationVisibility(!0):str.get_string("confirm_proceed","qtype_coderunner").then((function(s){window.confirm(s)?setCustomisationVisibility(!1):customise.prop("checked",!0)}))})),acelang.on("change",check_ace_lang),language.on("change",(function(){useace.prop("checked")&&setUi("id_template","ace"),check_ace_lang()})),typeCombo.on("change",(function(){customise.prop("checked")?str.get_string("question_type_changed","qtype_coderunner").then((function(s){window.confirm(s)&&loadCustomisationFields()})):loadCustomisationFields()})),useace.on("change",(function(){useace.prop("checked")?(setUi("id_template","ace"),setUi("id_templateparams","ace"),setUi("id_uiparameters","ace")):(setUi("id_template",""),setUi("id_templateparams",""),setUi("id_uiparameters",""))})),evaluatePerStudent.on("change",(function(){evaluatePerStudent.is(":checked")&&langStringAlert("templateparamsusingsandbox")})),uiplugin.on("change",(function(){setUis(),loadUiParametersDescription()})),precheck.on("change",set_testtype_visibilities),prototypeType.on("change",(function(){"0"==prototypeType.prop("value")?(testsection.css("display","block"),prototypeDisplay.attr("hidden","1")):(testsection.css("display","none"),prototypeDisplay.removeAttr("hidden"))})),new MutationObserver((function(){setUis()})).observe(preloadHdr.get(0),{attributes:!0}),$("button.replaceexpectedwithgot").click((function(){var gotPre=$(this).prev('pre[id^="id_got_"]'),testCaseId=gotPre.attr("id").replace("id_got_","");$("#id_expected_"+testCaseId).val(gotPre.text()),$("#id_fail_expected_"+testCaseId).html(gotPre.text()),$(".failrow_"+testCaseId).addClass("fixed"),$(this).prop("disabled",!0)})),$(".btn-primary").click((function(){typeCombo.prop("disabled",!1)}))}}})); /****************************************************************************** * * This module simply handles changes in the Language selection dropdown for * multilanguage questions as seen by students. It switches the Ace language * accordingly. * It should only be loaded in conjunction with the ui_ace module. * * @module qtype_coderunner/multilanguagequestion * @copyright Richard Lobb, 2018, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * */ define("qtype_coderunner/multilanguagequestion",["jquery","core/str"],(function($,str){let NO_LANGUAGE_MESSAGE="";return{initLangSelector:function(taId){$().ready((function(){!function(taId){const ta=$(document.getElementById(taId)),langSelectorId=taId.replace("answer","language"),selector=document.getElementById(langSelectorId),uiWrapperId=taId+"_wrapper";function hasAncestorWithId(element,id){for(;element;){if(element.id===id)return!0;element=element.parentElement}return!1}function setAceLang(){const lang=selector.value,uiWrapper=ta.data("current-ui-wrapper");uiWrapper&&uiWrapper.uiInstance&&"function"==typeof uiWrapper.uiInstance.setLanguage&&uiWrapper.uiInstance.setLanguage(lang)}selector.onchange=setAceLang,document.body.onkeydown=function(event){event.target&&hasAncestorWithId(event.target,uiWrapperId)&&""===selector.value&&NO_LANGUAGE_MESSAGE&&(alert(NO_LANGUAGE_MESSAGE),event.preventDefault())}}(taId)}));const promise=str.get_string("nolanguage","qtype_coderunner");$.when(promise).done((function(message){NO_LANGUAGE_MESSAGE=message}))}}})); /** * This AMD module provides the functionality for the "Reset" * button that is shown just below the student answer field if the question is * defined to have preloaded text. * If clicked, the button reloads the student answer field with the original * preloaded text (after a Confirm dialogue, of course). * * @module qtype_coderunner/resetbutton * @copyright Richard Lobb, 2016, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/resetbutton",["jquery"],(function($){return{initResetButton:function(buttonId,answerId,confirmText){var uiWrapper,resetButton=$('[id="'+buttonId+'"]'),studentAnswer=$('[id="'+answerId+'"]');resetButton.on("click",(function(){if(window.behattesting||window.confirm(confirmText)){var reloadText=resetButton.attr("data-reload-text");(uiWrapper=studentAnswer.data("current-ui-wrapper"))&&uiWrapper.uiInstance?(uiWrapper.stop(),studentAnswer.val(reloadText),uiWrapper.restart()):studentAnswer.val(reloadText)}}))}}})); /** * JavaScript to interface to the Graph editor, which is used both in * the author editing page and by the student question submission page. * * @module qtype_coderunner/ui_graph * @copyright Richard Lobb, 2015, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_graph",["jquery","qtype_coderunner/graphutil","qtype_coderunner/graphelements"],(function($,util,elements){function GraphCanvas(parent,canvasId,w,h){this.HANDLE_SIZE=10,this.parent=parent,this.canvas=$(document.createElement("canvas")),this.canvas.attr({id:canvasId,class:"coderunner_graphcanvas",tabindex:1}),this.canvas.css({"background-color":"white"}),this.canvas.on("mousedown",(function(e){return parent.mousedown(e)})),this.canvas.on("mouseup",(function(e){return parent.mouseup(e)})),this.canvas.on("dblclick",(function(e){return parent.dblclick(e)})),this.canvas.on("keydown",(function(e){return parent.keydown(e)})),this.canvas.on("mousemove",(function(e){return parent.mousemove(e)})),this.canvas.on("keypress",(function(e){return parent.keypress(e)})),this.resize=function(w,h){this.canvas.attr("width",w),this.canvas.attr("height",h)},this.resize(w,h)}function Graph(textareaId,width,height,uiParams){var save_this=this;this.SNAP_TO_PADDING=6,this.DUPLICATE_LINK_OFFSET=16,this.HIT_TARGET_PADDING=6,this.DEFAULT_NODE_RADIUS=26,this.DEFAULT_FONT_SIZE=20,this.DEFAULT_TEXT_OFFSET=5,this.DEFAULT_LINK_LABEL_REL_DIST=.5,this.MAX_VERSIONS=30,this.canvasId="graphcanvas_"+textareaId,this.textArea=$(document.getElementById(textareaId)),this.helpText="",this.readOnly=this.textArea.prop("readonly"),this.uiParams=uiParams,this.graphCanvas=new GraphCanvas(this,this.canvasId,width,height),this.caretVisible=!0,this.caretTimer=0,this.originalClick=null,this.nodes=[],this.links=[],this.selectedObject=null,this.currentLink=null,this.movingObject=!1,this.fail=!1,this.failString=null,this.versions=[],this.versionIndex=-1,this.helpBox=new elements.HelpBox(this,0,0),this.clearButton=new elements.Button(this,60,0,"Clear"),this.clearButton.onClick=function(){confirm("Are you sure you want to clear the diagram?")&&this.parent.clear()},this.buttons=[this.helpBox,this.clearButton],"locknodes"in uiParams&&(uiParams.locknodepositions=uiParams.locknodes),"lockedges"in uiParams&&(uiParams.lockedgepositions=uiParams.lockedges),"helpmenutext"in uiParams?this.helpText=uiParams.helpmenutext:require(["core/str"],(function(str){var helpPresent=str.get_string("graphhelp","qtype_coderunner");$.when(helpPresent).done((function(graphhelp){save_this.helpText=graphhelp}))})),this.reload(),this.fail||this.draw()}return Graph.prototype.failed=function(){return this.fail},Graph.prototype.failMessage=function(){return this.failString},Graph.prototype.getElement=function(){return this.getCanvas()},Graph.prototype.hasFocus=function(){return document.activeElement==this.getCanvas()},Graph.prototype.getCanvas=function(){return this.graphCanvas.canvas[0]},Graph.prototype.nodeRadius=function(){return this.uiParams.noderadius?this.uiParams.noderadius:this.DEFAULT_NODE_RADIUS},Graph.prototype.fontSize=function(){return this.uiParams.fontsize?this.uiParams.fontsize:this.DEFAULT_FONT_SIZE},Graph.prototype.isFsm=function(){return void 0===this.uiParams.isfsm||this.uiParams.isfsm},Graph.prototype.textOffset=function(){return this.uiParams.textoffset?this.uiParams.textoffset:this.DEFAULT_TEXT_OFFSET},Graph.prototype.arrowIfReqd=function(c,x,y,angle){(void 0===this.uiParams.isdirected||this.uiParams.isdirected)&&util.drawArrow(c,x,y,angle)},Graph.prototype.sync=function(){},Graph.prototype.syncIntervalSecs=function(){return 0},Graph.prototype.keypress=function(e){var key=util.crossBrowserKey(e);if(!this.readOnly)return key>=32&&key<=126&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&37!==key&&39!==key&&null!==this.selectedObject&&this.canEditText()?(this.selectedObject.justMoved&&this.saveVersion(),this.selectedObject.justMoved=!1,this.selectedObject.textBox.insertChar(String.fromCharCode(key)),this.resetCaret(),this.draw(),!1):8!==key&&32!==key&&9!==key&&void 0},Graph.prototype.mousedown=function(e){var mouse=util.crossBrowserRelativeMousePos(e);if(!this.readOnly){if(this.selectedObject=this.selectObject(mouse.x,mouse.y),this.movingObject=!1,this.movingGraph=!1,this.movingText=!1,this.originalClick=mouse,this.saveVersion(),this.selectedObject!==this.helpBox&&(this.helpBox.helpOpen=!1),null!==this.selectedObject){if(this.selectedObject instanceof elements.Button)this.selectedObject.onClick();else if(e.shiftKey&&this.selectedObject instanceof elements.Node)this.uiParams.lockedgeset||(this.currentLink=new elements.SelfLink(this,this.selectedObject,mouse));else if(e.altKey&&this.selectedObject instanceof elements.Node){if(!this.uiParams.locknodepositions){this.movingGraph=!0,this.movingNodes=this.selectedObject.traverseGraph(this.links,[]);for(var i=0;i<this.movingNodes.length;i++)this.movingNodes[i].setMouseStart(mouse.x,mouse.y)}}else this.selectedObject instanceof elements.TextBox?this.uiParams.lockedgelabels||(this.movingText=!0,this.selectedObject.setMouseStart(mouse.x,mouse.y),this.selectedObject=this.selectedObject.parent):this.uiParams.locknodepositions&&this.selectedObject instanceof elements.Node||this.uiParams.lockedgepositions&&this.selectedObject instanceof elements.Link||(this.movingObject=!0,this.selectedObject.setMouseStart&&this.selectedObject.setMouseStart(mouse.x,mouse.y));this.selectedObject.justMoved=!0,this.resetCaret()}else e.shiftKey&&this.isFsm()&&(this.currentLink=new elements.TemporaryLink(this,mouse,mouse));return this.draw(),!this.hasFocus()&&(this.resetCaret(),!0)}},Graph.prototype.canEditText=function(){var isNode=this.selectedObject instanceof elements.Node,isLink=this.selectedObject instanceof elements.Link||this.selectedObject instanceof elements.SelfLink;return"textBox"in this.selectedObject&&(isNode&&!this.uiParams.locknodelabels||isLink&&!this.uiParams.lockedgelabels)},Graph.prototype.keydown=function(e){var i,key=util.crossBrowserKey(e),nodeDeleted=!1;if(!this.readOnly){if(8===key)return null!==this.selectedObject&&this.canEditText()&&(this.selectedObject.textBox.deleteChar(),this.resetCaret(),this.draw()),!1;if(46===key&&null!==this.selectedObject){for(this.saveVersion(),i=0;i<this.nodes.length;i++)this.nodes[i]!==this.selectedObject||this.uiParams.locknodeset||(this.nodes.splice(i--,1),nodeDeleted=!0);for(i=0;i<this.links.length;i++)(this.links[i]===this.selectedObject&&!this.uiParams.lockedgeset||nodeDeleted&&(this.links[i].node===this.selectedObject||this.links[i].nodeA===this.selectedObject||this.links[i].nodeB===this.selectedObject))&&this.links.splice(i--,1);this.selectedObject=null,this.draw()}else 13===key?null!==this.selectedObject&&(this.selectedObject=null,this.draw()):37===key?null!==this.selectedObject&&this.canEditText()&&(this.selectedObject.textBox.caretLeft(),this.resetCaret(),this.draw()):39===key?null!==this.selectedObject&&this.canEditText()&&(this.selectedObject.textBox.caretRight(),this.resetCaret(),this.draw()):90==e.keyCode&&e.ctrlKey&&e.shiftKey||89==e.keyCode&&e.ctrlKey?this.redo():90==e.keyCode&&e.ctrlKey&&this.undo()}},Graph.prototype.dblclick=function(e){var mouse=util.crossBrowserRelativeMousePos(e);this.readOnly||this.uiParams.locknodeset||(this.selectedObject=this.selectObject(mouse.x,mouse.y),this.saveVersion(),null===this.selectedObject?(this.selectedObject=new elements.Node(this,mouse.x,mouse.y),this.nodes.push(this.selectedObject),this.selectedObject.justMoved=!0,this.resetCaret(),this.draw()):this.selectedObject instanceof elements.Node&&this.isFsm()&&(this.selectedObject.isAcceptState=!this.selectedObject.isAcceptState,this.draw()))},Graph.prototype.resize=function(w,h){this.graphCanvas.resize(w,h),this.draw()},Graph.prototype.mousemove=function(e){var closestPoint,mouse=util.crossBrowserRelativeMousePos(e);if(!this.readOnly){for(i=0;i<this.buttons.length;i++)this.buttons[i].containsPoint(mouse.x,mouse.y)?this.buttons[i].highLighted=!0:this.buttons[i].highLighted=!1,this.draw();if(null!==this.currentLink){var targetNode=this.selectObject(mouse.x,mouse.y);targetNode instanceof elements.Node||(targetNode=null),null===this.selectedObject?this.currentLink=null!==targetNode?new elements.StartLink(this,targetNode,this.originalClick):new elements.TemporaryLink(this,this.originalClick,mouse):targetNode===this.selectedObject?this.currentLink=new elements.SelfLink(this,this.selectedObject,mouse):null!==targetNode?this.currentLink=new elements.Link(this,this.selectedObject,targetNode):(closestPoint=this.selectedObject.closestPointOnCircle(mouse.x,mouse.y),this.currentLink=new elements.TemporaryLink(this,closestPoint,mouse)),this.draw()}if(this.movingGraph){for(var nodes=this.movingNodes,i=0;i<nodes.length;i++)nodes[i].trackMouse(mouse.x,mouse.y),this.snapNode(nodes[i]);this.draw()}else this.movingText?(this.selectedObject.textBox.setAnchorPoint(mouse.x,mouse.y),this.draw()):this.movingObject&&(this.selectedObject.setAnchorPoint(mouse.x,mouse.y),this.selectedObject instanceof elements.Node&&this.snapNode(this.selectedObject),this.draw())}},Graph.prototype.mouseup=function(){this.readOnly||(this.movingObject=!1,this.movingGraph=!1,this.movingText=!1,null!==this.currentLink&&(this.currentLink instanceof elements.TemporaryLink||(this.selectedObject=this.currentLink,this.addLink(this.currentLink),this.resetCaret()),this.currentLink=null,this.draw()))},Graph.prototype.selectObject=function(x,y){for(i=0;i<this.buttons.length;i++)if(this.buttons[i].containsPoint(x,y))return this.buttons[i];var i;for(i=0;i<this.nodes.length;i++)if(this.nodes[i].containsPoint(x,y))return this.nodes[i];for(i=0;i<this.links.length;i++){if(this.links[i].containsPoint(x,y))return this.links[i];if("textBox"in this.links[i]&&this.links[i].textBox.containsPoint(x,y))return this.links[i].textBox}return null},Graph.prototype.snapNode=function(node){for(var i=0;i<this.nodes.length;i++)this.nodes[i]!==node&&(Math.abs(node.x-this.nodes[i].x)<this.SNAP_TO_PADDING&&(node.x=this.nodes[i].x),Math.abs(node.y-this.nodes[i].y)<this.SNAP_TO_PADDING&&(node.y=this.nodes[i].y))},Graph.prototype.addLink=function(newLink){for(var maxPerpRHS=null,i=0;i<this.links.length;i++){var link=this.links[i];link.nodeA===newLink.nodeA&&link.nodeB===newLink.nodeB&&(null===maxPerpRHS||link.perpendicularPart>maxPerpRHS)&&(maxPerpRHS=link.perpendicularPart),link.nodeA===newLink.nodeB&&link.nodeB===newLink.nodeA&&(null===maxPerpRHS||-link.perpendicularPart>maxPerpRHS)&&(maxPerpRHS=-link.perpendicularPart)}null!==maxPerpRHS&&(newLink.perpendicularPart=maxPerpRHS+this.DUPLICATE_LINK_OFFSET),this.links.push(newLink)},Graph.prototype.reload=function(){var content=$(this.textArea).val();if(content)try{var i,backup=JSON.parse(content);for(i=0;i<backup.nodes.length;i++){var backupNode=backup.nodes[i],backupNodeLayout=backup.nodeGeometry[i],node=new elements.Node(this,backupNodeLayout[0],backupNodeLayout[1]);node.isAcceptState=backupNode[1],node.textBox=new elements.TextBox(backupNode[0].toString(),node),this.nodes.push(node)}for(i=0;i<backup.edges.length;i++){var backupLink=backup.edges[i],backupLinkLayout=backup.edgeGeometry[i],link=null;backupLink[0]===backupLink[1]?((link=new elements.SelfLink(this,this.nodes[backupLink[0]])).anchorAngle=backupLinkLayout.anchorAngle,link.textBox=new elements.TextBox(backupLink[2].toString(),link),backupLink.length>3&&link.textBox.setAnchorPoint(backupLink[3].x,backupLink[3].y)):-1===backupLink[0]?((link=new elements.StartLink(this,this.nodes[backupLink[1]])).deltaX=backupLinkLayout.deltaX,link.deltaY=backupLinkLayout.deltaY):((link=new elements.Link(this,this.nodes[backupLink[0]],this.nodes[backupLink[1]])).parallelPart=backupLinkLayout.parallelPart,link.perpendicularPart=backupLinkLayout.perpendicularPart,link.lineAngleAdjust=backupLinkLayout.lineAngleAdjust,link.textBox=new elements.TextBox(backupLink[2].toString(),link),backupLink.length>3&&link.textBox.setAnchorPoint(backupLink[3].x,backupLink[3].y)),null!==link&&this.links.push(link)}}catch(e){this.fail=!0,this.failString="graph_ui_invalidserialisation"}},Graph.prototype.save=function(){var i,backup={edgeGeometry:[],nodeGeometry:[],nodes:[],edges:[]};if(JSON&&(""!==this.textArea.val().trim()||0!==this.nodes.length)){for(i=0;i<this.nodes.length;i++){var node=this.nodes[i],nodeData=[node.textBox.text,node.isAcceptState],nodeLayout=[node.x,node.y];backup.nodeGeometry.push(nodeLayout),backup.nodes.push(nodeData)}for(i=0;i<this.links.length;i++){var link=this.links[i],linkData=null,linkLayout=null;link instanceof elements.SelfLink?(linkLayout={anchorAngle:link.anchorAngle},linkData=[this.nodes.indexOf(link.node),this.nodes.indexOf(link.node),link.textBox.text],link.textBox.dragged&&linkData.push(link.textBox.position)):link instanceof elements.StartLink?(linkLayout={deltaX:link.deltaX,deltaY:link.deltaY},linkData=[-1,this.nodes.indexOf(link.node),""]):link instanceof elements.Link&&(linkLayout={lineAngleAdjust:link.lineAngleAdjust,parallelPart:link.parallelPart,perpendicularPart:link.perpendicularPart},linkData=[this.nodes.indexOf(link.nodeA),this.nodes.indexOf(link.nodeB),link.textBox.text],link.textBox.dragged&&linkData.push(link.textBox.position)),null!==linkData&&null!==linkLayout&&(backup.edges.push(linkData),backup.edgeGeometry.push(linkLayout))}this.textArea.val(JSON.stringify(backup))}},Graph.prototype.saveVersion=function(){var curState=this.textArea.val();if(0==this.versions.length||0!=curState.localeCompare(this.versions[this.versionIndex])){for(this.versionIndex++;this.versionIndex<this.versions.length;)this.versions.pop();this.versions.push(curState),this.versions.length>this.MAX_VERSIONS&&(this.versions.shift(),this.versionIndex--)}},Graph.prototype.undo=function(){this.saveVersion(),this.versionIndex>0&&(this.versionIndex--,this.textArea.val(this.versions[this.versionIndex]),this.nodes=[],this.links=[],this.reload(),this.draw())},Graph.prototype.redo=function(){this.versionIndex<this.versions.length-1&&(this.versionIndex++,this.textArea.val(this.versions[this.versionIndex]),this.nodes=[],this.links=[],this.reload(),this.draw())},Graph.prototype.clear=function(){this.saveVersion(),this.nodes=[],this.links=[],this.save(),this.draw()},Graph.prototype.destroy=function(){clearInterval(this.caretTimer),this.graphCanvas.canvas.off(),this.graphCanvas.canvas.remove()},Graph.prototype.resetCaret=function(){var t=this;clearInterval(this.caretTimer),this.caretTimer=setInterval((function(){t.caretVisible=!t.caretVisible,t.draw()}),500),this.caretVisible=!0},Graph.prototype.draw=function(){var i,c=this.getCanvas().getContext("2d");for(c.clearRect(0,0,this.getCanvas().width,this.getCanvas().height),c.save(),c.translate(.5,.5),i=0;i<this.buttons.length;i++)this.buttons[i].draw(c);if(!this.helpBox.helpOpen){for(i=0;i<this.nodes.length;i++)c.lineWidth=1,c.fillStyle=c.strokeStyle=this.nodes[i]===this.selectedObject?"blue":"black",this.nodes[i].draw(c);for(i=0;i<this.links.length;i++)c.lineWidth=1,c.fillStyle=c.strokeStyle=this.links[i]===this.selectedObject||this.links[i].textBox===this.selectedObject?"blue":"black",this.links[i].draw(c);null!==this.currentLink&&(c.lineWidth=1,c.fillStyle=c.strokeStyle="black",this.currentLink.draw(c))}c.restore(),this.save()},{Constructor:Graph}})); /****************************************************************************** * * A module for use by ui_graph, defining classes Node, Link, SelfLink, * StartLink and TemporaryLink * * @module qtype_coderunner/graphelements * @copyright Richard Lobb, 2015, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/graphelements",["qtype_coderunner/graphutil"],(function(util){function Node(parent,x,y){this.parent=parent,this.x=x,this.y=y,this.mouseOffsetX=0,this.mouseOffsetY=0,this.isAcceptState=!1,this.textBox=new TextBox("",this),this.caretPosition=0}function Link(parent,a,b){this.parent=parent,this.nodeA=a,this.nodeB=b,this.textBox=new TextBox("",this),this.lineAngleAdjust=0,this.caretPosition=0,this.parallelPart=.5,this.perpendicularPart=0}function SelfLink(parent,node,mouse){this.parent=parent,this.node=node,this.anchorAngle=0,this.mouseOffsetAngle=0,this.textBox=new TextBox("",this),mouse&&this.setAnchorPoint(mouse.x,mouse.y)}function StartLink(parent,node,start){this.parent=parent,this.node=node,this.deltaX=0,this.deltaY=0,start&&this.setAnchorPoint(start.x,start.y)}function TemporaryLink(parent,from,to){this.parent=parent,this.from=from,this.to=to}function Button(parent,topX,topY,text){this.BUTTON_WIDTH=60,this.BUTTON_HEIGHT=25,this.TEXT_OFFSET_X=30,this.TEXT_OFFSET_Y=17,this.topX=topX,this.topY=topY,this.parent=parent,this.text=text,this.highLighted=!1}function HelpBox(parent,topX,topY){Button.call(this,parent,topX,topY,"Help"),this.helpOpen=!1,this.LINE_HEIGHT=18,this.HELP_INDENT=5}function TextBox(text,parent){this.text=text,this.parent=parent,this.caretPosition=text.length,this.relDist=.5,this.offset=parent.parent.textOffset(),this.dragged=!1,this.boundingBox={}}return Node.prototype.setMouseStart=function(mouseX,mouseY){this.mouseOffsetX=this.x-mouseX,this.mouseOffsetY=this.y-mouseY},Node.prototype.setAnchorPoint=function(x,y){this.x=x+this.mouseOffsetX,this.y=y+this.mouseOffsetY},Node.prototype.trackMouse=function(mouseX,mouseY){this.x=this.mouseOffsetX+mouseX,this.y=this.mouseOffsetY+mouseY},Node.prototype.draw=function(c){c.beginPath(),c.arc(this.x,this.y,this.parent.nodeRadius(),0,2*Math.PI,!1),c.stroke(),this.textBox.draw(this.x,this.y,null,this),this.isAcceptState&&(c.beginPath(),c.arc(this.x,this.y,this.parent.nodeRadius()-6,0,2*Math.PI,!1),c.stroke())},Node.prototype.closestPointOnCircle=function(x,y){var dx=x-this.x,dy=y-this.y,scale=Math.sqrt(dx*dx+dy*dy);return{x:this.x+dx*this.parent.nodeRadius()/scale,y:this.y+dy*this.parent.nodeRadius()/scale}},Node.prototype.containsPoint=function(x,y){return(x-this.x)*(x-this.x)+(y-this.y)*(y-this.y)<this.parent.nodeRadius()*this.parent.nodeRadius()},Node.prototype.neighbours=function(links){for(var link,neighbours=[],i=0;i<links.length;i++)(link=links[i])instanceof Link&&(link.nodeA!==this||neighbours.includes(link.nodeB)?link.nodeB!==this||neighbours.includes(link.nodeA)||neighbours.push(link.nodeA):neighbours.push(link.nodeB));return neighbours},Node.prototype.traverseGraph=function(links,visited){var neighbours,neighbour;if(!visited.includes(this)){visited.push(this),neighbours=this.neighbours(links);for(var i=0;i<neighbours.length;i++)neighbour=neighbours[i],visited.includes(neighbour)||neighbour.traverseGraph(links,visited)}return visited},Link.prototype.getAnchorPoint=function(){var dx=this.nodeB.x-this.nodeA.x,dy=this.nodeB.y-this.nodeA.y,scale=Math.sqrt(dx*dx+dy*dy);return{x:this.nodeA.x+dx*this.parallelPart-dy*this.perpendicularPart/scale,y:this.nodeA.y+dy*this.parallelPart+dx*this.perpendicularPart/scale}},Link.prototype.setAnchorPoint=function(x,y){var dx=this.nodeB.x-this.nodeA.x,dy=this.nodeB.y-this.nodeA.y,scale=Math.sqrt(dx*dx+dy*dy);this.parallelPart=(dx*(x-this.nodeA.x)+dy*(y-this.nodeA.y))/(scale*scale),this.perpendicularPart=(dx*(y-this.nodeA.y)-dy*(x-this.nodeA.x))/scale,this.parallelPart>0&&this.parallelPart<1&&Math.abs(this.perpendicularPart)<this.parent.SNAP_TO_PADDING&&(this.lineAngleAdjust=(this.perpendicularPart<0)*Math.PI,this.perpendicularPart=0)},Link.prototype.getEndPointsAndCircle=function(){if(0===this.perpendicularPart){var midX=(this.nodeA.x+this.nodeB.x)/2,midY=(this.nodeA.y+this.nodeB.y)/2,start=this.nodeA.closestPointOnCircle(midX,midY),end=this.nodeB.closestPointOnCircle(midX,midY);return{hasCircle:!1,startX:start.x,startY:start.y,endX:end.x,endY:end.y}}var anchor=this.getAnchorPoint(),circle=util.circleFromThreePoints(this.nodeA.x,this.nodeA.y,this.nodeB.x,this.nodeB.y,anchor.x,anchor.y),isReversed=this.perpendicularPart>0,reverseScale=isReversed?1:-1,rRatio=reverseScale*this.parent.nodeRadius()/circle.radius,startAngle=Math.atan2(this.nodeA.y-circle.y,this.nodeA.x-circle.x)-rRatio,endAngle=Math.atan2(this.nodeB.y-circle.y,this.nodeB.x-circle.x)+rRatio;return{hasCircle:!0,startX:circle.x+circle.radius*Math.cos(startAngle),startY:circle.y+circle.radius*Math.sin(startAngle),endX:circle.x+circle.radius*Math.cos(endAngle),endY:circle.y+circle.radius*Math.sin(endAngle),startAngle:startAngle,endAngle:endAngle,circleX:circle.x,circleY:circle.y,circleRadius:circle.radius,reverseScale:reverseScale,isReversed:isReversed}},Link.prototype.draw=function(c){var textX,textY,textAngle,relDist,linkInfo=this.getEndPointsAndCircle();if(c.beginPath(),linkInfo.hasCircle?c.arc(linkInfo.circleX,linkInfo.circleY,linkInfo.circleRadius,linkInfo.startAngle,linkInfo.endAngle,linkInfo.isReversed):(c.moveTo(linkInfo.startX,linkInfo.startY),c.lineTo(linkInfo.endX,linkInfo.endY)),c.stroke(),linkInfo.hasCircle?this.parent.arrowIfReqd(c,linkInfo.endX,linkInfo.endY,linkInfo.endAngle-linkInfo.reverseScale*(Math.PI/2)):this.parent.arrowIfReqd(c,linkInfo.endX,linkInfo.endY,Math.atan2(linkInfo.endY-linkInfo.startY,linkInfo.endX-linkInfo.startX)),relDist=this.textBox.relDist,linkInfo.hasCircle){var startAngle=linkInfo.startAngle,endAngle=linkInfo.endAngle;endAngle<startAngle&&(endAngle+=2*Math.PI),textAngle=(1-relDist)*startAngle+relDist*endAngle,linkInfo.isReversed&&(textAngle+=(1-relDist)*(2*Math.PI)),textX=linkInfo.circleX+linkInfo.circleRadius*Math.cos(textAngle),textY=linkInfo.circleY+linkInfo.circleRadius*Math.sin(textAngle),this.textBox.draw(textX,textY,textAngle,this)}else textX=(1-relDist)*linkInfo.startX+relDist*linkInfo.endX,textY=(1-relDist)*linkInfo.startY+relDist*linkInfo.endY,textAngle=Math.atan2(linkInfo.endX-linkInfo.startX,linkInfo.startY-linkInfo.endY),this.textBox.draw(textX,textY,textAngle+this.lineAngleAdjust,this)},Link.prototype.containsPoint=function(x,y){var dx,dy,distance,linkInfo=this.getEndPointsAndCircle();if(!linkInfo.hasCircle){dx=linkInfo.endX-linkInfo.startX,dy=linkInfo.endY-linkInfo.startY;var length=Math.sqrt(dx*dx+dy*dy),percent=(dx*(x-linkInfo.startX)+dy*(y-linkInfo.startY))/(length*length);return distance=(dx*(y-linkInfo.startY)-dy*(x-linkInfo.startX))/length,percent>0&&percent<1&&Math.abs(distance)<this.parent.HIT_TARGET_PADDING}if(dx=x-linkInfo.circleX,dy=y-linkInfo.circleY,distance=Math.sqrt(dx*dx+dy*dy)-linkInfo.circleRadius,Math.abs(distance)<this.parent.HIT_TARGET_PADDING){var angle=Math.atan2(dy,dx),startAngle=linkInfo.startAngle,endAngle=linkInfo.endAngle;if(linkInfo.isReversed){var temp=startAngle;startAngle=endAngle,endAngle=temp}return endAngle<startAngle&&(endAngle+=2*Math.PI),angle<startAngle?angle+=2*Math.PI:angle>endAngle&&(angle-=2*Math.PI),angle>startAngle&&angle<endAngle}return!1},SelfLink.prototype.setMouseStart=function(x,y){this.mouseStartX=x,this.mouseStartY=y},SelfLink.prototype.setAnchorPoint=function(x,y){this.anchorAngle=Math.atan2(y-this.node.y,x-this.node.x)+this.mouseOffsetAngle;var snap=Math.round(this.anchorAngle/(Math.PI/2))*(Math.PI/2);Math.abs(this.anchorAngle-snap)<.1&&(this.anchorAngle=snap),this.anchorAngle<-Math.PI&&(this.anchorAngle+=2*Math.PI),this.anchorAngle>Math.PI&&(this.anchorAngle-=2*Math.PI)},SelfLink.prototype.getEndPointsAndCircle=function(){var circleX=this.node.x+1.5*this.parent.nodeRadius()*Math.cos(this.anchorAngle),circleY=this.node.y+1.5*this.parent.nodeRadius()*Math.sin(this.anchorAngle),circleRadius=.75*this.parent.nodeRadius(),startAngle=this.anchorAngle-.8*Math.PI,endAngle=this.anchorAngle+.8*Math.PI;return{hasCircle:!0,startX:circleX+circleRadius*Math.cos(startAngle),startY:circleY+circleRadius*Math.sin(startAngle),endX:circleX+circleRadius*Math.cos(endAngle),endY:circleY+circleRadius*Math.sin(endAngle),startAngle:startAngle,endAngle:endAngle,circleX:circleX,circleY:circleY,circleRadius:circleRadius}},SelfLink.prototype.draw=function(c){var linkInfo=this.getEndPointsAndCircle();c.beginPath(),c.arc(linkInfo.circleX,linkInfo.circleY,linkInfo.circleRadius,linkInfo.startAngle,linkInfo.endAngle,!1),c.stroke();var relDist=this.textBox.relDist,textAngle=linkInfo.startAngle*(1-relDist)+linkInfo.endAngle*relDist,textX=linkInfo.circleX+linkInfo.circleRadius*Math.cos(textAngle),textY=linkInfo.circleY+linkInfo.circleRadius*Math.sin(textAngle);this.textBox.draw(textX,textY,textAngle,this),this.parent.arrowIfReqd(c,linkInfo.endX,linkInfo.endY,linkInfo.endAngle+.4*Math.PI)},SelfLink.prototype.containsPoint=function(x,y){var linkInfo=this.getEndPointsAndCircle(),dx=x-linkInfo.circleX,dy=y-linkInfo.circleY,distance=Math.sqrt(dx*dx+dy*dy)-linkInfo.circleRadius;return Math.abs(distance)<this.parent.HIT_TARGET_PADDING},StartLink.prototype.setAnchorPoint=function(x,y){this.deltaX=x-this.node.x,this.deltaY=y-this.node.y,Math.abs(this.deltaX)<this.parent.SNAP_TO_PADDING&&(this.deltaX=0),Math.abs(this.deltaY)<this.parent.SNAP_TO_PADDING&&(this.deltaY=0)},StartLink.prototype.getEndPoints=function(){var startX=this.node.x+this.deltaX,startY=this.node.y+this.deltaY,end=this.node.closestPointOnCircle(startX,startY);return{startX:startX,startY:startY,endX:end.x,endY:end.y}},StartLink.prototype.draw=function(c){var endPoints=this.getEndPoints();c.beginPath(),c.moveTo(endPoints.startX,endPoints.startY),c.lineTo(endPoints.endX,endPoints.endY),c.stroke(),this.parent.arrowIfReqd(c,endPoints.endX,endPoints.endY,Math.atan2(-this.deltaY,-this.deltaX))},StartLink.prototype.containsPoint=function(x,y){var endPoints=this.getEndPoints(),dx=endPoints.endX-endPoints.startX,dy=endPoints.endY-endPoints.startY,length=Math.sqrt(dx*dx+dy*dy),percent=(dx*(x-endPoints.startX)+dy*(y-endPoints.startY))/(length*length),distance=(dx*(y-endPoints.startY)-dy*(x-endPoints.startX))/length;return percent>0&&percent<1&&Math.abs(distance)<this.parent.HIT_TARGET_PADDING},TemporaryLink.prototype.draw=function(c){c.beginPath(),c.moveTo(this.to.x,this.to.y),c.lineTo(this.from.x,this.from.y),c.stroke(),this.parent.arrowIfReqd(c,this.to.x,this.to.y,Math.atan2(this.to.y-this.from.y,this.to.x-this.from.x))},Button.prototype.containsPoint=function(x,y){return util.isInside({x:x,y:y},{x:this.topX,y:this.topY,width:this.BUTTON_WIDTH,height:this.BUTTON_HEIGHT})},Button.prototype.draw=function(c){this.highLighted?c.fillStyle="#FFFFFF":c.fillStyle="#F0F0F0",c.fillRect(this.topX,this.topY,this.BUTTON_WIDTH,this.BUTTON_HEIGHT),c.lineWidth=.5,c.strokeStyle="#000000",c.strokeRect(this.topX,this.topY,this.BUTTON_WIDTH,this.BUTTON_HEIGHT),c.font="12pt Arial",c.fillStyle="#000000",c.textAlign="center",c.fillText(this.text,this.topX+this.TEXT_OFFSET_X,this.topY+this.TEXT_OFFSET_Y),c.textAlign="left"},Button.prototype.onClick=function(){},HelpBox.prototype=new Button,HelpBox.prototype.draw=function(c){var lines,i,y,helpText;if(Button.prototype.draw.call(this,c),this.helpOpen)for(helpText=this.parent.helpText,c.font="12pt Arial",lines=helpText.split("\n"),y=this.topY+this.BUTTON_HEIGHT,i=0;i<lines.length;i+=1)y+=this.LINE_HEIGHT,c.fillText(lines[i],this.topX+this.HELP_INDENT,y)},HelpBox.prototype.onClick=function(){this.helpOpen=!this.helpOpen,this.parent.draw()},TextBox.prototype.insertChar=function(char){this.text=this.text.slice(0,this.caretPosition)+char+this.text.slice(this.caretPosition),this.caretRight()},TextBox.prototype.deleteChar=function(){this.caretPosition>0&&(this.text=this.text.slice(0,this.caretPosition-1)+this.text.slice(this.caretPosition),this.caretLeft())},TextBox.prototype.caretLeft=function(){this.caretPosition>0&&this.caretPosition--},TextBox.prototype.caretRight=function(){this.caretPosition<this.text.length&&this.caretPosition++},TextBox.prototype.containsPoint=function(x,y){var point={x:x,y:y};return util.isInside(point,this.boundingBox)},TextBox.prototype.setMouseStart=function(x,y){this.mouseOffsetX=this.position.x-x,this.mouseOffsetY=this.position.y-y},TextBox.prototype.setAnchorPoint=function(x,y){x+=this.mouseOffsetX||0,y+=this.mouseOffsetY||0;var relDist,offset,linkInfo=this.parent.getEndPointsAndCircle();if(linkInfo.hasCircle){var textAngle=Math.atan2(y-linkInfo.circleY,x-linkInfo.circleX);textAngle<linkInfo.startAngle&&(textAngle+=2*Math.PI),linkInfo.endAngle<linkInfo.startAngle&&(linkInfo.endAngle+=2*Math.PI),relDist=linkInfo.isReversed?(textAngle-linkInfo.startAngle-2*Math.PI)/(linkInfo.endAngle-linkInfo.startAngle-2*Math.PI):(textAngle-linkInfo.startAngle)/(linkInfo.endAngle-linkInfo.startAngle),offset=util.vectorMagnitude({x:x-linkInfo.circleX,y:y-linkInfo.circleY})-linkInfo.circleRadius}else{var textVector={x:x-linkInfo.startX,y:y-linkInfo.startY},linkVector={x:linkInfo.endX-linkInfo.startX,y:linkInfo.endY-linkInfo.startY},projection=util.scalarProjection(textVector,linkVector);relDist=projection/util.vectorMagnitude(linkVector),offset=Math.sqrt(Math.pow(util.vectorMagnitude(textVector),2)-Math.pow(projection,2));var ccw=util.isCCW(textVector,linkVector),reversed=0!=this.parent.lineAngleAdjust;(!ccw&&reversed||ccw&&!reversed)&&(offset*=-1)}relDist>0&&relDist<1&&(this.relDist=relDist,this.offset=Math.round(offset),this.dragged=!0)},TextBox.prototype.draw=function(x,y,angleOrNull,parentObject){var graph=parentObject.parent,c=graph.getCanvas().getContext("2d");c.font=graph.fontSize()+"px Arial";var beforeCaretText=util.convertLatexShortcuts(this.text.slice(0,this.caretPosition)),afterCaretText=util.convertLatexShortcuts(this.text.slice(this.caretPosition)),width=c.measureText(beforeCaretText+afterCaretText).width,dy=Math.round(graph.fontSize()/2);if(null!==angleOrNull){var cos=Math.cos(angleOrNull),sin=Math.sin(angleOrNull);if(x+=this.offset*cos,y+=this.offset*sin,!this.dragged){var cornerPointX=width/2*(cos>0?1:-1),cornerPointY=dy/2*(sin>0?1:-1),slide=sin*Math.pow(Math.abs(sin),40)*cornerPointX-cos*Math.pow(Math.abs(cos),10)*cornerPointY;x+=cornerPointX-sin*slide,y+=cornerPointY+cos*slide}this.position={x:Math.round(x),y:Math.round(y)}}if(x-=width/2,x=Math.round(x),y=Math.round(y),"advancedFillText"in c)c.advancedFillText(this.text,this.text,x+width/2,y,angleOrNull);else{var prevStyle=c.fillStyle;c.fillStyle="rgba(255, 255, 255, 0.7)",c.fillRect(x,y-dy,width,2*dy),c.fillStyle=prevStyle,dy=Math.round(graph.fontSize()/3),c.fillText(beforeCaretText,x,y+dy);var caretX=x+c.measureText(beforeCaretText).width;c.fillText(afterCaretText,caretX,y+dy),dy=Math.round(graph.fontSize()/2),parentObject==graph.selectedObject&&graph.caretVisible&&graph.hasFocus()&&document.hasFocus()&&(c.beginPath(),c.moveTo(caretX,y-dy),c.lineTo(caretX,y+dy),c.stroke())}this.boundingBox={x:x,y:y-dy,height:2*dy,width:width}},{Node:Node,Link:Link,SelfLink:SelfLink,TemporaryLink:TemporaryLink,StartLink:StartLink,Button:Button,HelpBox:HelpBox,TextBox:TextBox}})); /** * Implementation of the table_ui user interface plugin. For overall details * of the UI plugin architecture, see userinterfacewrapper.js. * * This plugin replaces the usual textarea answer element with a div * containing an HTML table. The number of columns, and * the initial number of rows are specified by required UI parameters * num_columns and num_rows respectively. * Optional additional UI parameters are: * 1. column_headers: a list of strings that can be used to provide a * fixed header row at the top. * 2. row_labels: a list of strings that can be used to provide a * fixed row label column at the left. * 3. dynamic_rows, which, if true, allows the user to add rows. * 4. locked_cells: a list of [row, column] pairs, being the coordinates * of table cells that cannot be changed by the user. row and column numbers * are zero origin and do not include the header row or the row labels. * 5. width_percents: a list of the percentages of the width occupied * by each column. This list must include a value for the row labels, if present. * * Individual cells are textareas except when the number of rows per cell is set to * 1, in which case input elements are used instead. * * The serialisation of the table, which is what is essentially copied back * into the original answer box textarea for submissions as the answer, is a JSON array. Each * element in the array is itself an array containing the values of one row * of the table. Empty cells are empty strings. The table header row and row * label columns are not provided in the serialisation. * * To preload the table with data, simply set the answer_preload of the question * to a json array of row values (each itself an array). If the number of rows * in the preload exceeds the number set by num_rows, extra rows are * added. If the number is less than num_rows, or if there is no * answer preload, undefined rows are simply left blank. * * As a special case of the serialisation, if all cells in the serialisation * are empty strings, the serialisation is itself the empty string. * * @module qtype_coderunner/ui_table * @copyright Richard Lobb, 2018, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_table",["jquery"],(function($){function TableUi(textareaId,width,height,uiParams){if(this.textArea=$(document.getElementById(textareaId)),this.readOnly=this.textArea.prop("readonly"),this.tableDiv=null,this.uiParams=uiParams,!uiParams.num_columns||!uiParams.num_rows)return this.fail=!0,void(this.failString="table_ui_missingparams");this.fail=!1,this.lockedCells=uiParams.locked_cells||[],this.hasHeader=!!(uiParams.column_headers&&uiParams.column_headers.length>0),this.hasRowLabels=!!(uiParams.row_labels&&uiParams.row_labels.length>0),this.numDataColumns=uiParams.num_columns,this.rowsPerCell=uiParams.lines_per_cell||2,this.totNumColumns=this.numDataColumns+(this.hasRowLabels?1:0),this.columnWidths=this.computeColumnWidths(),this.reload()}return TableUi.prototype.computeColumnWidths=function(){var defaultWidth=Math.trunc(100/this.totNumColumns),columnWidths=[];if(this.uiParams.column_width_percents&&this.uiParams.column_width_percents.length>0)return this.uiParams.column_width_percents;if(Array.prototype.fill)return new Array(this.totNumColumns).fill(defaultWidth);for(var i=0;i<this.totNumColumns;i++)columnWidths.push(defaultWidth);return columnWidths},TableUi.prototype.isLockedCell=function(row,col){for(var i=0;i<this.lockedCells.length;i++)if(this.lockedCells[i][0]==row&&this.lockedCells[i][1]==col)return!0;return!1},TableUi.prototype.getElement=function(){return this.tableDiv},TableUi.prototype.failed=function(){return this.fail},TableUi.prototype.failMessage=function(){return this.failString},TableUi.prototype.sync=function(){var serialisation=[],empty=!0;$(this.tableDiv).find("table tbody tr").each((function(){var rowValues=[];$(this).find(".table_ui_cell").each((function(){var cellVal=$(this).val();rowValues.push(cellVal),cellVal&&(empty=!1)})),serialisation.push(rowValues)})),empty?this.textArea.val(""):this.textArea.val(JSON.stringify(serialisation))},TableUi.prototype.tableRow=function(iRow,preload){const cellStyle="width:100%;padding:0;font-family:monospace;";let width,disabled,value,html="<tr>",widthIndex=0;this.hasRowLabels&&(width=this.columnWidths[0],widthIndex=1,html+="<th style='padding-top:8px;text-align:center;width:"+width+"%' scope='row'>",iRow<this.uiParams.row_labels.length&&(html+=this.uiParams.row_labels[iRow]),html+="</th>");for(let iCol=0;iCol<this.numDataColumns;iCol++)width=this.columnWidths[widthIndex++],disabled=this.isLockedCell(iRow,iCol)?" disabled;":"",value=iRow<preload.length?preload[iRow][iCol]:"",iRow<preload.length&&(value=preload[iRow][iCol]),html+="<td style='padding:2px;margin:0,width:"+width+"'%>",1==this.rowsPerCell?html+='<input type="text" class="table_ui_cell" style="'.concat(cellStyle,'" value="').concat(value,'"').concat(disabled,">"):(html+='<textarea class="table_ui_cell" rows="'.concat(this.rowsPerCell,'"'),html+=' style="'.concat(cellStyle,'resize:vertical;"').concat(disabled,">").concat(value,"</textarea>")),html+="</td>";return html+="</tr>",html},TableUi.prototype.tableHeadSection=function(){let html="<thead>\n",colIndex=0;if(this.hasHeader){html+="<tr>",this.hasRowLabels&&(html+="<th style='width:"+this.columnWidths[0]+"%'></th>",colIndex+=1);for(let iCol=0;iCol<this.numDataColumns;iCol++)html+="<th style='width:"+this.columnWidths[colIndex]+"%'>",iCol<this.uiParams.column_headers.length&&(html+=this.uiParams.column_headers[iCol]),colIndex++,html+="</th>";html+="</tr>\n"}return html+="</thead>\n",html},TableUi.prototype.reload=function(){var preloadJson=$(this.textArea).val(),preload=[],divHtml="<div style='height:fit-content' class='qtype-coderunner-table-outer-div'>\n<table class='table table-bordered qtype-coderunner_table'>\n";if(preloadJson)try{preload=JSON.parse(preloadJson)}catch(error){return this.fail=!0,void(this.failString="table_ui_invalidjson")}try{divHtml+=this.tableHeadSection(),divHtml+="<tbody>\n";for(var num_rows_required=Math.max(this.uiParams.num_rows,preload.length),iRow=0;iRow<num_rows_required;iRow++)divHtml+=this.tableRow(iRow,preload);if(divHtml+="</tbody>\n</table>\n</div>",this.tableDiv=$(divHtml),this.uiParams.dynamic_rows&&this.addButtons(),1==this.rowsPerCell){const ENTER=13;$(this.tableDiv).find(".table_ui_cell").each((function(){$(this).on("keydown",(e=>{e.keyCode===ENTER&&e.preventDefault()}))}))}}catch(error){this.fail=!0,this.failString="table_ui_invalidserialisation"}},TableUi.prototype.addButtons=function(){var deleteButton=$('<button type="button"style="float:right;margin-right:6px" disabled>Delete row</button>'),t=this;this.tableDiv.append(deleteButton),deleteButton.click((function(){var numRows=t.tableDiv.find("table tbody tr").length,lastRow=t.tableDiv.find("tr:last");numRows>t.uiParams.num_rows&&lastRow.remove(),lastRow=t.tableDiv.find("tr:last"),numRows==t.uiParams.num_rows+1&&$(this).prop("disabled",!0)}));var addButton=$('<button type="button"style="float:right;margin-right:6px">Add row</button>');t.tableDiv.append(addButton),addButton.click((function(){var lastRow,newRow;(newRow=(lastRow=t.tableDiv.find("table tbody tr:last")).clone()).find(".table_ui_cell").each((function(){$(this).val("")})),lastRow.after(newRow),$(this).prev().prop("disabled",!1)}))},TableUi.prototype.resize=function(){},TableUi.prototype.hasFocus=function(){var focused=!1;return $(this.tableDiv).find(".table_ui_cell").each((function(){this===document.activeElement&&(focused=!0)})),focused},TableUi.prototype.destroy=function(){this.sync(),$(this.tableDiv).remove(),this.tableDiv=null},{Constructor:TableUi}})); /** * JavaScript for handling textareas and form actions in CodeRunner question * editing forms and student question answering forms. * * @module qtype_coderunner/textareas * @copyright Richard Lobb, 2015, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/textareas",["jquery"],(function($){function initTextArea(){$(this).data("clickInProgress",!1),$(this).data("capturingTab",!0),$(this).on("mousedown",(function(){$(this).data("clickInProgress",!0)})),$(this).on("focusin",(function(){$(this).data("capturingTab",$(this).data("clickInProgress"))})),$(this).on("click",(function(){$(this).data("clickInProgress",!1)})),$(this).on("keydown",(function(e){if(!(window.hasOwnProperty("behattesting")&&window.behattesting||void 0!==e.which&&0===e.which))if(9==e.keyCode&&$(this).data("capturingTab"))(e.shiftKey||insertString(this," "))&&e.preventDefault();else if(13===e.keyCode&&void 0!==this.selectionStart){for(var before=this.value.substring(0,this.selectionStart),eol=before.lastIndexOf("\n"),line=before.substring(eol+1),indent="",i=0;i<line.length&&" "===line.charAt(i);i++)indent+=" ";insertString(this,"\n"+indent)&&e.preventDefault(),$(this).data("capturingTab",!0)}else 77===e.keyCode&&e.ctrlKey&&!e.altKey?($(this).data("capturingTab",!$(this).data("capturingTab")),e.preventDefault()):27===e.keyCode?$(this).data("capturingTab",!1):e.ctrlKey||e.altKey||$(this).data("capturingTab",!0)}))}function insertString(ta,sToInsert){if(void 0!==ta.selectionStart){var before=ta.value.substring(0,ta.selectionStart),selSave=ta.selectionEnd,after=ta.value.substring(ta.selectionEnd,ta.value.length),tmp=ta.scrollTop;ta.value=before+sToInsert+after;var pos=selSave+sToInsert.length;return ta.selectionStart=pos,ta.selectionEnd=pos,ta.scrollTop=tmp,!0}if(document.selection&&document.selection.createRange){var r=document.selection.createRange(),dr=r.duplicate();return dr.moveToElementText(ta),dr.setEndPoint("EndToEnd",r),r.text=sToInsert,!0}return!1}return{setupAllTAs:function(){$("textarea.edit_code").each(initTextArea)},initQuestionTA:function(taId){$(document.getElementById(taId)).each(initTextArea)},setupShowHideAnswer:function(linkId,divId){let link=$(document.getElementById(linkId)),div=$(document.getElementById(divId)),hdr=link.children()[0],hdrText=hdr.innerText;link.click((()=>{div.is(":visible")?(div.hide(),hdr.innerText=hdrText.replace("â–¾","â–¸")):(div.show(),div.trigger("mousemove"),hdr.innerText=hdrText.replace("â–¸","â–¾"))}))}}})); /****************************************************************************** * * This module provides a wrapper for user-interface modules, handling hiding * of the textArea that is being replaced by the UI element, * resizing of the UI component, and support of such usability functions as * ctrl-alt-M to disable/re-enable the entire user interface, including the * wrapper. * * @module coderunner/userinterfacewrapper * @copyright Richard Lobb, 2015, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * * The InterfaceWrapper class is constructed either by Moodle PHP calls of * the form * * $PAGE->requires->js_call_amd($modulename, $functionname, $params) * * (e.g. from within render.php) or by JavaScript require calls, e.g. from * authorform.js when the question author changes UI type. * * The InterfaceWrapper provides: * * 1. A constructor InterfaceWrapper(uiname, textareaId) which * hides the given text area, replaces it with a wrapper div (resizable in * height by the user but with width resizing managed by changes in window * width), created an instance of nameInstance as defined in the file * ui_name.js (see below). * params is a record containing the decoded value of * * 2. A stop() method that destroys the embedded UI and hides the wrapper. * * 3. A restart() method that shows the wrapper again and re-creates the prior * embedded UI component within it. * * 4. A loadUi(uiname, params) method that kills any currently running UI element * (if there is one) and (re)loads the specified one. The params parameter * is a record that allows additional parameters to be passed in, such as * those from the question's uiParams field and, in the case of the * Ace UI, the 'lang' (language) that the editor is editing. This data * is supplied by the PHP via the data-params attribute of the answer's * base textarea. * * 5. Regular checking for any resizing of the wrapper, which are passed on to * the embedded UI element's resize() method. * * 6. Monitoring of alt-ctrl-M key presses which toggle the visibility of the * wrapper plus UI element and the syncronised textArea by calls to stop() * and restart * * ========================================================================= * * The embedded user-interface module must be defined in a JavaScript file * of the form ui_name.js which must define a class nameInstance with * the following functionality: * * 1. A constructor SomeUiName(textareaId, width, height, params) that * builds an HTML component of the given width and height. textareaId is the * ID of the textArea from which the UI element should obtain its initial * serialisation and to which it should write the serialisation when its save * or destroy methods are called. params is a JavaScript object, * decoded from the JSON uiParams defined by the question plus any * additional data required, such as the 'lang' in the case of Ace. * * 2. A getElement() method that returns the HTML element that the * InterfaceWrapper is to insert into the document tree. * * 3. A method failed() that should return true unless the constructor * failed (e.g. because it was not able to de-serialise the text area's * contents). The wrapper will call destroy() on the object if failed() * returns true and abort the use of the UI element. The text area will * have the uiloadfailed class added, which CSS will display in some * error mode (e.g. a red border). * * 4. A method failMessage() that will be called only when failed() returns * True. It should be a defined CodeRunner language string key. * * 5. A sync() method that copies the serialised represention of the UI plugin's * data to the related TextArea. This is used when submit is clicked. * * 6. A destroy() method that should sync the contents to the text area then * destroy any HTML elements or other created content. This method is called * when CTRL-ALT-M is typed by the user to turn off all UI plugins * * 7. A resize(width, height) method that should resize the entire UI element * to the given dimensions. * * 8. A hasFocus() method that returns true if the UI element has focus. * * 9. A syncIntervalSecs() method that returns the time interval between * calls to the sync() method. 0 for no sync calls. The userinterfacewrapper * provides all instances with a generic (base-class) version that returns * the value of a UI parameter sync_interval_secs if given else uses the * UI interface wrapper default (currently 5). * * The return value from the module define is a record with a single field * 'Constructor' that references the constructor (e.g. Graph, AceWrapper etc) * *****************************************************************************/ define("qtype_coderunner/userinterfacewrapper",["jquery"],(function($){function InterfaceWrapper(uiname,textareaId){let t=this;this.GUTTER=14,this.DEFAULT_SYNC_INTERVAL_SECS=5;this.taId=textareaId,this.loadFailId=textareaId+"_loadfailerr";const ta=document.getElementById(textareaId);this.textArea=$(ta);const params=this.textArea.attr("data-params");this.uiParams=params?JSON.parse(params):{},this.uiParams.lang=this.textArea.attr("data-lang"),this.readOnly=this.textArea.prop("readonly"),this.isLoading=!1,this.loadFailed=!1,this.retries=0;let h=parseInt(this.textArea.css("height")),content_lines=this.textArea.val().split("\n").length,rows=ta.rows;content_lines>rows&&(rows=Math.min(content_lines,50)),h=Math.max(h,19*rows,50),this.wrapperNode=$("<div id='"+this.taId+"_wrapper' class='ui_wrapper'></div>"),this.textArea.after(this.wrapperNode),this.wrapperNode.hide(),this.wrapperNode.css({resize:"vertical",overflow:"hidden",minHeight:h,width:"100%",border:"1px solid darkgrey"}),this.textArea.data("current-ui-wrapper",this),this.uiInstance=null,this.loadUi(uiname,this.uiParams),$(document).mousemove((function(){t.checkForResize()})),$(window).resize((function(){t.checkForResize()})),this.textArea.closest("form").submit((function(){null!==t.uiInstance&&t.uiInstance.sync()})),$(document.body).on("keydown",(function(e){77===e.keyCode&&e.ctrlKey&&e.altKey&&(null!==t.uiInstance||t.loadFailed?t.stop():t.restart())}))}return InterfaceWrapper.prototype.loadUi=function(uiname,params){const t=this;function syncIntervalSecsBase(){return params.hasOwnProperty("sync_interval_secs")?parseInt(params.sync_interval_secs):t.DEFAULT_SYNC_INTERVAL_SECS}if(this.isLoading)return this.retries+=1,void(this.retries>20?(alert("Failed to load "+uiname+" UI component. If this error persists, please report it to the forum on coderunner.org.nz"),this.retries=0,this.loading=0):setTimeout((function(){t.loadUi(uiname,params)}),200));this.retries=0,this.params=params,this.stop(),this.uiname=uiname,""===this.uiname||"none"===this.uiname||sessionStorage.getItem("disableUis")?this.uiInstance=null:(this.isLoading=!0,require(["qtype_coderunner/ui_"+this.uiname],(function(ui){const h=t.wrapperNode.innerHeight()-t.GUTTER,w=t.wrapperNode.innerWidth(),uiInstance=new ui.Constructor(t.taId,w,h,params);if(uiInstance.failed()){t.loadFailed=!0,t.wrapperNode.hide(),uiInstance.destroy(),t.uiInstance=null,t.textArea.addClass("uiloadfailed");const loadFailDiv='<div id="'+t.loadFailId+'"class="uiloadfailed"></div>';let jqLoadFailDiv=$(loadFailDiv);jqLoadFailDiv.insertBefore(t.textArea),langString=uiInstance.failMessage(),errorDiv=jqLoadFailDiv,require(["core/str"],(function(str){const s=str.get_string(langString,"qtype_coderunner"),fallback=str.get_string("ui_fallback","qtype_coderunner");$.when(s,fallback).done((function(s,fallback){errorDiv.html(s+"<br>"+fallback)}))}))}else{t.hLast=0,t.wLast=0,t.textArea.hide(),t.wrapperNode.show(),t.wrapperNode.append(uiInstance.getElement()),t.uiInstance=uiInstance,t.loadFailed=!1,t.checkForResize();let uiInstancePrototype=Object.getPrototypeOf(uiInstance);uiInstancePrototype.syncIntervalSecs=uiInstancePrototype.syncIntervalSecs||syncIntervalSecsBase,t.startSyncTimer(uiInstance)}var langString,errorDiv;t.isLoading=!1})))},InterfaceWrapper.prototype.startSyncTimer=function(uiInstance){const timeout=uiInstance.syncIntervalSecs();this.uiInstance.timer=timeout?setInterval((function(){uiInstance.sync()}),1e3*timeout):null},InterfaceWrapper.prototype.stopSyncTimer=function(uiInstance){uiInstance.timer&&clearTimeout(uiInstance.timer)},InterfaceWrapper.prototype.stop=function(){null!==this.uiInstance&&(this.stopSyncTimer(this.uiInstance),this.textArea.show(),this.uiInstance.hasFocus()&&(this.textArea.focus(),this.textArea[0].selectionStart=this.textArea[0].value.length),this.uiInstance.destroy(),this.uiInstance=null,this.wrapperNode.hide()),this.loadFailed=!1,this.textArea.removeClass("uiloadfailed"),$(document.getElementById(this.loadFailId)).remove()},InterfaceWrapper.prototype.restart=function(){null===this.uiInstance&&this.loadUi(this.uiname,this.params)},InterfaceWrapper.prototype.checkForResize=function(){if(this.uiInstance){const h=this.wrapperNode.innerHeight(),w=this.wrapperNode.innerWidth();if(h!=this.hLast||w!=this.wLast){const xLeft=this.wrapperNode.offset().left,maxWidth=$(window).innerWidth()-xLeft-25,hAdjusted=h-this.GUTTER,wAdjusted=Math.min(maxWidth,w);this.uiInstance.resize(wAdjusted,hAdjusted),this.hLast=this.wrapperNode.innerHeight(),this.wLast=this.wrapperNode.innerWidth()}}},{newUiWrapper:function(uiname,textareaId){return uiname?new InterfaceWrapper(uiname,textareaId):null},InterfaceWrapper:InterfaceWrapper}})); define("qtype_coderunner/graphutil",(function(){function Util(){this.greekLetterNames=["Alpha","Beta","Gamma","Delta","Epsilon","Zeta","Eta","Theta","Iota","Kappa","Lambda","Mu","Nu","Xi","Omicron","Pi","Rho","Sigma","Tau","Upsilon","Phi","Chi","Psi","Omega"]}return Util.prototype.convertLatexShortcuts=function(text){for(var i=0;i<this.greekLetterNames.length;i++){var name=this.greekLetterNames[i];text=(text=text.replace(new RegExp("\\\\"+name,"g"),String.fromCharCode(913+i+(i>16)))).replace(new RegExp("\\\\"+name.toLowerCase(),"g"),String.fromCharCode(945+i+(i>16)))}for(i=0;i<10;i++)text=text.replace(new RegExp("_"+i,"g"),String.fromCharCode(8320+i));return text=text.replace(new RegExp("_a","g"),String.fromCharCode(8336))},Util.prototype.drawArrow=function(c,x,y,angle){var dx=Math.cos(angle),dy=Math.sin(angle);c.beginPath(),c.moveTo(x,y),c.lineTo(x-8*dx+5*dy,y-8*dy-5*dx),c.lineTo(x-8*dx-5*dy,y-8*dy+5*dx),c.fill()},Util.prototype.det=function(a,b,c,d,e,f,g,h,i){return a*e*i+b*f*g+c*d*h-a*f*h-b*d*i-c*e*g},Util.prototype.vectorMagnitude=function(v){return Math.sqrt(v.x*v.x+v.y*v.y)},Util.prototype.scalarProjection=function(a,b){return(a.x*b.x+a.y*b.y)/this.vectorMagnitude(b)},Util.prototype.isCCW=function(a,b){return a.x*b.y-b.x*a.y>0},Util.prototype.circleFromThreePoints=function(x1,y1,x2,y2,x3,y3){var a=this.det(x1,y1,1,x2,y2,1,x3,y3,1),bx=-this.det(x1*x1+y1*y1,y1,1,x2*x2+y2*y2,y2,1,x3*x3+y3*y3,y3,1),by=this.det(x1*x1+y1*y1,x1,1,x2*x2+y2*y2,x2,1,x3*x3+y3*y3,x3,1),c=-this.det(x1*x1+y1*y1,x1,y1,x2*x2+y2*y2,x2,y2,x3*x3+y3*y3,x3,y3);return{x:-bx/(2*a),y:-by/(2*a),radius:Math.sqrt(bx*bx+by*by-4*a*c)/(2*Math.abs(a))}},Util.prototype.isInside=function(pos,rect){return pos.x>rect.x&&pos.x<rect.x+rect.width&&pos.y<rect.y+rect.height&&pos.y>rect.y},Util.prototype.crossBrowserKey=function(e){return(e=e||window.event).which||e.keyCode},Util.prototype.crossBrowserRelativeMousePos=function(e){const rect=e.target.getBoundingClientRect();return{x:e.clientX-rect.left,y:e.clientY-rect.top}},new Util})); define("qtype_coderunner/outputdisplayarea",["exports","core/ajax","core/str"],(function(_exports,_ajax,_str){var obj; /** * A module used for running code using the Coderunner webservice (CRWS) and displaying output. Originally * developed for use in the Scratchpad UI. It has three modes of operation: * - 'text': Just display the output as text, html escaped. * - 'json': The recommended way to display programs that use stdin or output images (or both). * - Accepts JSON in the CRWS response output with fields: * - "returncode": Error/return code from running program. * - "stdout": Stdout text from running program. * - "stderr": Error text from running program. * - "files": An object containing filenames mapped to base64 encoded images. * These will be displayed below any stdout text. * - When input from stdin is required the returncode 42 should be returned, raise this * any time the program asks for input. An (html) input will be added after the last stdout received. * When enter is pressed, runCode is called with value of the input added to the stdin string. * This repeats until returncode is no longer 42. * - 'html': Display program output as raw html inside the output area. * - This can be used to show images and insert other HTML tags (and beyond). * - Giving an <input> tag the class 'coderunner-run-input' will add an event that * on pressing enter will call the runCode method again with the value of that input field added to stdin. * This method of receiving stdin is harder to use but more flexible than JSON, enter at your own risk. * * @module qtype_coderunner/outputdisplayarea * @copyright James Napier, 2023, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.OutputDisplayArea=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};const JSON_DISPLAY_PROPS=["returncode","stdout","stderr","files"],setLangString=async function(langStringName,node,callback){let additionalText=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",message=await(0,_str.get_string)(langStringName,"qtype_coderunner");langStringName.includes("error")&&(message="*** "+message+" ***\n"),additionalText&&(message+=additionalText),callback instanceof Function?callback(node,message):node.innerText=message},combinedOutput=response=>response.cmpinfo+response.output+response.stderr,getImage=function(base64){let type=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"png";const image=document.createElement("img");return image.src="data:image/".concat(type,";base64,").concat(base64),image};_exports.OutputDisplayArea=class{constructor(displayAreaId,outputMode,lang,sandboxParams){this.displayAreaId=displayAreaId,this.lang=lang,this.mode=outputMode,this.sandboxParams=sandboxParams,this.textDisplay=document.getElementById(displayAreaId+"-text"),this.imageDisplay=document.getElementById(displayAreaId+"-images"),this.prevRunSettings=null}clearDisplay(){this.textDisplay.innerHTML="",this.imageDisplay.innerHTML=""}displayText(response){this.textDisplay.innerText=combinedOutput(response)}displayHtml(response){this.textDisplay.innerHTML=combinedOutput(response);const inputEl=this.textDisplay.querySelector(".coderunner-run-input");inputEl&&this.addInputEvents(inputEl)}displayJson(response){const result=this.validateJson(response.output);let text=result.stdout;42!==result.returncode&&(text+=result.stderr),13==result.returncode&&setLangString("error_timeout",this.textDisplay,((node,msg)=>{node.innerText+=msg}));const numImages=this.displayImages(result.files);""===text.trim()&&42!==result.returncode?0==numImages&&this.displayNoOutput(null):this.textDisplay.innerText=text,42===result.returncode&&this.addInput()}validateJson(jsonString){let result=null;try{result=JSON.parse(jsonString)}catch(e){window.alert("Error parsing display JSON output: \n"+"'".concat(jsonString,"\n'")+"Error Msg: \n"+" ".concat(e.message," \n")+"The question author must fix this!")}const missing=((obj,props)=>props.filter((prop=>!obj.hasOwnProperty(prop))))(result,JSON_DISPLAY_PROPS);return missing.length>0&&window.alert("Display JSON (in response.result) is missing the following fields: \n"+"".concat(missing.join()," \n")+"The question author must fix this!"),result}displayNoOutput(response){const isNoOutput=!response||0===combinedOutput(response).length;if(isNoOutput||null===response){const span=document.createElement("span");span.style.color="red",setLangString("nooutput",span),this.clearDisplay(),this.textDisplay.append(span)}return isNoOutput}display(response){const error=(response=>{const ERROR_RESPONSES=[[1,0,"error_access_denied"],[2,0,"error_unknown_language"],[3,0,"error_access_denied"],[4,0,"error_submission_limit_reached"],[5,0,"error_sandbox_server_overload"],[0,11,""],[0,12,""],[0,13,"error_timeout"],[0,15,""],[0,17,"error_memory_limit"],[0,21,"error_sandbox_server_overload"],[0,30,"error_excessive_output"]];for(let i=0;i<ERROR_RESPONSES.length;i++){let row=ERROR_RESPONSES[i];if(row[0]==response.error&&(0!=response.error||response.result==row[1]))return row[2]}return"error_unknown_runtime"})(response);if(""===error){if(!this.displayNoOutput(response))if("json"===this.mode)this.displayJson(response);else if("html"===this.mode)this.displayHtml(response);else{if("text"!==this.mode)throw Error('Invalid outputMode given: "'.concat(this.mode,'"'));this.displayText(response)}}else setLangString(error,this.textDisplay)}runCode(code,stdin){let shouldClearDisplay=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.prevRunSettings=[code,stdin],shouldClearDisplay&&this.clearDisplay(),_ajax.default.call([{methodname:"qtype_coderunner_run_in_sandbox",args:{contextid:M.cfg.contextid,sourcecode:code,language:this.lang,stdin:stdin,params:JSON.stringify(this.sandboxParams)},done:responseJson=>{const response=JSON.parse(responseJson);this.display(response)},fail:error=>{alert(error.message)}}])}addInput(){const inputId="".concat(this.displayAreaId,"-input-field");this.textDisplay.innerHTML+='<input type="text" id="'.concat(inputId,'" class="').concat("coderunner-run-input",'">');const inputEl=document.getElementById(inputId);setLangString("enter_to_submit",inputEl,((node,msg)=>{node.placeholder+=msg})),this.addInputEvents(inputEl)}addInputEvents(inputEl){inputEl.focus(),inputEl.addEventListener("keydown",(e=>{13===e.keyCode&&e.preventDefault()})),inputEl.addEventListener("keyup",(e=>{if(13===e.keyCode){const line=inputEl.value;inputEl.remove(),this.textDisplay.innterHTML+=line,this.prevRunSettings[1]+=line+"\n",this.runCode(...this.prevRunSettings,!1)}}))}displayImages(files){let numImages=0;for(const[fname,fcontents]of Object.entries(files)){const fileType=fname.split(".")[1];if(fileType){const image=getImage(fcontents,fileType);this.imageDisplay.append(image),numImages+=1}else window.alert('Could not read filename correctly: "'.concat(fname,'"'))}return numImages}}})); /** * JavaScript to interface to the Ace editor, which is used both in * the author editing page and by the student question submission page. * The class defined in this module is a plugin for the InterfaceWrapper class * declared in userinterfacewrapper.js. See that file for an explanation of * the interface to this module. * * A special case behaviour of the AceWrapper is that it needs to know * the Programming language that is being edited. This MUST be provided in * the constructor params parameter (an associative array) as a string * with key 'lang'. * * @module qtype_coderunner/ui_ace * @copyright Richard Lobb, 2015, 2017, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_ace",["jquery"],(function($){function AceWrapper(textareaId,w,h,params){var session,code,textarea=$(document.getElementById(textareaId)),wrapper=$(document.getElementById(textareaId+"_wrapper")),focused=textarea[0]===document.activeElement,lang=params.lang,t=this;try{window.ace.require("ace/ext/language_tools"),this.modelist=window.ace.require("ace/ext/modelist"),this.textareaId=textareaId,this.textarea=textarea,this.enabled=!1,this.contents_changed=!1,this.capturingTab=!1,this.clickInProgress=!1,this.editNode=$("<div></div>"),this.editNode.css({resize:"none",height:h,width:"100%"}),this.editor=window.ace.edit(this.editNode.get(0)),textarea.prop("readonly")&&this.editor.setReadOnly(!0),this.editor.setOptions({enableBasicAutocompletion:!0,enableLiveAutocompletion:params.live_autocompletion,fontSize:params.font_size?params.font_size:"14px",newLineMode:"unix"}),this.editor.$blockScrolling=1/0,session=this.editor.getSession(),code=this.textarea.val(),(void 0===params.import_from_scratchpad||params.import_from_scratchpad)&&(code=this.extract_from_json_maybe(code)),session.setValue(code);const userTheme=window.localStorage.getItem("qtype_coderunner.ace.theme"),consider_prefers=params.auto_switch_light_dark&&window.matchMedia;null!==userTheme?this.editor.setTheme(userTheme):consider_prefers&&window.matchMedia("(prefers-color-scheme: dark)").matches?this.editor.setTheme("ace/theme/tomorrow_night"):consider_prefers&&window.matchMedia("(prefers-color-scheme: light)").matches?this.editor.setTheme("ace/theme/textmate"):params.theme?this.editor.setTheme("ace/theme/"+params.theme):this.editor.setTheme("ace/theme/textmate"),this.currentTheme=this.editor.getTheme(),this.fixSlowLoad(),this.setLanguage(lang),this.setEventHandlers(textarea),this.captureTab(),this.editor.renderer.on("afterRender",(function(){var gutter=wrapper.find(".ace_gutter");gutter.hasClass("moodle-has-zindex")||(gutter.addClass("moodle-has-zindex"),focused&&(t.editor.focus(),t.editor.navigateFileEnd()),t.aceLabel=wrapper.find(".answerprompt"),t.aceLabel.attr("for","ace_"+textareaId),t.aceTextarea=wrapper.find(".ace_text-input"),t.aceTextarea.attr("id","ace_"+textareaId))})),this.fail=!1}catch(err){this.fail=!0}}return AceWrapper.prototype.extract_from_json_maybe=function(code){try{code=JSON.parse(code).answer_code[0]}catch(err){}return code},AceWrapper.prototype.failed=function(){return this.fail},AceWrapper.prototype.failMessage=function(){return"ace_ui_notready"},AceWrapper.prototype.sync=function(){const thisThemeNow=this.editor.getTheme(),globalTheme=window.localStorage.getItem("qtype_coderunner.ace.theme");thisThemeNow!==this.currentTheme?(this.currentTheme=thisThemeNow,window.localStorage.setItem("qtype_coderunner.ace.theme",thisThemeNow)):globalTheme&&thisThemeNow!=globalTheme&&(this.editor.setTheme(globalTheme),this.currentTheme=globalTheme)},AceWrapper.prototype.syncIntervalSecs=function(){return 2},AceWrapper.prototype.setLanguage=function(language){var session=this.editor.getSession(),mode=this.findMode(language);mode&&session.setMode(mode.mode)},AceWrapper.prototype.getElement=function(){return this.editNode},AceWrapper.prototype.captureTab=function(){this.capturingTab=!0,this.editor.commands.bindKeys({Tab:"indent","Shift-Tab":"outdent"})},AceWrapper.prototype.releaseTab=function(){this.capturingTab=!1,this.editor.commands.bindKeys({Tab:null,"Shift-Tab":null})},AceWrapper.prototype.fixSlowLoad=function(){const observer=new IntersectionObserver((()=>{$(document).trigger("mousemove")})),editNode=this.editNode.get(0);observer.observe(editNode)},AceWrapper.prototype.setEventHandlers=function(){var t=this;this.editor.getSession().on("change",(function(){t.textarea.val(t.editor.getSession().getValue()),t.contents_changed=!0})),this.editor.on("blur",(function(){t.contents_changed&&t.textarea.trigger("change")})),this.editor.on("mousedown",(function(){t.clickInProgress=!0})),this.editor.on("focus",(function(){t.clickInProgress?t.captureTab():t.releaseTab()})),this.editor.on("click",(function(){t.clickInProgress=!1})),this.editor.container.addEventListener("keydown",(function(e){void 0!==e.which&&0===e.which||(77===e.keyCode&&e.ctrlKey&&!e.altKey?(t.capturingTab?t.releaseTab():t.captureTab(),e.preventDefault()):27===e.keyCode?t.releaseTab():e.shiftKey||e.ctrlKey||e.altKey||9==e.keyCode||t.captureTab())}),!0)},AceWrapper.prototype.destroy=function(){var focused;this.fail||(focused=this.editor.isFocused(),this.textarea.val(this.editor.getSession().getValue()),this.editor.destroy(),$(this.editNode).remove(),focused&&(this.textarea.focus(),this.textarea[0].selectionStart=this.textarea[0].value.length))},AceWrapper.prototype.hasFocus=function(){return this.editor.isFocused()},AceWrapper.prototype.findMode=function(language){var candidate,filename,result,candidates,nameMap={octave:"matlab",nodejs:"javascript","c#":"cs"};if("string"==typeof language){language.toLowerCase()in nameMap&&(language=nameMap[language.toLowerCase()]),candidates=[language,language.replace(/\d+$/,"")];for(var i=0;i<candidates.length;i++)if(filename="input."+(candidate=candidates[i]),(result=this.modelist.modesByName[candidate]||this.modelist.modesByName[candidate.toLowerCase()]||this.modelist.getModeForPath(filename)||this.modelist.getModeForPath(filename.toLowerCase()))&&"text"!==result.name)return result}},AceWrapper.prototype.resize=function(w,h){this.editNode.outerHeight(h),this.editNode.outerWidth(w),this.editor.resize()},{Constructor:AceWrapper}})); /** * This AMD module provides the functionality for the "Show differences" * button that is shown in the student's result page if their answer * isn't right and an "exact-match" (or near equivalent) grader is being used. * * @module qtype_coderunner/showdiff * @copyright Richard Lobb, 2016, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/showdiff",["jquery"],(function($){function lcss(items1,items2){var M,i,j,n,result,length;for(M=function(items1,items2){var lengths,i,j,n1=items1.length,n2=items2.length,has_fill="function"==typeof[1].fill;for(lengths=[],i=0;i<=n1;i+=1)if(lengths[i]=new Array(n2+1),has_fill)lengths[i].fill(0);else for(j=0;j<n2+1;j++)lengths[i][j]=0;for(i=0;i<n1;i+=1)for(j=0;j<n2;j+=1)items1[i]==items2[j]?lengths[i+1][j+1]=1+lengths[i][j]:lengths[i+1][j+1]=Math.max(lengths[i][j+1],lengths[i+1][j]);return lengths}(items1,items2),length=M[items1.length][items2.length],result=[],i=items1.length,j=items2.length,n=length-1;n>=0;)items1[i-1]==items2[j-1]?(result[n]=items1[i-1],n-=1,i-=1,j-=1):M[i-1][j]==M[i][j]?i-=1:j-=1;return result}function insertDels(tokens,subSeq,startDel,endDel){var i,html="",deleting=!1,ssi=0;for(void 0===startDel&&(startDel="<del>"),void 0===endDel&&(endDel="</del>"),i=0;i<tokens.length;i+=1)ssi<subSeq.length&&tokens[i]==subSeq[ssi]?(deleting&&(html+=endDel,deleting=!1),ssi+=1):deleting||(html+=startDel,deleting=!0),html+=tokens[i];return deleting&&(html+=endDel),html}function getTokens(element){var seq,token,match,isPre="pre"===element.tagName.toLowerCase(),text=element.innerHTML,i=0;for(isPre&&(text=text.replace(/\n/g,"↩\n")),text=text.replace(/(<br ?.*?>)/g,"↩$1"),seq=[],i=0;i<text.length;)seq.push((token=void 0,match=void 0,"&"!=text[i]||null===(match=text.substring(i,text.length).match(/(^&[a-zA-Z]+;)|(^&#[0-9]+;)|(^&#[xX][0-9a-fA-F]+;)/))?(token=text[i],i+=1):(token=match[0],i+=token.length),token));return seq}function showDifferences(firstEl,secondEl){var seq1,seq2,css;css=lcss(seq1=getTokens(firstEl),seq2=getTokens(secondEl)),firstEl.innerHTML=insertDels(seq1,css,"<del>","</del>"),secondEl.innerHTML=insertDels(seq2,css,"<del>","</del>")}function hideDifferences(firstEl,secondEl){var replPat=new RegExp("(</?del[^>]*>)|(↩)","g");firstEl.innerHTML=firstEl.innerHTML.replace(replPat,""),secondEl.innerHTML=secondEl.innerHTML.replace(replPat,"")}function processAllRows(tableRows,gotCol,expectedCol,f){for(var cells,i=0;i<tableRows.length;i++)f((cells=tableRows[i].getElementsByTagName("td"))[expectedCol].children[0],cells[gotCol].children[0])}return{initDiffButton:function(buttonId,showValue,hideValue,expectedString,gotString){var table,tableRows,thEls,diffButton=$('[id="'+buttonId+'"]'),columnCount=0,gotCol=-1,expectedCol=-1;thEls=(table=diffButton.closest("div.coderunner-test-results")).find("thead tr").children(),tableRows=table.find("tbody tr"),thEls.each((function(){$(this).html()===gotString?gotCol=columnCount:$(this).html()===expectedString&&(expectedCol=columnCount),columnCount+=1})),-1!==gotCol&&-1!==expectedCol?diffButton.on("click",(function(){diffButton.prop("value")===showValue?(processAllRows(tableRows.toArray(),gotCol,expectedCol,showDifferences),diffButton.prop("value",hideValue)):(processAllRows(tableRows.toArray(),gotCol,expectedCol,hideDifferences),diffButton.prop("value",showValue))})):(diffButton.enabled=!1,diffButton.hide())}}})); define("qtype_coderunner/ui_scratchpad",["exports","core/templates","qtype_coderunner/userinterfacewrapper","qtype_coderunner/outputdisplayarea"],(function(_exports,_templates,_userinterfacewrapper,_outputdisplayarea){var obj; /** * Implementation of the scratchpad_ui user interface plugin. For overall details * of the UI plugin architecture, see userinterfacewrapper.js. * * This plugin replaces the usual textarea answer element with a UI is designed to * allow the execution of code in the CodeRunner question in a manner similar to an IDE. * It contains two editor boxes, one on top of another, allowing users to enter and * edit code in both. It contains two embedded Ace UIs. * By default, only the top editor is visible and the bottom editor (Scratchpad Area) is hidden, * clicking the Scratchpad button shows it. The Scratchpad area contains a second editor, * a Run button and a Prefix with Answer checkbox. Additionally, there is a help button that * provides information about how to use the Scratchpad. * It's possible to run code 'in-browser' by clicking the Run Button, * without making a submission via the Check Button: * If Prefix with Answer is not checked, only the code in the Scratchpad is run -- * allowing for a rough working spot to quickly check the result of code. * Otherwise, when Prefix with Answer is checked, the code in the Scratchpad is * appended to the code in the first editor before being run. * The Run Button has some limitations when using its default configuration: * Does not support programs that use STDIN (by default); * Only supports textual STDOUT (by default). * Note: These features can be supported, see the README section on wrappers... * The serialisation of this UI is a JSON object with the fields * with fields: * answer_code: [""] A list containing a string with answer code from the first editor; * test_code: [""] A list containing a string with containing answer code from the second editor; * show_hide: ["1"] when scratchpad is visible, otherwise [""]; * prefix_ans: ["1"] when Prefix with Answer is checked, otherwise [""]. * * UI Parameters: * - scratchpad_name: display name of the scratchpad, used to hide/un-hide the scratchpad. * - button_name: run button text. * - prefix_name: prefix with answer check-box label text. * - help_text: help text to show. * - run_lang: language used to run code when the run button is clicked, * this should be the language your wrapper is written in (if applicable). * - wrapper_src: location of wrapper code to be used by the run button, if applicable: * setting to globalextra will use text in global extra field, * - prototypeextra will use the prototype extra field. * - output_display_mode: control how program output is displayed on runs, there are three modes: * - text: display program output as text, html escaped; * - json: display program output, when it is json, * - html: display program output as raw html. * NOTE: see qtype_coderunner/outputdisplayarea.js for more info... * - disable_scratchpad: disable the scratchpad, effectively reverting to the Ace UI * from student perspective. * - invert_prefix: inverts meaning of prefix_ans serialisation -- '1' means un-ticked, vice versa. * This can be used to swap the default state. * * @module qtype_coderunner/ui_scratchpad * @copyright Richard Lobb, 2022, The University of Canterbury * @copyright James Napier, 2022, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.Constructor=void 0,_templates=(obj=_templates)&&obj.__esModule?obj:{default:obj};const invertSerial=current=>"1"===current[0]?[""]:["1"],escapeRegExp=string=>string.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),overwriteValues=(defaults,prescribed)=>{let overwritten={...defaults};if(prescribed)for(const[key,value]of Object.entries(defaults))overwritten[key]=prescribed[key]||value;return overwritten};_exports.Constructor=class{constructor(textAreaId,width,height,uiParams){const DEF_UI_PARAMS={scratchpad_name:"",button_name:"",prefix_name:"",help_text:"",params:{},run_lang:uiParams.lang,output_display_mode:"text",disable_scratchpad:!1,wrapper_src:null,open_delimiter:"{|",close_delimiter:"|}",escape:!1};this.textArea=document.getElementById(textAreaId),this.textAreaId=textAreaId,this.height=height,this.readOnly=this.textArea.readonly,this.fail=!1,this.outerDiv=null,this.outputDisplay=null,this.invertPreload=uiParams.invert_prefix,this.lang=uiParams.lang,this.numRows=this.textArea.rows,this.uiParams=overwriteValues(DEF_UI_PARAMS,uiParams),this.runWrapper=this.getRunWrapper();const preloadString=this.textArea.value;let preload;try{preload=this.readJson(preloadString)}catch(error){return this.fail=!0,void(this.failString="scratchpad_ui_invalidserialisation")}this.updateContext(preload),this.reload()}getRunWrapper(){const wrapperSrc=this.uiParams.wrapper_src;let runWrapper=null;return wrapperSrc&&("globalextra"===wrapperSrc||"prototypeextra"===wrapperSrc?runWrapper=this.textArea.dataset[wrapperSrc]:(this.fail=!0,this.failString="scratchpad_ui_badrunwrappersrc")),runWrapper}failed(){return this.fail}failMessage(){return this.failString}sync(){if(!this.context)return;const serialisation=this.getSerialisation();this.setSerialisation(serialisation)}getSerialisation(){const prefixAns=document.getElementById(this.context.prefix_ans.id),showHide=document.getElementById(this.context.show_hide.id);let serialisation={answer_code:[this.context.answer_code.text],test_code:[this.context.test_code.text],show_hide:[this.context.show_hide.show],prefix_ans:[invertSerial(this.context.prefix_ans.checked)]};return this.answerTextarea&&(serialisation.answer_code=[this.answerTextarea.value]),this.testTextarea&&(serialisation.test_code=[this.testTextarea.value]),showHide&&!(el=>{if(!el.classList.contains("collapse")&&!el.classList.contains("collapsing"))throw Error("Element does not have collapse class");return!el.classList.contains("show")})(showHide)?serialisation.show_hide=["1"]:serialisation.show_hide=[""],null!=prefixAns&&prefixAns.checked||this.context.disable_scratchpad?serialisation.prefix_ans=["1"]:serialisation.prefix_ans=[""],this.invertPreload&&(serialisation.prefix_ans=invertSerial(serialisation.prefix_ans)),serialisation}setSerialisation(serialisation){serialisation.prefix_ans=invertSerial(serialisation.prefix_ans),Object.values(serialisation).some((val=>1===val.length&&val[0].length>0))?(serialisation.prefix_ans=invertSerial(serialisation.prefix_ans),this.textArea.value=JSON.stringify(serialisation)):this.textArea.value=""}getElement(){return this.outerDiv}handleRunButtonClick(){if(null===this.outputDisplay)return;this.sync();const preloadString=this.textArea.value,serial=this.readJson(preloadString),escape=code=>this.uiParams.escape?JSON.stringify(code).slice(1,-1):code,code=function(answerCode,testCode,prefixAns,template){let open=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"\\(",close=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"\\)";template||(template="".concat(open," ANSWER_CODE ").concat(close,"\n")+"".concat(open," SCRATCHPAD_CODE ").concat(close)),prefixAns||(answerCode="");const escOpen=escapeRegExp(open),escClose=escapeRegExp(close),answerRegex=new RegExp("".concat(escOpen,"\\s*ANSWER_CODE\\s*").concat(escClose),"g"),scratchpadRegex=new RegExp("".concat(escOpen,"\\s*SCRATCHPAD_CODE\\s*").concat(escClose),"g");return(template=template.replaceAll(answerRegex,(()=>answerCode))).replaceAll(scratchpadRegex,(()=>testCode))}(escape(serial.answer_code[0]),escape(serial.test_code[0]),serial.prefix_ans[0],this.runWrapper,this.uiParams.open_delimiter,this.uiParams.close_delimiter);this.outputDisplay.runCode(code,"",!0)}updateContext(preload){this.context={id:this.textAreaId,disable_scratchpad:this.uiParams.disable_scratchpad,scratchpad_name:this.uiParams.scratchpad_name,button_name:this.uiParams.button_name,help_text:{text:this.uiParams.help_text},answer_code:{id:this.textAreaId+"_answer-code",name:"answer_code",text:preload.answer_code[0],lang:this.lang,rows:this.numRows},test_code:{id:this.textAreaId+"_test-code",name:"test_code",text:preload.test_code[0],lang:this.lang,rows:6},show_hide:{id:this.textAreaId+"_scratchpad",show:preload.show_hide[0]},prefix_ans:{id:this.textAreaId+"_prefix-ans",label:this.uiParams.prefix_name,checked:preload.prefix_ans[0]},output_display:{id:this.textAreaId+"_run-output"},jquery_escape:function(){return function(text,render){return CSS.escape(render(text))}}}}readJson(preloadString){let serial;if(""!==preloadString){try{serial=JSON.parse(preloadString)}catch{serial={answer_code:[preloadString]}}if(!serial.hasOwnProperty("answer_code"))throw TypeError("JSON has wrong signature, missing answer_code field.")}return serial=overwriteValues({answer_code:[""],test_code:[""],show_hide:[""],prefix_ans:["1"]},serial),this.invertPreload&&(serial.prefix_ans=invertSerial(serial.prefix_ans)),serial}async reload(){try{const{html:html}=await _templates.default.renderForPromise("qtype_coderunner/scratchpad_ui",this.context);this.drawUi(html),this.addAceUis(),this.outputDisplay=new _outputdisplayarea.OutputDisplayArea(this.context.output_display.id,this.uiParams.output_display_mode,this.uiParams.run_lang,this.uiParams.params),this.addEventListeners()}catch(e){this.fail=!0,this.failString="scratchpad_ui_templateloadfail"}}drawUi(html){const wrapperDiv=document.getElementById(this.textAreaId).nextSibling;wrapperDiv.innerHTML=html,this.outerDiv=wrapperDiv.firstChild,wrapperDiv.style.resize="none"}addAceUis(){this.answerTextarea=document.getElementById(this.context.answer_code.id),this.testTextarea=document.getElementById(this.context.test_code.id),this.answerCodeUi=(0,_userinterfacewrapper.newUiWrapper)("ace",this.context.answer_code.id),this.testTextarea&&(this.testCodeUi=(0,_userinterfacewrapper.newUiWrapper)("ace",this.context.test_code.id))}addEventListeners(){const runButton=document.getElementById(this.textAreaId+"_run-btn");runButton&&runButton.addEventListener("click",(()=>this.handleRunButtonClick()))}resize(){}hasFocus(){var _this$answerCodeUi,_this$testCodeUi;let focused=!1;return null!==(_this$answerCodeUi=this.answerCodeUi)&&void 0!==_this$answerCodeUi&&_this$answerCodeUi.uiInstance.hasFocus()&&(focused=!0),null!==(_this$testCodeUi=this.testCodeUi)&&void 0!==_this$testCodeUi&&_this$testCodeUi.uiInstance.hasFocus()&&(focused=!0),focused}destroy(){var _this$answerCodeUi2,_this$testCodeUiCodeU,_this$outerDiv;this.sync(),null===(_this$answerCodeUi2=this.answerCodeUi)||void 0===_this$answerCodeUi2||_this$answerCodeUi2.uiInstance.destroy(),null===(_this$testCodeUiCodeU=this.testCodeUiCodeUi)||void 0===_this$testCodeUiCodeU||_this$testCodeUiCodeU.uiInstance.destroy(),null===(_this$outerDiv=this.outerDiv)||void 0===_this$outerDiv||_this$outerDiv.remove(),this.outerDiv=null}}})); /** * Implementation of the html_ui user interface plugin. For overall details * of the UI plugin architecture, see userinterfacewrapper.js. * * This plugin replaces the usual textarea answer element with a div * containing the author-supplied HTML. The serialisation of that HTML, * which is what is essentially copied back into the textarea for submissions * as the answer, is a JSON object. The fields of that object are the names * of all author-supplied HTML elements with a class 'coderunner-ui-element'; * all such objects are expected to have a 'name' attribute as well. The * associated field values are lists. Each list contains all the values, in * document order, of the results of calling the jquery val() method in turn * on each of the UI elements with that name. * This means that at least input, select and textarea * elements are supported. The author is responsible for checking the * compatibility of other elements with jquery's val() method. * * The HTML to use in the answer area must be provided as the contents of * either the globalextra field or the prototypeextra field in the question * authoring form. The choice of which is set by the html_src UI parameter, which * must be either 'globalextra' or 'prototypeextra'. * * If any fields of the answer html are to be preloaded, these should be specified * in the answer preload with json of the form '{"<fieldName>": "<fieldValueList>",...}' * where fieldValueList is a list of all the values to be assigned to the fields * with the given name, in document order. * * To accommodate the possibility of dynamic HTML, any leftover preload values, * that is, values that cannot be positioned within the HTML either because * there is no field of the required name or because, in the case of a list, * there are insufficient elements, are assigned to the data['leftovers'] * attribute of the outer html div, as a sub-object of the original object. * This outer div can be located as the 'closest' (in a jQuery sense) * div.qtype-coderunner-html-outer-div. The author-supplied HTML must include * JavaScript to make use of the 'leftovers'. * * As a special case of the serialisation, if all values in the serialisation * are either empty strings or a list of empty strings, the serialisation is * itself the empty string. * * @module coderunner/ui_html * @copyright Richard Lobb, 2018, The University of Canterbury * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_coderunner/ui_html",["jquery"],(function($){function HtmlUi(textareaId,width,height,uiParams){this.textArea=$(document.getElementById(textareaId)),this.textareaId=textareaId;var srcField=uiParams.html_src||"globalextra";this.html=this.textArea.attr("data-"+srcField),this.html=this.html.replace(/___textareaId___/gm,textareaId),this.readOnly=this.textArea.prop("readonly"),this.uiParams=uiParams,this.fail=!1,this.htmlDiv=null,this.reload()}return HtmlUi.prototype.failed=function(){return this.fail},HtmlUi.prototype.failMessage=function(){return"htmluiloadfail"},HtmlUi.prototype.sync=function(){var name,serialisation={},empty=!0;this.getFields().each((function(){var value,type;type=$(this).attr("type"),name=$(this).attr("name"),value="checkbox"!==type&&"radio"!==type||$(this).is(":checked")?$(this).val():"",serialisation.hasOwnProperty(name)?serialisation[name].push(value):serialisation[name]=[value],""!==value&&(empty=!1)})),empty?this.textArea.val(""):this.textArea.val(JSON.stringify(serialisation))},HtmlUi.prototype.getElement=function(){return this.htmlDiv},HtmlUi.prototype.getFields=function(){return $(this.htmlDiv).find(".coderunner-ui-element")},HtmlUi.prototype.setField=function(field,value){"checkbox"===field.attr("type")||"radio"===field.attr("type")?field.prop("checked",field.val()===value):field.val(value)},HtmlUi.prototype.reload=function(){var valuesToLoad,values,i,fields,leftOvers,content=$(this.textArea).val(),outerDiv="<div style='height:fit-content' class='qtype-coderunner-html-outer-div' id='"+("qtype-coderunner-outer-div-"+this.textareaId)+"'>";if(this.htmlDiv=$(outerDiv+this.html+"</div>"),this.htmlDiv.data("uiparams",this.uiParams),this.htmlDiv.data("templateparams",this.uiParams),content)try{for(var name in valuesToLoad=JSON.parse(content),leftOvers={},valuesToLoad){for(values=valuesToLoad[name],fields=this.getFields().filter("[name='"+name+"']"),leftOvers[name]=[],i=0;i<values.length;i++)i<fields.length?this.setField($(fields[i]),values[i]):leftOvers[name].push(values[i]);0===leftOvers[name].length&&delete leftOvers[name]}$.isEmptyObject(leftOvers)||this.htmlDiv.attr("data-leftovers",JSON.stringify(leftOvers))}catch(e){this.fail=!0}},HtmlUi.prototype.resize=function(){},HtmlUi.prototype.hasFocus=function(){var focused=!1;return this.getFields().each((function(){this===document.activeElement&&(focused=!0)})),focused},HtmlUi.prototype.destroy=function(){this.sync(),$(this.htmlDiv).remove(),this.htmlDiv=null},{Constructor:HtmlUi}})); /* * JavaScript to allow dragging options to slots (using mouse down or touch) or tab through slots using keyboard. * * @module qtype_ddimageortext/form * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ddimageortext/form",["jquery","core/dragdrop"],(function($,dragDrop){var dragDropToImageForm={maxBgImageSize:null,maxDragImageSize:null,fp:null,init:function(){dragDropToImageForm.fp=dragDropToImageForm.filePickers(),dragDropToImageForm.updateVisibilityOfFilePickers(),dragDropToImageForm.setOptionsForDragItemSelectors(),dragDropToImageForm.setupEventHandlers(),dragDropToImageForm.waitForFilePickerToInitialise()},setupPreviewArea:function(){$("#id_previewareaheader").append('<div class="ddarea que ddimageortext"> <div id="id_droparea" class="droparea"> <img class="dropbackground" /> <div class="dropzones"></div> </div> <div class="dragitems"></div></div>')},waitForFilePickerToInitialise:function(){null!==dragDropToImageForm.fp.file("bgimage").href?(M.util.js_pending("dragDropToImageForm"),$('form.mform[data-qtype="ddimageortext"]').on("change",".filepickerhidden",(function(){M.util.js_pending("dragDropToImageForm"),dragDropToImageForm.loadPreviewImage()})),$("#id_droparea").length||dragDropToImageForm.setupPreviewArea(),dragDropToImageForm.loadPreviewImage()):setTimeout(dragDropToImageForm.waitForFilePickerToInitialise,1e3)},loadPreviewImage:function(){$("fieldset#id_previewareaheader .dropbackground").one("load",dragDropToImageForm.afterPreviewImageLoaded).attr("src",dragDropToImageForm.fp.file("bgimage").href)},afterPreviewImageLoaded:function(){dragDropToImageForm.createDropZones(),M.util.js_complete("dragDropToImageForm")},createDropZones:function(){var dropZoneHolder=$(".dropzones");if(dropZoneHolder.empty(),null!==dragDropToImageForm.fp.file("bgimage").href){for(var numDrops=dragDropToImageForm.form.getFormValue("nodropzone",[]),dropNo=0;dropNo<numDrops;dropNo++){var dragNo=dragDropToImageForm.form.getFormValue("drops",[dropNo,"choice"]);if("0"!==dragNo){dragNo-=1;var group=dragDropToImageForm.form.getFormValue("drags",[dragNo,"draggroup"]),label=dragDropToImageForm.form.getFormValue("draglabel",[dragNo]);if("image"===dragDropToImageForm.form.getFormValue("drags",[dragNo,"dragitemtype"])){var imgUrl=dragDropToImageForm.fp.file("dragitem["+dragNo+"]").href;if(null===imgUrl)continue;dropZoneHolder.append('<img class="droppreview group'+group+" drop"+dropNo+'" src="'+imgUrl+'" alt="'+label+'" data-drop-no="'+dropNo+'">')}else""!==label&&dropZoneHolder.append('<div class="droppreview group'+group+" drop"+dropNo+'" data-drop-no="'+dropNo+'">'+label+"</div>")}}dragDropToImageForm.waitForAllDropImagesToBeLoaded()}},waitForAllDropImagesToBeLoaded:function(){$(".dropzones img").not((function(i,imgNode){return dragDropToImageForm.imageIsLoaded(imgNode)})).length>0?setTimeout((function(){dragDropToImageForm.waitForAllDropImagesToBeLoaded()}),100):dragDropToImageForm.updateDropZones()},imageIsLoaded:function(imgElement){return imgElement.complete&&0!==imgElement.naturalHeight},updateDropZones:function(){if(null!==dragDropToImageForm.fp.file("bgimage").href){for(var dropBackgroundPosition=$("fieldset#id_previewareaheader .dropbackground").offset(),numDrops=dragDropToImageForm.form.getFormValue("nodropzone",[]),dropNo=0;dropNo<numDrops;dropNo++){var drop=$(".dropzones .drop"+dropNo);if(0!==drop.length){var dragNo=dragDropToImageForm.form.getFormValue("drops",[dropNo,"choice"])-1;drop.offset({left:dropBackgroundPosition.left+parseInt(dragDropToImageForm.form.getFormValue("drops",[dropNo,"xleft"])),top:dropBackgroundPosition.top+parseInt(dragDropToImageForm.form.getFormValue("drops",[dropNo,"ytop"]))});var label=dragDropToImageForm.form.getFormValue("draglabel",[dragNo]);drop.is("img")?drop.attr("alt",label):drop.html(label)}}$(".dropzones .droppreview").css("padding","0");for(var numGroups=$(".draggroup select").first().find("option").length,group=1;group<=numGroups;group++)dragDropToImageForm.resizeAllDragsAndDropsInGroup(group)}},resizeAllDragsAndDropsInGroup:function(group){var drops=$(".dropzones .droppreview.group"+group),maxWidth=0,maxHeight=0;drops.each((function(i,drop){maxWidth=Math.max(maxWidth,Math.ceil(drop.offsetWidth)),maxHeight=Math.max(maxHeight,Math.ceil(drop.offsetHeight))})),maxWidth+=10,maxHeight+=10,drops.each((function(i,drop){var left=Math.round((maxWidth-drop.offsetWidth)/2),top=Math.floor((maxHeight-drop.offsetHeight)/2);$(drop).css({"padding-left":left+"px","padding-right":maxWidth-drop.offsetWidth-left+"px","padding-top":top+"px","padding-bottom":maxHeight-drop.offsetHeight-top+"px"})}))},setupEventHandlers:function(){$("fieldset#id_draggableitemheader").on("change input","input, select",(function(e){var input=$(e.target).closest("select, input");input.hasClass("dragitemtype")&&dragDropToImageForm.updateVisibilityOfFilePickers(),dragDropToImageForm.setOptionsForDragItemSelectors(),input.is(".dragitemtype, .draggroup")?dragDropToImageForm.createDropZones():input.is(".draglabel")&&dragDropToImageForm.updateDropZones()})),$("fieldset#id_dropzoneheader").on("change input","input, select",(function(e){$(e.target).closest("select, input").is("select")?dragDropToImageForm.createDropZones():dragDropToImageForm.updateDropZones()})),$("fieldset#id_previewareaheader").on("mousedown touchstart",".droppreview",(function(e){dragDropToImageForm.dragStart(e)})),$(window).on("resize",(function(){dragDropToImageForm.updateDropZones()}))},updateVisibilityOfFilePickers:function(){for(var numDrags=dragDropToImageForm.form.getFormValue("noitems",[]),dragNo=0;dragNo<numDrags;dragNo++){var picker=$("input#id_dragitem_"+dragNo).closest(".fitem_ffilepicker");"image"===dragDropToImageForm.form.getFormValue("drags",[dragNo,"dragitemtype"])?picker.show():picker.hide()}},setOptionsForDragItemSelectors:function(){for(var dragItemOptions={0:""},numDrags=dragDropToImageForm.form.getFormValue("noitems",[]),numDrops=dragDropToImageForm.form.getFormValue("nodropzone",[]),dragNo=0;dragNo<numDrags;dragNo++){var label=dragDropToImageForm.form.getFormValue("draglabel",[dragNo]),file=dragDropToImageForm.fp.file(dragDropToImageForm.form.toNameWithIndex("dragitem",[dragNo]));"image"===dragDropToImageForm.form.getFormValue("drags",[dragNo,"dragitemtype"])&&null!==file.name?dragItemOptions[dragNo+1]=dragNo+1+". "+label+" ("+file.name+")":""!==label&&(dragItemOptions[dragNo+1]=dragNo+1+". "+label)}for(var dropNo=0;dropNo<numDrops;dropNo++){var selector=$("#id_drops_"+dropNo+"_choice"),selectedvalue=selector.val();for(var value in selector.find("option").remove(),dragItemOptions)if(dragItemOptions.hasOwnProperty(value)){selector.append('<option value="'+value+'">'+dragItemOptions[value]+"</option>");var optionnode=selector.find('option[value="'+value+'"]');parseInt(value)===parseInt(selectedvalue)?optionnode.attr("selected",!0):dragDropToImageForm.isItemUsed(parseInt(value))&&optionnode.attr("disabled",!0)}}},isItemUsed:function(value){return 0!==value&&(!dragDropToImageForm.form.getFormValue("drags",[value-1,"infinite"])&&0!==$("fieldset#id_dropzoneheader select").filter((function(i,selectNode){return parseInt($(selectNode).val())===value})).length)},dragStart:function(e){var drop=$(e.target).closest(".droppreview");dragDrop.prepare(e).start&&dragDrop.start(e,drop,(function(x,y,drop){dragDropToImageForm.dragMove(drop)}),(function(){dragDropToImageForm.dragEnd()}))},dragMove:function(drop){var backgroundImage=$("fieldset#id_previewareaheader .dropbackground"),backgroundPosition=backgroundImage.offset(),dropNo=drop.data("dropNo"),dropPosition=drop.offset(),left=Math.round(dropPosition.left-backgroundPosition.left),top=Math.round(dropPosition.top-backgroundPosition.top);left=Math.round(Math.max(0,Math.min(left,backgroundImage.outerWidth()-drop.outerWidth()))),top=Math.round(Math.max(0,Math.min(top,backgroundImage.outerHeight()-drop.outerHeight()))),dragDropToImageForm.form.setFormValue("drops",[dropNo,"xleft"],left),dragDropToImageForm.form.setFormValue("drops",[dropNo,"ytop"],top)},dragEnd:function(){dragDropToImageForm.updateDropZones()},form:{toNameWithIndex:function(name,indexes){for(var indexString=name,i=0;i<indexes.length;i++)indexString=indexString+"["+indexes[i]+"]";return indexString},getEl:function(name,indexes){return $('form.mform[data-qtype="ddimageortext"]')[0].elements[this.toNameWithIndex(name,indexes)]},getFormValue:function(name,indexes){var el=this.getEl(name,indexes);return el.type||(el=el[el.length-1]),"checkbox"===el.type?el.checked:el.value},setFormValue:function(name,indexes,value){var el=this.getEl(name,indexes);"checkbox"===el.type?el.checked=value:el.value=value}},filePickers:function(){var draftItemIdsToName,nameToParentNode;void 0===draftItemIdsToName&&(draftItemIdsToName={},nameToParentNode={},$('form.mform[data-qtype="ddimageortext"] input.filepickerhidden').each((function(index,filepicker){draftItemIdsToName[filepicker.value]=filepicker.name,nameToParentNode[filepicker.name]=filepicker.parentNode})));return{file:function(name){var fileAnchor=$(nameToParentNode[name]).find("div.filepicker-filelist a");return fileAnchor.length?{href:fileAnchor.get(0).href,name:fileAnchor.get(0).innerHTML}:{href:null,name:null}},name:function(draftitemid){return draftItemIdsToName[draftitemid]}}}};return{init:dragDropToImageForm.init}})); /* * JavaScript to allow dragging options to slots (using mouse down or touch) or tab through slots using keyboard. * * @module qtype_ddimageortext/question * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ddimageortext/question",["jquery","core/dragdrop","core/key_codes","core_form/changechecker"],(function($,dragDrop,keys,FormChangeChecker){function DragDropOntoImageQuestion(containerId,readOnly,places){this.containerId=containerId,this.questionAnswer={},M.util.js_pending("qtype_ddimageortext-init-"+this.containerId),this.places=places,this.allImagesLoaded=!1,this.imageLoadingTimeoutId=null,this.isPrinting=!1,readOnly&&this.getRoot().addClass("qtype_ddimageortext-readonly");var thisQ=this;this.getNotYetLoadedImages().one("load",(function(){thisQ.waitForAllImagesToBeLoaded()})),this.waitForAllImagesToBeLoaded()}DragDropOntoImageQuestion.prototype.waitForAllImagesToBeLoaded=function(){var thisQ=this;this.allImagesLoaded||(null!==this.imageLoadingTimeoutId&&clearTimeout(this.imageLoadingTimeoutId),this.getNotYetLoadedImages().length>0?this.imageLoadingTimeoutId=setTimeout((function(){thisQ.waitForAllImagesToBeLoaded()}),100):(this.allImagesLoaded=!0,thisQ.setupQuestion()))},DragDropOntoImageQuestion.prototype.getNotYetLoadedImages=function(){var thisQ=this;return this.getRoot().find(".ddarea img").not((function(i,imgNode){return thisQ.imageIsLoaded(imgNode)}))},DragDropOntoImageQuestion.prototype.imageIsLoaded=function(imgElement){return imgElement.complete&&0!==imgElement.naturalHeight},DragDropOntoImageQuestion.prototype.setupQuestion=function(){this.resizeAllDragsAndDrops(),this.cloneDrags(),this.positionDragsAndDrops(),M.util.js_complete("qtype_ddimageortext-init-"+this.containerId)},DragDropOntoImageQuestion.prototype.resizeAllDragsAndDrops=function(){var thisQ=this;this.getRoot().find(".draghomes > div").each((function(i,node){thisQ.resizeAllDragsAndDropsInGroup(thisQ.getClassnameNumericSuffix($(node),"dragitemgroup"))}))},DragDropOntoImageQuestion.prototype.resizeAllDragsAndDropsInGroup=function(group){var root=this.getRoot(),dragHomes=root.find(".dragitemgroup"+group+" .draghome"),maxWidth=0,maxHeight=0;for(var i in dragHomes.each((function(i,drag){maxWidth=Math.max(maxWidth,Math.ceil(drag.offsetWidth)),maxHeight=Math.max(maxHeight,Math.ceil(drag.offsetHeight))})),maxWidth+=10,maxHeight+=10,dragHomes.each((function(i,drag){var left=Math.round((maxWidth-drag.offsetWidth)/2),top=Math.floor((maxHeight-drag.offsetHeight)/2);$(drag).css({"padding-left":left+"px","padding-right":maxWidth-drag.offsetWidth-left+"px","padding-top":top+"px","padding-bottom":maxHeight-drag.offsetHeight-top+"px"})})),this.places)if(this.places.hasOwnProperty(i)){var place=this.places[i],label=place.text;parseInt(place.group)===group&&(""===label&&(label=M.util.get_string("blank","qtype_ddimageortext")),root.find(".dropzones").append('<div class="dropzone active group'+place.group+" place"+i+'" tabindex="0"><span class="accesshide">'+label+"</span> </div>"),root.find(".dropzone.place"+i).width(maxWidth-2).height(maxHeight-2))}},DragDropOntoImageQuestion.prototype.cloneDrags=function(){var thisQ=this;thisQ.getRoot().find(".draghome").each((function(index,dragHome){var drag=$(dragHome),placeHolder=drag.clone();placeHolder.removeClass(),placeHolder.addClass("draghome choice"+thisQ.getChoice(drag)+" group"+thisQ.getGroup(drag)+" dragplaceholder"),drag.before(placeHolder)}))},DragDropOntoImageQuestion.prototype.cloneDragsForOneChoice=function(dragHome){if(dragHome.hasClass("infinite"))for(var noOfDrags=this.noOfDropsInGroup(this.getGroup(dragHome)),i=0;i<noOfDrags;i++)this.cloneDrag(dragHome);else this.cloneDrag(dragHome)},DragDropOntoImageQuestion.prototype.cloneDrag=function(dragHome){var drag=dragHome.clone();drag.removeClass("draghome").addClass("drag unplaced moodle-has-zindex").offset(dragHome.offset()),this.getRoot().find(".dragitems").append(drag)},DragDropOntoImageQuestion.prototype.positionDragsAndDrops=function(){var thisQ=this,root=this.getRoot(),bgRatio=this.bgRatio();root.find(".ddarea .dropzone").each((function(i,dropNode){var drop=$(dropNode),place=thisQ.places[thisQ.getPlace(drop)];drop.css("left",parseInt(place.xy[0])*bgRatio).css("top",parseInt(place.xy[1])*bgRatio),drop.data("originX",parseInt(place.xy[0])).data("originY",parseInt(place.xy[1])),thisQ.handleElementScale(drop,"left top")})),root.find(".draghome").not(".dragplaceholder").each((function(i,dragNode){var drag=$(dragNode),currentPlace=thisQ.getClassnameNumericSuffix(drag,"inplace");drag.addClass("unplaced").removeClass("placed"),drag.removeAttr("tabindex"),null!==currentPlace&&drag.removeClass("inplace"+currentPlace)})),root.find("input.placeinput").each((function(i,inputNode){var input=$(inputNode),choice=input.val();if(!(0===choice.length||choice.length>0&&"0"===choice)){var place=thisQ.getPlace(input),unplacedDrag=thisQ.getUnplacedChoice(thisQ.getGroup(input),choice),hiddenDrag=thisQ.getDragClone(unplacedDrag);if(hiddenDrag.length)if(unplacedDrag.hasClass("infinite")){var noOfDrags=thisQ.noOfDropsInGroup(thisQ.getGroup(unplacedDrag));if(thisQ.getInfiniteDragClones(unplacedDrag,!1).length<noOfDrags){var cloneDrag=unplacedDrag.clone();cloneDrag.removeClass("beingdragged"),cloneDrag.removeAttr("tabindex"),hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag)}else hiddenDrag.addClass("active")}else hiddenDrag.addClass("active");var drop=root.find(".dropzone.place"+place);thisQ.sendDragToDrop(unplacedDrag,drop)}})),thisQ.questionAnswer=thisQ.getQuestionAnsweredValues()},DragDropOntoImageQuestion.prototype.getQuestionAnsweredValues=function(){let result={};return this.getRoot().find("input.placeinput").each(((i,inputNode)=>{result[inputNode.id]=inputNode.value})),result},DragDropOntoImageQuestion.prototype.isQuestionInteracted=function(){const oldAnswer=this.questionAnswer,newAnswer=this.getQuestionAnsweredValues();let isInteracted=!1;return JSON.stringify(newAnswer)!==JSON.stringify(oldAnswer)?(isInteracted=!0,isInteracted):(Object.keys(newAnswer).forEach((key=>{newAnswer[key]!==oldAnswer[key]&&(isInteracted=!0)})),isInteracted)},DragDropOntoImageQuestion.prototype.handleDragStart=function(e){var thisQ=this,drag=$(e.target).closest(".draghome"),newIndex=this.calculateZIndex()+2;if(dragDrop.prepare(e).start&&!drag.hasClass("beingdragged")){drag.addClass("beingdragged").css("transform","").css("z-index",newIndex);var currentPlace=this.getClassnameNumericSuffix(drag,"inplace");if(null!==currentPlace){this.setInputValue(currentPlace,0),drag.removeClass("inplace"+currentPlace);var hiddenDrop=thisQ.getDrop(drag,currentPlace);hiddenDrop.length&&(hiddenDrop.addClass("active"),drag.offset(hiddenDrop.offset()))}else{var hiddenDrag=thisQ.getDragClone(drag);if(hiddenDrag.length)if(drag.hasClass("infinite")){var noOfDrags=this.noOfDropsInGroup(thisQ.getGroup(drag));if(this.getInfiniteDragClones(drag,!1).length<noOfDrags){var cloneDrag=drag.clone();cloneDrag.removeClass("beingdragged"),cloneDrag.removeAttr("tabindex"),hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag),drag.offset(cloneDrag.offset())}else hiddenDrag.addClass("active"),drag.offset(hiddenDrag.offset())}else hiddenDrag.addClass("active"),drag.offset(hiddenDrag.offset())}dragDrop.start(e,drag,(function(x,y,drag){thisQ.dragMove(x,y,drag)}),(function(x,y,drag){thisQ.dragEnd(x,y,drag)}))}},DragDropOntoImageQuestion.prototype.dragMove=function(pageX,pageY,drag){var thisQ=this,highlighted=!1;this.getRoot().find(".dropzone.group"+this.getGroup(drag)).each((function(i,dropNode){var drop=$(dropNode);thisQ.isPointInDrop(pageX,pageY,drop)&&!highlighted?(highlighted=!0,drop.addClass("valid-drag-over-drop")):drop.removeClass("valid-drag-over-drop")})),this.getRoot().find(".draghome.placed.group"+this.getGroup(drag)).not(".beingdragged").each((function(i,dropNode){var drop=$(dropNode);!thisQ.isPointInDrop(pageX,pageY,drop)||highlighted||thisQ.isDragSameAsDrop(drag,drop)?drop.removeClass("valid-drag-over-drop"):(highlighted=!0,drop.addClass("valid-drag-over-drop"))}))},DragDropOntoImageQuestion.prototype.dragEnd=function(pageX,pageY,drag){var thisQ=this,root=this.getRoot(),placed=!1;root.find(".dropzone.group"+this.getGroup(drag)).each((function(i,dropNode){var drop=$(dropNode);return!thisQ.isPointInDrop(pageX,pageY,drop)||(drop.removeClass("valid-drag-over-drop"),thisQ.sendDragToDrop(drag,drop),placed=!0,!1)})),placed||root.find(".draghome.placed.group"+this.getGroup(drag)).not(".beingdragged").each((function(i,placedNode){var placedDrag=$(placedNode);if(!thisQ.isPointInDrop(pageX,pageY,placedDrag)||thisQ.isDragSameAsDrop(drag,placedDrag))return!0;placedDrag.removeClass("valid-drag-over-drop");var currentPlace=thisQ.getClassnameNumericSuffix(placedDrag,"inplace"),drop=thisQ.getDrop(drag,currentPlace);return thisQ.sendDragToDrop(drag,drop),placed=!0,!1})),placed||this.sendDragHome(drag)},DragDropOntoImageQuestion.prototype.sendDragToDrop=function(drag,drop){var oldDrag=this.getCurrentDragInPlace(this.getPlace(drop));if(0!==oldDrag.length){oldDrag.addClass("beingdragged"),oldDrag.offset(oldDrag.offset());var currentPlace=this.getClassnameNumericSuffix(oldDrag,"inplace");this.getDrop(oldDrag,currentPlace).addClass("active"),this.sendDragHome(oldDrag)}0===drag.length?(this.setInputValue(this.getPlace(drop),0),drop.data("isfocus")&&drop.focus()):(this.setInputValue(this.getPlace(drop),this.getChoice(drag)),drag.removeClass("unplaced").addClass("placed inplace"+this.getPlace(drop)),drag.attr("tabindex",0),this.animateTo(drag,drop))},DragDropOntoImageQuestion.prototype.sendDragHome=function(drag){var currentPlace=this.getClassnameNumericSuffix(drag,"inplace");null!==currentPlace&&drag.removeClass("inplace"+currentPlace),drag.data("unplaced",!0),this.animateTo(drag,this.getDragHome(this.getGroup(drag),this.getChoice(drag)))},DragDropOntoImageQuestion.prototype.handleKeyPress=function(e){var drop=$(e.target).closest(".dropzone");if(0===drop.length){var placedDrag=$(e.target),currentPlace=this.getClassnameNumericSuffix(placedDrag,"inplace");null!==currentPlace&&(drop=this.getDrop(placedDrag,currentPlace))}var currentDrag=this.getCurrentDragInPlace(this.getPlace(drop)),nextDrag=$();switch(e.keyCode){case keys.space:case keys.arrowRight:case keys.arrowDown:nextDrag=this.getNextDrag(this.getGroup(drop),currentDrag);break;case keys.arrowLeft:case keys.arrowUp:nextDrag=this.getPreviousDrag(this.getGroup(drop),currentDrag);break;case keys.escape:questionManager.isKeyboardNavigation=!1;break;default:return void(questionManager.isKeyboardNavigation=!1)}if(nextDrag.length){nextDrag.data("isfocus",!0),nextDrag.addClass("beingdragged");var hiddenDrag=this.getDragClone(nextDrag);if(hiddenDrag.length)if(nextDrag.hasClass("infinite")){var noOfDrags=this.noOfDropsInGroup(this.getGroup(nextDrag));if(this.getInfiniteDragClones(nextDrag,!1).length<noOfDrags){var cloneDrag=nextDrag.clone();cloneDrag.removeClass("beingdragged"),cloneDrag.removeAttr("tabindex"),hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag),nextDrag.offset(cloneDrag.offset())}else hiddenDrag.addClass("active"),nextDrag.offset(hiddenDrag.offset())}else hiddenDrag.addClass("active"),nextDrag.offset(hiddenDrag.offset())}else drop.data("isfocus",!0);e.preventDefault(),this.sendDragToDrop(nextDrag,drop)},DragDropOntoImageQuestion.prototype.getNextDrag=function(group,drag){var choice,numChoices=this.noOfChoicesInGroup(group);choice=0===drag.length?1:this.getChoice(drag)+1;for(var next=this.getUnplacedChoice(group,choice);0===next.length&&choice<numChoices;)choice++,next=this.getUnplacedChoice(group,choice);return next},DragDropOntoImageQuestion.prototype.getPreviousDrag=function(group,drag){var choice;choice=0===drag.length?this.noOfChoicesInGroup(group):this.getChoice(drag)-1;for(var previous=this.getUnplacedChoice(group,choice);0===previous.length&&choice>1;)choice--,previous=this.getUnplacedChoice(group,choice);return previous},DragDropOntoImageQuestion.prototype.animateTo=function(drag,target){var currentPos=drag.offset(),targetPos=target.offset(),thisQ=this;M.util.js_pending("qtype_ddimageortext-animate-"+thisQ.containerId),drag.animate({left:parseInt(drag.css("left"))+targetPos.left-currentPos.left,top:parseInt(drag.css("top"))+targetPos.top-currentPos.top},{duration:"fast",done:function(){$("body").trigger("qtype_ddimageortext-dragmoved",[drag,target,thisQ]),M.util.js_complete("qtype_ddimageortext-animate-"+thisQ.containerId)}})},DragDropOntoImageQuestion.prototype.isPointInDrop=function(pageX,pageY,drop){var position=drop.offset();return drop.hasClass("draghome")?pageX>=position.left&&pageX<position.left+drop.outerWidth()&&pageY>=position.top&&pageY<position.top+drop.outerHeight():pageX>=position.left&&pageX<position.left+drop.width()&&pageY>=position.top&&pageY<position.top+drop.height()},DragDropOntoImageQuestion.prototype.setInputValue=function(place,choice){this.getRoot().find("input.placeinput.place"+place).val(choice)},DragDropOntoImageQuestion.prototype.getRoot=function(){return $(document.getElementById(this.containerId))},DragDropOntoImageQuestion.prototype.bgImage=function(){return this.getRoot().find("img.dropbackground")},DragDropOntoImageQuestion.prototype.getDragHome=function(group,choice){return this.getRoot().find(".draghome.dragplaceholder.group"+group+".choice"+choice).is(":visible")?this.getRoot().find(".draghome.dragplaceholder.group"+group+".choice"+choice):this.getRoot().find(".dragitemgroup"+group+" .draghome.infinite.choice"+choice+".group"+group)},DragDropOntoImageQuestion.prototype.getUnplacedChoice=function(group,choice){return this.getRoot().find(".ddarea .draghome.group"+group+".choice"+choice+".unplaced").slice(0,1)},DragDropOntoImageQuestion.prototype.getCurrentDragInPlace=function(place){return this.getRoot().find(".ddarea .draghome.inplace"+place)},DragDropOntoImageQuestion.prototype.noOfDropsInGroup=function(group){return this.getRoot().find(".dropzone.group"+group).length},DragDropOntoImageQuestion.prototype.noOfChoicesInGroup=function(group){return this.getRoot().find(".dragitemgroup"+group+" .draghome").length},DragDropOntoImageQuestion.prototype.getClassnameNumericSuffix=function(node,prefix){var classes=node.attr("class");if(""!==classes)for(var classesArr=classes.split(" "),index=0;index<classesArr.length;index++){if(new RegExp("^"+prefix+"([0-9])+$").test(classesArr[index])){var match=new RegExp("([0-9])+$").exec(classesArr[index]);return Number(match[0])}}return null},DragDropOntoImageQuestion.prototype.getChoice=function(drag){return this.getClassnameNumericSuffix(drag,"choice")},DragDropOntoImageQuestion.prototype.getGroup=function(node){return this.getClassnameNumericSuffix(node,"group")},DragDropOntoImageQuestion.prototype.getPlace=function(node){return this.getClassnameNumericSuffix(node,"place")},DragDropOntoImageQuestion.prototype.getDragClone=function(drag){return this.getRoot().find(".dragitemgroup"+this.getGroup(drag)+" .draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".dragplaceholder")},DragDropOntoImageQuestion.prototype.getInfiniteDragClones=function(drag,inHome){return inHome?this.getRoot().find(".dragitemgroup"+this.getGroup(drag)+" .draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".infinite").not(".dragplaceholder"):this.getRoot().find(".draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".infinite").not(".dragplaceholder")},DragDropOntoImageQuestion.prototype.getDrop=function(drag,currentPlace){return this.getRoot().find(".dropzone.group"+this.getGroup(drag)+".place"+currentPlace)},DragDropOntoImageQuestion.prototype.handleResize=function(){var thisQ=this,bgRatio=this.bgRatio();this.isPrinting&&(bgRatio=1),this.getRoot().find(".ddarea .dropzone").each((function(i,dropNode){$(dropNode).css("left",parseInt($(dropNode).data("originX"))*parseFloat(bgRatio)).css("top",parseInt($(dropNode).data("originY"))*parseFloat(bgRatio)),thisQ.handleElementScale(dropNode,"left top")})),this.getRoot().find("div.droparea .draghome").not(".beingdragged").each((function(key,drag){$(drag).css("left",parseFloat($(drag).data("originX"))*parseFloat(bgRatio)).css("top",parseFloat($(drag).data("originY"))*parseFloat(bgRatio)),thisQ.handleElementScale(drag,"left top")}))},DragDropOntoImageQuestion.prototype.bgRatio=function(){var bgImg=this.bgImage(),bgImgNaturalWidth=bgImg.get(0).naturalWidth;return bgImg.width()/bgImgNaturalWidth},DragDropOntoImageQuestion.prototype.handleElementScale=function(element,type){var bgRatio=parseFloat(this.bgRatio());this.isPrinting&&(bgRatio=1),$(element).css({"-webkit-transform":"scale("+bgRatio+")","-moz-transform":"scale("+bgRatio+")","-ms-transform":"scale("+bgRatio+")","-o-transform":"scale("+bgRatio+")",transform:"scale("+bgRatio+")","transform-origin":type})},DragDropOntoImageQuestion.prototype.calculateZIndex=function(){var zIndex=0;return this.getRoot().find(".ddarea .dropzone, div.droparea .draghome").each((function(i,dropNode){var itemZIndex=(dropNode=$(dropNode)).css("z-index")?parseInt(dropNode.css("z-index")):0;itemZIndex>zIndex&&(zIndex=itemZIndex)})),zIndex},DragDropOntoImageQuestion.prototype.isDragSameAsDrop=function(drag,drop){return this.getChoice(drag)===this.getChoice(drop)&&this.getGroup(drag)===this.getGroup(drop)};var questionManager={eventHandlersInitialised:!1,dragEventHandlersInitialised:{},isPrinting:!1,isKeyboardNavigation:!1,questions:{},init:function(containerId,readOnly,places){if(questionManager.questions[containerId]=new DragDropOntoImageQuestion(containerId,readOnly,places),questionManager.eventHandlersInitialised||(questionManager.setupEventHandlers(),questionManager.eventHandlersInitialised=!0),!questionManager.dragEventHandlersInitialised.hasOwnProperty(containerId)){questionManager.dragEventHandlersInitialised[containerId]=!0;var questionContainer=document.getElementById(containerId);questionContainer.classList.contains("ddimageortext")&&!questionContainer.classList.contains("qtype_ddimageortext-readonly")&&questionManager.addEventHandlersToDrag($(questionContainer).find(".draghome"))}},setupEventHandlers:function(){$("body").on("keydown",".que.ddimageortext:not(.qtype_ddimageortext-readonly) .dropzones .dropzone",questionManager.handleKeyPress).on("keydown",".que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome.placed:not(.beingdragged)",questionManager.handleKeyPress).on("qtype_ddimageortext-dragmoved",questionManager.handleDragMoved),$(window).on("resize",(function(){questionManager.handleWindowResize(!1)})),window.addEventListener("beforeprint",(function(){questionManager.isPrinting=!0,questionManager.handleWindowResize(questionManager.isPrinting)})),window.addEventListener("afterprint",(function(){questionManager.isPrinting=!1,questionManager.handleWindowResize(questionManager.isPrinting)})),setTimeout((function(){questionManager.fixLayoutIfThingsMoved()}),100)},addEventHandlersToDrag:function(element){element.unbind("mousedown touchstart"),element.on("mousedown touchstart",questionManager.handleDragStart)},handleDragStart:function(e){e.preventDefault();var question=questionManager.getQuestionForEvent(e);question&&question.handleDragStart(e)},handleKeyPress:function(e){if(!questionManager.isKeyboardNavigation){questionManager.isKeyboardNavigation=!0;var question=questionManager.getQuestionForEvent(e);question&&question.handleKeyPress(e)}},handleWindowResize:function(isPrinting){for(var containerId in questionManager.questions)questionManager.questions.hasOwnProperty(containerId)&&(questionManager.questions[containerId].isPrinting=isPrinting,questionManager.questions[containerId].handleResize())},fixLayoutIfThingsMoved:function(){this.handleWindowResize(questionManager.isPrinting),setTimeout((function(){questionManager.fixLayoutIfThingsMoved(questionManager.isPrinting)}),100)},handleDragMoved:function(e,drag,target,thisQ){drag.removeClass("beingdragged").css("z-index",""),drag.css("top",target.position().top).css("left",target.position().left),target.after(drag),target.removeClass("active"),void 0!==drag.data("unplaced")&&!0===drag.data("unplaced")?(drag.removeClass("placed").addClass("unplaced"),drag.removeAttr("tabindex"),drag.removeData("unplaced"),drag.css("top","").css("left","").css("transform",""),drag.hasClass("infinite")&&thisQ.getInfiniteDragClones(drag,!0).length>1&&thisQ.getInfiniteDragClones(drag,!0).first().remove()):(drag.data("originX",target.data("originX")).data("originY",target.data("originY")),thisQ.handleElementScale(drag,"left top")),void 0!==drag.data("isfocus")&&!0===drag.data("isfocus")&&(drag.focus(),drag.removeData("isfocus")),void 0!==target.data("isfocus")&&!0===target.data("isfocus")&&target.removeData("isfocus"),questionManager.isKeyboardNavigation&&(questionManager.isKeyboardNavigation=!1),thisQ.isQuestionInteracted()&&(questionManager.handleFormDirty(),thisQ.questionAnswer=thisQ.getQuestionAnsweredValues())},getQuestionForEvent:function(e){var containerId=$(e.currentTarget).closest(".que.ddimageortext").attr("id");return questionManager.questions[containerId]},handleFormDirty:function(){const responseForm=document.getElementById("responseform");FormChangeChecker.markFormAsDirty(responseForm)}};return{init:questionManager.init}})); /** * This class provides the enhancements to the drag-drop marker editing form. * * @module qtype_ddmarker/form * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ddmarker/form",["jquery","core/dragdrop","qtype_ddmarker/shapes"],(function($,dragDrop,Shapes){function DropZoneManager(dropzoneNo){this.dropzoneNo=dropzoneNo,this.svgEl=null,this.shape=Shapes.make(this.getShapeType(),this.getLabel()),this.updateCoordinatesFromForm()}DropZoneManager.prototype.updateCoordinatesFromForm=function(svg){var coordinates=this.getCoordinates(),currentNumPoints="polygon"===this.shape.getType()&&this.shape.points.length;if(this.shape.getCoordinates()!==coordinates&&this.shape.parse(coordinates,1)){if("polygon"===this.shape.getType()&¤tNumPoints!==this.shape.points.length){var currentyActive=this.isActive();this.removeFromSvg(),svg&&(this.addToSvg(svg),currentyActive&&this.setActive())}else this.updateSvgEl();this.setCoordinatesInForm()}},DropZoneManager.prototype.updateLabel=function(){var label=this.getLabel();this.shape.label!==label&&(this.shape.label=label,this.updateSvgEl())},DropZoneManager.prototype.changeShape=function(svg){var newShapeType=this.getShapeType(),currentyActive=this.isActive();newShapeType!==this.shape.getType()&&(this.removeFromSvg(),this.shape=Shapes.getSimilar(newShapeType,this.shape),svg&&(this.addToSvg(svg),currentyActive&&this.setActive()),this.setCoordinatesInForm())},DropZoneManager.prototype.addToSvg=function(svg){if(null!==this.svgEl)throw new Error("this.svgEl already set");if(this.svgEl=this.shape.makeSvg(svg),this.svgEl){this.svgEl.setAttribute("class","dropzone"),this.svgEl.setAttribute("data-dropzone-no",this.dropzoneNo);var handles=this.shape.getHandlePositions();if(null!==handles){var moveHandle=Shapes.createSvgElement(this.svgEl,"circle");moveHandle.setAttribute("cx",handles.moveHandle.x),moveHandle.setAttribute("cy",handles.moveHandle.y),moveHandle.setAttribute("r",7),moveHandle.setAttribute("class","handle move");for(var i=0;i<handles.editHandles.length;++i)this.makeEditHandle(i,handles.editHandles[i])}}},DropZoneManager.prototype.makeEditHandle=function(index,point){var editHandle=Shapes.createSvgElement(this.svgEl,"rect");editHandle.setAttribute("x",point.x-6),editHandle.setAttribute("y",point.y-6),editHandle.setAttribute("width",11),editHandle.setAttribute("height",11),editHandle.setAttribute("class","handle edit"),editHandle.setAttribute("data-edit-handle-no",index)},DropZoneManager.prototype.removeFromSvg=function(){null!==this.svgEl&&(this.svgEl.parentNode.removeChild(this.svgEl),this.svgEl=null)},DropZoneManager.prototype.updateSvgEl=function(){if(null!==this.svgEl){this.shape.updateSvg(this.svgEl);var handles=this.shape.getHandlePositions();if(null!==handles){this.svgEl.childNodes[2].setAttribute("cx",handles.moveHandle.x),this.svgEl.childNodes[2].setAttribute("cy",handles.moveHandle.y);for(var i=0;i<handles.editHandles.length;++i)this.svgEl.childNodes[3+i].setAttribute("x",handles.editHandles[i].x-6),this.svgEl.childNodes[3+i].setAttribute("y",handles.editHandles[i].y-6)}}},DropZoneManager.prototype.isActive=function(){return null!==this.svgEl&&this.svgEl.getAttribute("class").match(/\bactive\b/)},DropZoneManager.prototype.setActive=function(){var parent=this.svgEl.parentNode;parent.removeChild(this.svgEl),parent.appendChild(this.svgEl),this.svgEl.setAttribute("class",this.svgEl.getAttribute("class")+" active")},DropZoneManager.prototype.setCoordinatesInForm=function(){dragDropForm.form.setFormValue("drops",[this.dropzoneNo,"coords"],this.shape.getCoordinates())},DropZoneManager.prototype.getCoordinates=function(){return dragDropForm.form.getFormValue("drops",[this.dropzoneNo,"coords"]).replace(/\s*/g,"")},DropZoneManager.prototype.getChoiceNo=function(){return dragDropForm.form.getFormValue("drops",[this.dropzoneNo,"choice"])},DropZoneManager.prototype.getLabel=function(){return dragDropForm.form.getMarkerText(this.getChoiceNo())},DropZoneManager.prototype.getShapeType=function(){return dragDropForm.form.getFormValue("drops",[this.dropzoneNo,"shape"])},DropZoneManager.prototype.handleMove=function(e){var info=dragDrop.prepare(e);if(info.start){var movingDropZone=this,lastX=info.x,lastY=info.y,dragProxy=this.makeDragProxy(info.x,info.y),bgImg=$("fieldset#id_previewareaheader .dropbackground"),maxX=bgImg.width(),maxY=bgImg.height();dragDrop.start(e,$(dragProxy),(function(pageX,pageY){movingDropZone.shape.move(pageX-lastX,pageY-lastY,maxX,maxY),lastX=pageX,lastY=pageY,movingDropZone.updateSvgEl(),movingDropZone.setCoordinatesInForm()}),(function(){document.body.removeChild(dragProxy)}))}},DropZoneManager.prototype.handleEdit=function(e,handleIndex,svg){var info=dragDrop.prepare(e);if(info.start){"polygon"===this.shape.getType()&&(e.ctrlKey||e.metaKey)&&(this.shape.addNewPointAfter(handleIndex),this.removeFromSvg(),this.addToSvg(svg),this.setActive());var changingDropZone=this,lastX=info.x,lastY=info.y,dragProxy=this.makeDragProxy(info.x,info.y),bgImg=$("fieldset#id_previewareaheader .dropbackground"),maxX=bgImg.width(),maxY=bgImg.height();dragDrop.start(e,$(dragProxy),(function(pageX,pageY){changingDropZone.shape.edit(handleIndex,pageX-lastX,pageY-lastY,maxX,maxY),lastX=pageX,lastY=pageY,changingDropZone.updateSvgEl(),changingDropZone.setCoordinatesInForm()}),(function(){document.body.removeChild(dragProxy),changingDropZone.shape.normalizeShape(),changingDropZone.updateSvgEl(),changingDropZone.setCoordinatesInForm()}))}},DropZoneManager.prototype.makeDragProxy=function(x,y){var dragProxy=document.createElement("div");return dragProxy.style.position="absolute",dragProxy.style.top=y+"px",dragProxy.style.left=x+"px",dragProxy.style.width="1px",dragProxy.style.height="1px",document.body.appendChild(dragProxy),dragProxy};var dragDropForm={fp:null,noDropZones:null,dropZones:[],init:function(){dragDropForm.fp=dragDropForm.filePickers(),dragDropForm.noDropZones=dragDropForm.form.getFormValue("nodropzone",[]),dragDropForm.setOptionsForDragItemSelectors(),dragDropForm.createShapes(),dragDropForm.setupEventHandlers(),dragDropForm.waitForFilePickerToInitialise()},setupPreviewArea:function(){$("fieldset#id_previewareaheader div.fcontainer").append('<div class="ddarea que ddmarker"> <div id="ddm-droparea" class="droparea"> <img class="dropbackground" /> <div id="ddm-dropzone" class="dropzones"> </div> </div></div>')},setOptionsForDragItemSelectors:function(){var selector,i,label,dragItemsOptions={0:""},noItems=dragDropForm.form.getFormValue("noitems",[]),selectedValues=[];for(i=1;i<=noItems;i++)""!==(label=dragDropForm.form.getMarkerText(i))&&(dragItemsOptions[i]=$("<div/>").text(label).html());for(i=0;i<dragDropForm.noDropZones;i++)selector=$("#id_drops_"+i+"_choice"),selectedValues[i]=Number(selector.val());for(i=0;i<dragDropForm.noDropZones;i++){for(var value in(selector=$("#id_drops_"+i+"_choice")).find("option").remove(),dragItemsOptions){var option='<option value="'+(value=Number(value))+'">'+dragItemsOptions[value]+"</option>";selector.append(option);var optionnode=selector.find('option[value="'+value+'"]');if(0!==value)if(value!==selectedValues[i]){var noofdrags=dragDropForm.form.getFormValue("drags",[value-1,"noofdrags"]);if(0!==Number(noofdrags))for(var k in selectedValues)if(Number(selectedValues[k])===value){if(1===Number(noofdrags)){optionnode.attr("disabled",!0);break}noofdrags--}}else optionnode.attr("selected",!0)}dragDropForm.dropZones.length>0&&dragDropForm.dropZones[i].updateLabel()}},createShapes:function(){for(var dropzoneNo=0;dropzoneNo<dragDropForm.noDropZones;dropzoneNo++)dragDropForm.dropZones[dropzoneNo]=new DropZoneManager(dropzoneNo)},setupEventHandlers:function(){$("fieldset#id_draggableitemheader").on("change input","input, select",(function(){dragDropForm.setOptionsForDragItemSelectors()})),$("fieldset#id_dropzoneheader").on("change input","input, select",(function(e){var ids=e.currentTarget.name.match(/^drops\[(\d+)]\[([a-z]*)]$/);if(ids){var dropzoneNo=ids[1],inputType=ids[2],dropZone=dragDropForm.dropZones[dropzoneNo];switch(inputType){case"shape":dropZone.changeShape(dragDropForm.form.getSvg());break;case"coords":dropZone.updateCoordinatesFromForm(dragDropForm.form.getSvg());break;case"choice":dropZone.updateLabel()}}}));var previewArea=$("fieldset#id_previewareaheader");previewArea.on("click","g.dropzone",(function(e){var dropzoneNo=$(e.currentTarget).data("dropzone-no"),currentlyActive=dragDropForm.dropZones[dropzoneNo].isActive();$(dragDropForm.form.getSvg()).find(".dropzone.active").removeClass("active"),currentlyActive||dragDropForm.dropZones[dropzoneNo].setActive()})),previewArea.on("mousedown touchstart",".dropzone .handle.move",(function(e){var dropzoneNo=$(e.currentTarget).closest("g").data("dropzoneNo");dragDropForm.dropZones[dropzoneNo].handleMove(e)})),previewArea.on("mousedown touchstart",".dropzone .handle.edit",(function(e){var dropzoneNo=$(e.currentTarget).closest("g").data("dropzoneNo"),handleIndex=e.currentTarget.getAttribute("data-edit-handle-no");dragDropForm.dropZones[dropzoneNo].handleEdit(e,handleIndex,dragDropForm.form.getSvg())}))},waitForFilePickerToInitialise:function(){null!==dragDropForm.fp.file("bgimage").href?($('form.mform[data-qtype="ddmarker"]').on("change","#id_bgimage",dragDropForm.loadPreviewImage),$("#ddm-droparea").length||dragDropForm.setupPreviewArea(),dragDropForm.loadPreviewImage()):setTimeout(dragDropForm.waitForFilePickerToInitialise,1e3)},loadPreviewImage:function(){$("fieldset#id_previewareaheader .dropbackground").one("load",dragDropForm.afterPreviewImageLoaded).attr("src",dragDropForm.fp.file("bgimage").href)},afterPreviewImageLoaded:function(){var bgImg=$("fieldset#id_previewareaheader .dropbackground");$("#ddm-dropzone").css("position","relative").css("top",-1*(bgImg.height()+1)),$("#ddm-droparea").css("height",bgImg.height()+20),dragDropForm.updateSvgDisplay()},updateSvgDisplay:function(){var dropzoneNo,bgImg=$("fieldset#id_previewareaheader .dropbackground");if(dragDropForm.form.getSvg())for(dropzoneNo=0;dropzoneNo<dragDropForm.noDropZones;dropzoneNo++)dragDropForm.dropZones[dropzoneNo].updateSvgEl();else for($("#ddm-dropzone").html('<svg xmlns="http://www.w3.org/2000/svg" class="dropzones" width="'+bgImg.outerWidth()+'" height="'+bgImg.outerHeight()+'"></svg>'),dropzoneNo=0;dropzoneNo<dragDropForm.noDropZones;dropzoneNo++)dragDropForm.dropZones[dropzoneNo].addToSvg(dragDropForm.form.getSvg())},form:{getMarkerText:function(markerNo){return 0!==Number(markerNo)?dragDropForm.form.getFormValue("drags",[markerNo-1,"label"]).replace(new RegExp("^\\s*(.*)\\s*$"),"$1"):""},getSvg:function(){var svg=$("fieldset#id_previewareaheader svg");return 0===svg.length?null:svg[0]},toNameWithIndex:function(name,indexes){for(var indexString=name,i=0;i<indexes.length;i++)indexString=indexString+"["+indexes[i]+"]";return indexString},getEl:function(name,indexes){return $('form.mform[data-qtype="ddmarker"]')[0].elements[this.toNameWithIndex(name,indexes)]},getFormValue:function(name,indexes){var el=this.getEl(name,indexes);return"checkbox"===el.type?el.checked:el.value},setFormValue:function(name,indexes,value){var el=this.getEl(name,indexes);"checkbox"===el.type?el.checked=value:el.value=value}},filePickers:function(){var draftItemIdsToName,nameToParentNode;return void 0===draftItemIdsToName&&(draftItemIdsToName={},nameToParentNode={},$("form.mform input.filepickerhidden").each((function(key,filepicker){draftItemIdsToName[filepicker.value]=filepicker.name,nameToParentNode[filepicker.name]=filepicker.parentNode}))),{file:function(name){var fileAnchor=$(nameToParentNode[name]).find("div.filepicker-filelist a");return fileAnchor.length?{href:fileAnchor.get(0).href,name:fileAnchor.get(0).innerHTML}:{href:null,name:null}},name:function(draftitemid){return draftItemIdsToName[draftitemid]}}}};return{init:dragDropForm.init}})); /** * Question class for drag and drop marker question type, used to support the question and preview pages. * * @module qtype_ddmarker/question * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ddmarker/question",["jquery","core/dragdrop","qtype_ddmarker/shapes","core/key_codes","core_form/changechecker"],(function($,dragDrop,Shapes,keys,FormChangeChecker){function DragDropMarkersQuestion(containerId,readOnly,visibleDropZones){var thisQ=this;this.containerId=containerId,this.visibleDropZones=visibleDropZones,this.shapes=[],this.shapeSVGs=[],this.isPrinting=!1,this.questionAnswer={},readOnly&&this.getRoot().addClass("qtype_ddmarker-readonly"),thisQ.allImagesLoaded=!1,thisQ.getNotYetLoadedImages().one("load",(function(){thisQ.waitForAllImagesToBeLoaded()})),thisQ.waitForAllImagesToBeLoaded()}DragDropMarkersQuestion.prototype.drawDropzones=function(){if(this.visibleDropZones.length>0){var bgImage=this.bgImage();this.getRoot().find("div.dropzones").html('<svg xmlns="http://www.w3.org/2000/svg" class="dropzones" width="'+bgImage.outerWidth()+'" height="'+bgImage.outerHeight()+'"></svg>');for(var svg=this.getRoot().find("svg.dropzones"),nextColourIndex=0,dropZoneNo=0;dropZoneNo<this.visibleDropZones.length;dropZoneNo++){var colourClass="color"+nextColourIndex;nextColourIndex=(nextColourIndex+1)%8,this.addDropzone(svg,dropZoneNo,colourClass)}}},DragDropMarkersQuestion.prototype.addDropzone=function(svg,dropZoneNo,colourClass){var existingmarkertext,dropZone=this.visibleDropZones[dropZoneNo],shape=Shapes.make(dropZone.shape,""),bgRatio=this.bgRatio();if(shape.parse(dropZone.coords,bgRatio)){if((existingmarkertext=this.getRoot().find("div.markertexts span.markertext"+dropZoneNo)).length)""!==dropZone.markertext?existingmarkertext.html(dropZone.markertext):existingmarkertext.remove();else if(""!==dropZone.markertext){var classnames="markertext markertext"+dropZoneNo;this.getRoot().find("div.markertexts").append('<span class="'+classnames+'">'+dropZone.markertext+"</span>");var markerspan=this.getRoot().find("div.ddarea div.markertexts span.markertext"+dropZoneNo);if(markerspan.length){var handles=shape.getHandlePositions(),positionLeft=handles.moveHandle.x-markerspan.outerWidth()/2-4,positionTop=handles.moveHandle.y-markerspan.outerHeight()/2;markerspan.css("left",positionLeft).css("top",positionTop),markerspan.data("originX",markerspan.position().left/bgRatio).data("originY",markerspan.position().top/bgRatio),this.handleElementScale(markerspan,"center")}}var shapeSVG=shape.makeSvg(svg[0]);shapeSVG.setAttribute("class","dropzone "+colourClass),this.shapes[this.shapes.length]=shape,this.shapeSVGs[this.shapeSVGs.length]=shapeSVG}},DragDropMarkersQuestion.prototype.repositionDrags=function(){var root=this.getRoot(),thisQ=this;root.find("div.draghomes .marker").not(".dragplaceholder").each((function(key,item){$(item).addClass("unneeded")})),root.find("input.choices").each((function(key,input){var choiceNo=thisQ.getChoiceNoFromElement(input),imageCoords=thisQ.getImageCoords(input);if(imageCoords.length){var drag=thisQ.getRoot().find(".draghomes span.marker.choice"+choiceNo).not(".dragplaceholder");drag.remove();for(var i=0;i<imageCoords.length;i++){var dragInDrop=drag.clone();const screenCoords=thisQ.convertToWindowXY(imageCoords[i]);dragInDrop.data("pagex",screenCoords.x).data("pagey",screenCoords.y),dragInDrop.data("imageCoords",imageCoords[i]),dragInDrop.data("scaleRatio",1),thisQ.sendDragToDrop(dragInDrop,!1,!0)}thisQ.getDragClone(drag).addClass("active"),thisQ.cloneDragIfNeeded(drag)}})),thisQ.questionAnswer=thisQ.getQuestionAnsweredValues()},DragDropMarkersQuestion.prototype.getQuestionAnsweredValues=function(){let result={};return this.getRoot().find("input.choices").each(((i,inputNode)=>{result[inputNode.id]=inputNode.value})),result},DragDropMarkersQuestion.prototype.isQuestionInteracted=function(){const oldAnswer=this.questionAnswer,newAnswer=this.getQuestionAnsweredValues();let isInteracted=!1;return JSON.stringify(newAnswer)!==JSON.stringify(oldAnswer)?(isInteracted=!0,isInteracted):(Object.keys(newAnswer).forEach((key=>{newAnswer[key]!==oldAnswer[key]&&(isInteracted=!0)})),isInteracted)},DragDropMarkersQuestion.prototype.getImageCoords=function(inputNode){var imageCoords=[],val=$(inputNode).val();if(""!==val)for(var coordsStrings=val.split(";"),i=0;i<coordsStrings.length;i++)imageCoords[i]=Shapes.Point.parse(coordsStrings[i]);return imageCoords},DragDropMarkersQuestion.prototype.convertToWindowXY=function(point){var bgImage=this.bgImage();return point.offset(bgImage.offset().left+1,bgImage.offset().top+1)},DragDropMarkersQuestion.prototype.convertToBgImgXY=function(point){var bgImage=this.bgImage();return point.offset(-bgImage.offset().left-1,-bgImage.offset().top-1)},DragDropMarkersQuestion.prototype.coordsInBgImg=function(point){var bgImage=this.bgImage(),bgPosition=bgImage.offset();return point.x>=bgPosition.left&&point.x<bgPosition.left+bgImage.width()&&point.y>=bgPosition.top&&point.y<bgPosition.top+bgImage.height()},DragDropMarkersQuestion.prototype.getRoot=function(){return $(document.getElementById(this.containerId))},DragDropMarkersQuestion.prototype.bgImage=function(){return this.getRoot().find("img.dropbackground")},DragDropMarkersQuestion.prototype.handleDragStart=function(e){var thisQ=this,dragged=$(e.target).closest(".marker");if(dragDrop.prepare(e).start){if(dragged.addClass("beingdragged").css("transform",""),!!dragged.hasClass("unneeded")){var hiddenDrag=thisQ.getDragClone(dragged);hiddenDrag.length&&(hiddenDrag.addClass("active"),dragged.offset(hiddenDrag.offset()))}dragDrop.start(e,dragged,(function(){}),(function(x,y,dragged){thisQ.dragEnd(dragged)}))}},DragDropMarkersQuestion.prototype.dragEnd=function(dragged){var dragXY,placed=!1,choiceNo=this.getChoiceNoFromElement(dragged),bgRatio=this.bgRatio();if(dragged.data("pagex",dragged.offset().left).data("pagey",dragged.offset().top),dragXY=new Shapes.Point(dragged.data("pagex"),dragged.data("pagey")),this.coordsInBgImg(dragXY)){this.sendDragToDrop(dragged,!0),placed=!0,dragged.data("imageCoords")&&dragged.data("imageCoords",null);var bgImgXY=this.convertToBgImgXY(dragXY);bgImgXY=new Shapes.Point(bgImgXY.x/bgRatio,bgImgXY.y/bgRatio),dragged.data("originX",bgImgXY.x).data("originY",bgImgXY.y)}placed?this.cloneDragIfNeeded(dragged):(this.sendDragHome(dragged),this.removeDragIfNeeded(dragged)),this.saveCoordsForChoice(choiceNo)},DragDropMarkersQuestion.prototype.saveCoordsForChoice=function(choiceNo){let imageCoords=[];var items=this.getRoot().find("div.droparea span.marker.choice"+choiceNo),thiQ=this,bgRatio=this.bgRatio();items.length&&items.each((function(){var drag=$(this);if(drag.hasClass("beingdragged")||drag.data("imageCoords"))drag.data("imageCoords")&&(imageCoords[imageCoords.length]=drag.data("imageCoords"));else{drag.data("scaleRatio")!==bgRatio&&drag.data("pagex",drag.offset().left).data("pagey",drag.offset().top);var dragXY=new Shapes.Point(drag.data("pagex"),drag.data("pagey"));if(thiQ.coordsInBgImg(dragXY)){var bgImgXY=thiQ.convertToBgImgXY(dragXY);bgImgXY=new Shapes.Point(bgImgXY.x/bgRatio,bgImgXY.y/bgRatio),imageCoords[imageCoords.length]=bgImgXY}}})),this.getRoot().find("input.choice"+choiceNo).val(imageCoords.join(";")),this.isQuestionInteracted()&&(questionManager.handleFormDirty(),this.questionAnswer=this.getQuestionAnsweredValues())},DragDropMarkersQuestion.prototype.handleKeyPress=function(e){var drag=$(e.target).closest(".marker"),point=new Shapes.Point(drag.offset().left,drag.offset().top),choiceNo=this.getChoiceNoFromElement(drag);switch(e.keyCode){case keys.arrowLeft:case 65:point.x-=1;break;case keys.arrowRight:case 68:point.x+=1;break;case keys.arrowDown:case 83:point.y+=1;break;case keys.arrowUp:case 87:point.y-=1;break;case keys.space:case keys.escape:point=null;break;default:return}if(e.preventDefault(),null!==point){point=this.constrainToBgImg(point),drag.offset({left:point.x,top:point.y}),drag.data("pagex",drag.offset().left).data("pagey",drag.offset().top);var dragXY=this.convertToBgImgXY(new Shapes.Point(drag.data("pagex"),drag.data("pagey")));if(drag.data("originX",dragXY.x/this.bgRatio()).data("originY",dragXY.y/this.bgRatio()),this.coordsInBgImg(new Shapes.Point(drag.offset().left,drag.offset().top))&&drag.hasClass("unneeded")){this.sendDragToDrop(drag,!0);var hiddenDrag=this.getDragClone(drag);hiddenDrag.length&&hiddenDrag.addClass("active"),this.cloneDragIfNeeded(drag)}}else drag.css("left","").css("top",""),drag.data("pagex",drag.offset().left).data("pagey",drag.offset().top),this.sendDragHome(drag),this.removeDragIfNeeded(drag);drag.focus(),this.saveCoordsForChoice(choiceNo)},DragDropMarkersQuestion.prototype.constrainToBgImg=function(windowxy){var bgImg=this.bgImage(),bgImgXY=this.convertToBgImgXY(windowxy);return bgImgXY.x=Math.max(0,bgImgXY.x),bgImgXY.y=Math.max(0,bgImgXY.y),bgImgXY.x=Math.min(bgImg.width(),bgImgXY.x),bgImgXY.y=Math.min(bgImg.height(),bgImgXY.y),this.convertToWindowXY(bgImgXY)},DragDropMarkersQuestion.prototype.getChoiceNoFromElement=function(node){return Number(this.getClassnameNumericSuffix(node,"choice"))},DragDropMarkersQuestion.prototype.getClassnameNumericSuffix=function(node,prefix){var classes=$(node).attr("class");if(void 0!==classes&&""!==classes)for(var classesarr=classes.split(" "),index=0;index<classesarr.length;index++){if(new RegExp("^"+prefix+"([0-9])+$").test(classesarr[index])){var match=new RegExp("([0-9])+$").exec(classesarr[index]);return Number(match[0])}}return null},DragDropMarkersQuestion.prototype.handleResize=function(){var thisQ=this,bgRatio=this.bgRatio();this.isPrinting&&(bgRatio=1),this.getRoot().find("div.droparea .marker").not(".beingdragged").each((function(key,drag){$(drag).css("left",parseFloat($(drag).data("originX"))*parseFloat(bgRatio)).css("top",parseFloat($(drag).data("originY"))*parseFloat(bgRatio)),thisQ.handleElementScale(drag,"left top")})),this.getRoot().find("div.droparea svg.dropzones").width(this.bgImage().width()).height(this.bgImage().height());for(var dropZoneNo=0;dropZoneNo<this.visibleDropZones.length;dropZoneNo++){var originCoords=thisQ.visibleDropZones[dropZoneNo].coords,shape=thisQ.shapes[dropZoneNo],shapeSVG=thisQ.shapeSVGs[dropZoneNo];shape.parse(originCoords,bgRatio),shape.updateSvg(shapeSVG);var handles=shape.getHandlePositions(),markerSpan=this.getRoot().find("div.ddarea div.markertexts span.markertext"+dropZoneNo);markerSpan.css("left",handles.moveHandle.x-markerSpan.outerWidth()/2-4).css("top",handles.moveHandle.y-markerSpan.outerHeight()/2),thisQ.handleElementScale(markerSpan,"center")}},DragDropMarkersQuestion.prototype.cloneDrags=function(){var thisQ=this;this.getRoot().find("div.draghomes span.marker").each((function(index,draghome){var drag=$(draghome),placeHolder=drag.clone();placeHolder.removeClass(),placeHolder.addClass("marker"),placeHolder.addClass("choice"+thisQ.getChoiceNoFromElement(drag)),placeHolder.addClass(thisQ.getDragNoClass(drag,!1)),placeHolder.addClass("dragplaceholder"),drag.before(placeHolder)}))},DragDropMarkersQuestion.prototype.getDragNo=function(drag){return this.getClassnameNumericSuffix(drag,"dragno")},DragDropMarkersQuestion.prototype.getDragNoClass=function(drag,includeSelector){var className="dragno"+this.getDragNo(drag);return this.isInfiniteDrag(drag)&&(className="infinite"),includeSelector?"."+className:className},DragDropMarkersQuestion.prototype.getDragClone=function(drag){return this.getRoot().find(".draghomes span.marker.choice"+this.getChoiceNoFromElement(drag)+this.getDragNoClass(drag,!0)+".dragplaceholder")},DragDropMarkersQuestion.prototype.dropArea=function(){return this.getRoot().find("div.droparea")},DragDropMarkersQuestion.prototype.sendDragHome=function(drag){drag.removeClass("beingdragged").addClass("unneeded").css("top","").css("left","").css("transform","");var placeHolder=this.getDragClone(drag);placeHolder.after(drag),placeHolder.removeClass("active")},DragDropMarkersQuestion.prototype.sendDragToDrop=function(drag,isScaling){let initialLoad=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var dropArea=this.dropArea(),bgRatio=this.bgRatio();drag.removeClass("beingdragged").removeClass("unneeded");var dragXY=this.convertToBgImgXY(new Shapes.Point(drag.data("pagex"),drag.data("pagey")));isScaling?(drag.data("originX",dragXY.x/bgRatio).data("originY",dragXY.y/bgRatio),drag.css("left",dragXY.x).css("top",dragXY.y)):(drag.data("originX",dragXY.x).data("originY",dragXY.y),drag.css("left",dragXY.x*bgRatio).css("top",dragXY.y*bgRatio)),initialLoad||drag.data("scaleRatio",bgRatio),dropArea.append(drag),this.handleElementScale(drag,"left top")},DragDropMarkersQuestion.prototype.cloneDragIfNeeded=function(drag){var inputNode=this.getInput(drag),noOfDrags=Number(this.getClassnameNumericSuffix(inputNode,"noofdrags")),displayedDragsInDropArea=this.getRoot().find("div.droparea .marker.choice"+this.getChoiceNoFromElement(drag)+this.getDragNoClass(drag,!0)).length,displayedDragsInDragHomes=this.getRoot().find("div.draghomes .marker.choice"+this.getChoiceNoFromElement(drag)+this.getDragNoClass(drag,!0)).not(".dragplaceholder").length;if((this.isInfiniteDrag(drag)||!this.isInfiniteDrag(drag)&&displayedDragsInDropArea<noOfDrags)&&0===displayedDragsInDragHomes){var dragClone=drag.clone();dragClone.addClass("unneeded").css("top","").css("left","").css("transform",""),this.getDragClone(drag).removeClass("active").after(dragClone),questionManager.addEventHandlersToMarker(dragClone)}},DragDropMarkersQuestion.prototype.removeDragIfNeeded=function(drag){for(var dragsInHome=this.getRoot().find("div.draghomes .marker.choice"+this.getChoiceNoFromElement(drag)+this.getDragNoClass(drag,!0)).not(".dragplaceholder"),displayedDrags=dragsInHome.length;displayedDrags>1;)dragsInHome.first().remove(),displayedDrags--},DragDropMarkersQuestion.prototype.getInput=function(drag){var choiceNo=this.getChoiceNoFromElement(drag);return this.getRoot().find("input.choices.choice"+choiceNo)},DragDropMarkersQuestion.prototype.bgRatio=function(){var bgImg=this.bgImage(),bgImgNaturalWidth=bgImg.get(0).naturalWidth;return bgImg.width()/bgImgNaturalWidth},DragDropMarkersQuestion.prototype.handleElementScale=function(element,type){var bgRatio=parseFloat(this.bgRatio());this.isPrinting&&(bgRatio=1),$(element).css({"-webkit-transform":"scale("+bgRatio+")","-moz-transform":"scale("+bgRatio+")","-ms-transform":"scale("+bgRatio+")","-o-transform":"scale("+bgRatio+")",transform:"scale("+bgRatio+")","transform-origin":type})},DragDropMarkersQuestion.prototype.isInfiniteDrag=function(drag){return drag.hasClass("infinite")},DragDropMarkersQuestion.prototype.waitForAllImagesToBeLoaded=function(){this.allImagesLoaded||(null!==this.imageLoadingTimeoutId&&clearTimeout(this.imageLoadingTimeoutId),this.getNotYetLoadedImages().length>0?this.imageLoadingTimeoutId=setTimeout((function(){this.waitForAllImagesToBeLoaded()}),100):(this.allImagesLoaded=!0,this.cloneDrags(),this.repositionDrags(),this.drawDropzones()))},DragDropMarkersQuestion.prototype.getNotYetLoadedImages=function(){return this.getRoot().find(".ddmarker img.dropbackground").not((function(i,imgNode){return this.imageIsLoaded(imgNode)}))},DragDropMarkersQuestion.prototype.imageIsLoaded=function(imgElement){return imgElement.complete&&0!==imgElement.naturalHeight};var questionManager={eventHandlersInitialised:!1,markerEventHandlersInitialised:{},isPrinting:!1,isKeyboardNavigation:!1,questions:{},init:function(containerId,readOnly,visibleDropZones){if(questionManager.questions[containerId]=new DragDropMarkersQuestion(containerId,readOnly,visibleDropZones),questionManager.eventHandlersInitialised||(questionManager.setupEventHandlers(),questionManager.eventHandlersInitialised=!0),!questionManager.markerEventHandlersInitialised.hasOwnProperty(containerId)){questionManager.markerEventHandlersInitialised[containerId]=!0;var questionContainer=document.getElementById(containerId);questionContainer.classList.contains("ddmarker")&&!questionContainer.classList.contains("qtype_ddmarker-readonly")&&(questionManager.addEventHandlersToMarker($(questionContainer).find("div.draghomes .marker")),questionManager.addEventHandlersToMarker($(questionContainer).find("div.droparea .marker")))}},setupEventHandlers:function(){$(window).on("resize",(function(){questionManager.handleWindowResize(!1)})),window.addEventListener("beforeprint",(function(){questionManager.isPrinting=!0,questionManager.handleWindowResize(questionManager.isPrinting)})),window.addEventListener("afterprint",(function(){questionManager.isPrinting=!1,questionManager.handleWindowResize(questionManager.isPrinting)})),setTimeout((function(){questionManager.fixLayoutIfThingsMoved()}),100)},addEventHandlersToMarker:function(element){element.on("mousedown touchstart",questionManager.handleDragStart).on("keydown keypress",questionManager.handleKeyPress).focusin((function(e){questionManager.handleKeyboardFocus(e,!0)})).focusout((function(e){questionManager.handleKeyboardFocus(e,!1)}))},handleDragStart:function(e){e.preventDefault();var question=questionManager.getQuestionForEvent(e);question&&question.handleDragStart(e)},handleKeyPress:function(e){var question=questionManager.getQuestionForEvent(e);question&&question.handleKeyPress(e)},handleWindowResize:function(isPrinting){for(var containerId in questionManager.questions)questionManager.questions.hasOwnProperty(containerId)&&(questionManager.questions[containerId].isPrinting=isPrinting,questionManager.questions[containerId].handleResize())},handleKeyboardFocus:function(e,isNavigating){questionManager.isKeyboardNavigation=isNavigating},fixLayoutIfThingsMoved:function(){questionManager.isKeyboardNavigation||this.handleWindowResize(questionManager.isPrinting),setTimeout((function(){questionManager.fixLayoutIfThingsMoved(questionManager.isPrinting)}),100)},getQuestionForEvent:function(e){var containerId=$(e.currentTarget).closest(".que.ddmarker").attr("id");return questionManager.questions[containerId]},handleFormDirty:function(){const responseForm=document.getElementById("responseform");FormChangeChecker.markFormAsDirty(responseForm)}};return{init:questionManager.init}})); /** * Library of classes for handling simple shapes. * * These classes can represent shapes, let you alter them, can go to and from a string * representation, and can give you an SVG representation. * * @module qtype_ddmarker/shapes * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ddmarker/shapes",(function(){function Point(x,y){this.x=x,this.y=y}function Shape(label,x,y){this.label=label,this.centre=new Point(x||0,y||0)}function Circle(label,x,y,radius){x=x||15,y=y||15,Shape.call(this,label,x,y),this.radius=radius||15}function Rectangle(label,x,y,width,height){Shape.call(this,label,x,y),this.width=width||30,this.height=height||30}function Polygon(label,points){Shape.call(this,label,0,0),this.points=points?points.slice():[new Point(10,10),new Point(40,10),new Point(10,40)],this.normalizeShape(),this.ratio=1}function NullShape(label){Shape.call(this,label)}function createSvgElement(svg,tagName){var svgEl=svg.ownerDocument.createElementNS("http://www.w3.org/2000/svg",tagName);return svg.appendChild(svgEl),svgEl}function createSvgShapeGroup(svg,tagName){var svgEl=createSvgElement(svg,"g");return createSvgElement(svgEl,tagName).setAttribute("class","shape"),createSvgElement(svgEl,"text").setAttribute("class","shapeLabel"),svgEl}return Point.prototype.toString=function(){return this.x+","+this.y},Point.prototype.move=function(dx,dy){this.x+=dx,this.y+=dy},Point.prototype.offset=function(offsetX,offsetY){return offsetX instanceof Point&&(offsetY=offsetX.y,offsetX=offsetX.x),new Point(this.x+offsetX,this.y+offsetY)},Point.parse=function(coordinates){var bits=coordinates.split(",");if(2!==bits.length)throw new Error(coordinates+" is not a valid point");return new Point(Math.round(bits[0]),Math.round(bits[1]))},Shape.prototype.getType=function(){throw new Error("Not implemented.")},Shape.prototype.getCoordinates=function(){throw new Error("Not implemented.")},Shape.prototype.parse=function(coordinates,ratio){throw new Error("Not implemented.")},Shape.prototype.move=function(dx,dy,maxX,maxY){},Shape.prototype.edit=function(handleIndex,dx,dy,maxX,maxY){},Shape.prototype.normalizeShape=function(){},Shape.prototype.makeSvg=function(svg){throw new Error("Not implemented.")},Shape.prototype.updateSvg=function(svgEl){},Shape.prototype.makeSimilarCircle=function(){throw new Error("Not implemented.")},Shape.prototype.makeSimilarRectangle=function(){throw new Error("Not implemented.")},Shape.prototype.makeSimilarPolygon=function(){throw new Error("Not implemented.")},Shape.prototype.getHandlePositions=function(){return null},Circle.prototype=new Shape,Circle.prototype.getType=function(){return"circle"},Circle.prototype.getCoordinates=function(){return this.centre+";"+Math.abs(this.radius)},Circle.prototype.makeSvg=function(svg){var svgEl=createSvgShapeGroup(svg,"circle");return this.updateSvg(svgEl),svgEl},Circle.prototype.updateSvg=function(svgEl){svgEl.childNodes[0].setAttribute("cx",this.centre.x),svgEl.childNodes[0].setAttribute("cy",this.centre.y),svgEl.childNodes[0].setAttribute("r",Math.abs(this.radius)),svgEl.childNodes[1].setAttribute("x",this.centre.x),svgEl.childNodes[1].setAttribute("y",this.centre.y+15),svgEl.childNodes[1].textContent=this.label},Circle.prototype.parse=function(coordinates,ratio){if(!coordinates.match(/^\d+(\.\d+)?,\d+(\.\d+)?;\d+(\.\d+)?$/))return!1;var bits=coordinates.split(";");return this.centre=Point.parse(bits[0]),this.centre.x=this.centre.x*parseFloat(ratio),this.centre.y=this.centre.y*parseFloat(ratio),this.radius=Math.round(bits[1])*parseFloat(ratio),!0},Circle.prototype.move=function(dx,dy,maxX,maxY){this.centre.move(dx,dy),this.centre.x<this.radius&&(this.centre.x=this.radius),this.centre.x>maxX-this.radius&&(this.centre.x=maxX-this.radius),this.centre.y<this.radius&&(this.centre.y=this.radius),this.centre.y>maxY-this.radius&&(this.centre.y=maxY-this.radius)},Circle.prototype.edit=function(handleIndex,dx,dy,maxX,maxY){this.radius+=dx;var limit=Math.min(this.centre.x,this.centre.y,maxX-this.centre.x,maxY-this.centre.y);this.radius>limit&&(this.radius=limit),this.radius<-limit&&(this.radius=-limit)},Circle.prototype.normalizeShape=function(){this.radius=Math.abs(this.radius)},Circle.prototype.makeSimilarRectangle=function(){return new Rectangle(this.label,this.centre.x-this.radius,this.centre.y-this.radius,2*this.radius,2*this.radius)},Circle.prototype.makeSimilarPolygon=function(){return new Polygon(this.label,[this.centre.offset(-this.radius,-this.radius),this.centre.offset(-this.radius,this.radius),this.centre.offset(this.radius,this.radius),this.centre.offset(this.radius,-this.radius)])},Circle.prototype.getHandlePositions=function(){return{moveHandle:this.centre,editHandles:[this.centre.offset(this.radius,0)]}},Rectangle.prototype=new Shape,Rectangle.prototype.getType=function(){return"rectangle"},Rectangle.prototype.getCoordinates=function(){return this.centre+";"+this.width+","+this.height},Rectangle.prototype.makeSvg=function(svg){var svgEl=createSvgShapeGroup(svg,"rect");return this.updateSvg(svgEl),svgEl},Rectangle.prototype.updateSvg=function(svgEl){this.width>=0?(svgEl.childNodes[0].setAttribute("x",this.centre.x),svgEl.childNodes[0].setAttribute("width",this.width)):(svgEl.childNodes[0].setAttribute("x",this.centre.x+this.width),svgEl.childNodes[0].setAttribute("width",-this.width)),this.height>=0?(svgEl.childNodes[0].setAttribute("y",this.centre.y),svgEl.childNodes[0].setAttribute("height",this.height)):(svgEl.childNodes[0].setAttribute("y",this.centre.y+this.height),svgEl.childNodes[0].setAttribute("height",-this.height)),svgEl.childNodes[1].setAttribute("x",this.centre.x+this.width/2),svgEl.childNodes[1].setAttribute("y",this.centre.y+this.height/2+15),svgEl.childNodes[1].textContent=this.label},Rectangle.prototype.parse=function(coordinates,ratio){if(!coordinates.match(/^\d+(\.\d+)?,\d+(\.\d+)?;\d+(\.\d+)?,\d+(\.\d+)?$/))return!1;var bits=coordinates.split(";");this.centre=Point.parse(bits[0]),this.centre.x=this.centre.x*parseFloat(ratio),this.centre.y=this.centre.y*parseFloat(ratio);var size=Point.parse(bits[1]);return this.width=size.x*parseFloat(ratio),this.height=size.y*parseFloat(ratio),!0},Rectangle.prototype.move=function(dx,dy,maxX,maxY){this.centre.move(dx,dy),this.centre.x<0&&(this.centre.x=0),this.centre.x>maxX-this.width&&(this.centre.x=maxX-this.width),this.centre.y<0&&(this.centre.y=0),this.centre.y>maxY-this.height&&(this.centre.y=maxY-this.height)},Rectangle.prototype.edit=function(handleIndex,dx,dy,maxX,maxY){this.width+=dx,this.height+=dy,this.width<-this.centre.x&&(this.width=-this.centre.x),this.width>maxX-this.centre.x&&(this.width=maxX-this.centre.x),this.height<-this.centre.y&&(this.height=-this.centre.y),this.height>maxY-this.centre.y&&(this.height=maxY-this.centre.y)},Rectangle.prototype.normalizeShape=function(){this.width<0&&(this.centre.x+=this.width,this.width=-this.width),this.height<0&&(this.centre.y+=this.height,this.height=-this.height)},Rectangle.prototype.makeSimilarCircle=function(){return new Circle(this.label,Math.round(this.centre.x+this.width/2),Math.round(this.centre.y+this.height/2),Math.round((this.width+this.height)/4))},Rectangle.prototype.makeSimilarPolygon=function(){return new Polygon(this.label,[this.centre,this.centre.offset(0,this.height),this.centre.offset(this.width,this.height),this.centre.offset(this.width,0)])},Rectangle.prototype.getHandlePositions=function(){return{moveHandle:this.centre.offset(this.width/2,this.height/2),editHandles:[this.centre.offset(this.width,this.height)]}},Polygon.prototype=new Shape,Polygon.prototype.getType=function(){return"polygon"},Polygon.prototype.getCoordinates=function(){for(var coordinates="",i=0;i<this.points.length;i++)coordinates+=this.centre.offset(this.points[i])+";";return coordinates.slice(0,coordinates.length-1)},Polygon.prototype.makeSvg=function(svg){var svgEl=createSvgShapeGroup(svg,"polygon");return this.updateSvg(svgEl),svgEl},Polygon.prototype.updateSvg=function(svgEl){svgEl.childNodes[0].setAttribute("points",this.getCoordinates().replace(/[,;]/g," ")),svgEl.childNodes[0].setAttribute("transform","scale("+parseFloat(this.ratio)+")"),svgEl.childNodes[1].setAttribute("x",this.centre.x),svgEl.childNodes[1].setAttribute("y",this.centre.y+15),svgEl.childNodes[1].textContent=this.label},Polygon.prototype.parse=function(coordinates,ratio){if(!coordinates.match(/^\d+(\.\d+)?,\d+(\.\d+)?(?:;\d+(\.\d+)?,\d+(\.\d+)?)*$/))return!1;for(var bits=coordinates.split(";"),points=[],i=0;i<bits.length;i++)points.push(Point.parse(bits[i]));return this.points=points,this.centre.x=0,this.centre.y=0,this.ratio=ratio,this.normalizeShape(),!0},Polygon.prototype.move=function(dx,dy,maxX,maxY){this.centre.move(dx,dy);for(var bbXMin=maxX,bbXMax=0,bbYMin=maxY,bbYMax=0,i=0;i<this.points.length;i++)bbXMin=Math.min(bbXMin,this.points[i].x),bbXMax=Math.max(bbXMax,this.points[i].x),bbYMin=Math.min(bbYMin,this.points[i].y),bbYMax=Math.max(bbYMax,this.points[i].y);this.centre.x<-bbXMin&&(this.centre.x=-bbXMin),this.centre.x>maxX-bbXMax&&(this.centre.x=maxX-bbXMax),this.centre.y<-bbYMin&&(this.centre.y=-bbYMin),this.centre.y>maxY-bbYMax&&(this.centre.y=maxY-bbYMax)},Polygon.prototype.edit=function(handleIndex,dx,dy,maxX,maxY){this.points[handleIndex].move(dx,dy),this.points[handleIndex].x<-this.centre.x&&(this.points[handleIndex].x=-this.centre.x),this.points[handleIndex].x>maxX-this.centre.x&&(this.points[handleIndex].x=maxX-this.centre.x),this.points[handleIndex].y<-this.centre.y&&(this.points[handleIndex].y=-this.centre.y),this.points[handleIndex].y>maxY-this.centre.y&&(this.points[handleIndex].y=maxY-this.centre.y)},Polygon.prototype.addNewPointAfter=function(pointIndex){this.points.splice(pointIndex,0,new Point(this.points[pointIndex].x,this.points[pointIndex].y))},Polygon.prototype.normalizeShape=function(){var i,x=0,y=0;if(0!==this.points.length){for(i=0;i<this.points.length;i++)x+=this.points[i].x,y+=this.points[i].y;if(x=Math.round(x/this.points.length),y=Math.round(y/this.points.length),0!==x||0!==y){for(i=0;i<this.points.length;i++)this.points[i].move(-x,-y);this.centre.move(x,y)}}},Polygon.prototype.makeSimilarCircle=function(){return this.makeSimilarRectangle().makeSimilarCircle()},Polygon.prototype.makeSimilarRectangle=function(){for(var p,minX=0,maxX=0,minY=0,maxY=0,i=0;i<this.points.length;i++)p=this.points[i],minX=Math.min(minX,p.x),maxX=Math.max(maxX,p.x),minY=Math.min(minY,p.y),maxY=Math.max(maxY,p.y);return new Rectangle(this.label,this.centre.x+minX,this.centre.y+minY,Math.max(maxX-minX,10),Math.max(maxY-minY,10))},Polygon.prototype.getHandlePositions=function(){for(var editHandles=[],i=0;i<this.points.length;i++)editHandles.push(this.points[i].offset(this.centre.x,this.centre.y));return this.centre.x=this.centre.x*parseFloat(this.ratio),this.centre.y=this.centre.y*parseFloat(this.ratio),{moveHandle:this.centre,editHandles:editHandles}},NullShape.prototype=new Shape,NullShape.prototype.getType=function(){return"null"},NullShape.prototype.getCoordinates=function(){return""},NullShape.prototype.makeSvg=function(svg){return null},NullShape.prototype.updateSvg=function(svgEl){},NullShape.prototype.parse=function(coordinates){return!1},NullShape.prototype.makeSimilarCircle=function(){return new Circle(this.label)},NullShape.prototype.makeSimilarRectangle=function(){return new Rectangle(this.label)},NullShape.prototype.makeSimilarPolygon=function(){return new Polygon(this.label)},{Point:Point,Shape:Shape,Circle:Circle,Rectangle:Rectangle,Polygon:Polygon,NullShape:NullShape,createSvgElement:createSvgElement,make:function(shapeType,label){switch(shapeType){case"circle":return new Circle(label);case"rectangle":return new Rectangle(label);case"polygon":return new Polygon(label);default:return new NullShape(label)}},getSimilar:function(shapeType,shape){if(shapeType===shape.getType())return shape;switch(shapeType){case"circle":return shape.makeSimilarCircle();case"rectangle":return shape.makeSimilarRectangle();case"polygon":return shape.makeSimilarPolygon();default:return new NullShape(shape.label)}}}})); /** * JavaScript to make drag-drop into text questions work. * * Some vocabulary to help understand this code: * * The question text contains 'drops' - blanks into which the 'drags', the missing * words, can be put. * * The thing that can be moved into the drops are called 'drags'. There may be * multiple copies of the 'same' drag which does not really cause problems. * Each drag has a 'choice' number which is the value set on the drop's hidden * input when this drag is placed in a drop. * * These may be in separate 'groups', distinguished by colour. * Things can only interact with other things in the same group. * The groups are numbered from 1. * * The place where a given drag started from is called its 'home'. * * @module qtype_ddwtos/ddwtos * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("qtype_ddwtos/ddwtos",["jquery","core/dragdrop","core/key_codes","core_form/changechecker"],(function($,dragDrop,keys,FormChangeChecker){function DragDropToTextQuestion(containerId,readOnly){this.containerId=containerId,this.questionAnswer={},readOnly&&this.getRoot().addClass("qtype_ddwtos-readonly"),this.resizeAllDragsAndDrops(),this.cloneDrags(),this.positionDrags()}DragDropToTextQuestion.prototype.resizeAllDragsAndDrops=function(){var thisQ=this;this.getRoot().find(".answercontainer > div").each((function(i,node){thisQ.resizeAllDragsAndDropsInGroup(thisQ.getClassnameNumericSuffix($(node),"draggrouphomes"))}))},DragDropToTextQuestion.prototype.resizeAllDragsAndDropsInGroup=function(group){var thisQ=this,dragHomes=this.getRoot().find(".draggrouphomes"+group+" span.draghome"),maxWidth=0,maxHeight=0;dragHomes.each((function(i,drag){maxWidth=Math.max(maxWidth,Math.ceil(drag.offsetWidth)),maxHeight=Math.max(maxHeight,Math.ceil(0+drag.offsetHeight))})),maxWidth+=8,maxHeight+=2,dragHomes.each((function(i,drag){thisQ.setElementSize(drag,maxWidth,maxHeight)})),this.getRoot().find("span.drop.group"+group).each((function(i,drop){thisQ.setElementSize(drop,maxWidth,maxHeight)}))},DragDropToTextQuestion.prototype.setElementSize=function(element,width,height){$(element).width(width).height(height).css("lineHeight",height+"px")},DragDropToTextQuestion.prototype.cloneDrags=function(){var thisQ=this;thisQ.getRoot().find("span.draghome").each((function(index,draghome){var drag=$(draghome),placeHolder=drag.clone();placeHolder.removeClass(),placeHolder.addClass("draghome choice"+thisQ.getChoice(drag)+" group"+thisQ.getGroup(drag)+" dragplaceholder"),drag.before(placeHolder)}))},DragDropToTextQuestion.prototype.positionDrags=function(){var thisQ=this,root=this.getRoot();root.find("span.draghome").not(".dragplaceholder").each((function(i,dragNode){var drag=$(dragNode),currentPlace=thisQ.getClassnameNumericSuffix(drag,"inplace");drag.addClass("unplaced").removeClass("placed"),drag.removeAttr("tabindex"),null!==currentPlace&&drag.removeClass("inplace"+currentPlace)})),root.find("input.placeinput").each((function(i,inputNode){var input=$(inputNode),choice=input.val(),place=thisQ.getPlace(input),drop=root.find(".drop.place"+place),dropPosition=drop.offset();if(drop.data("prev-top",dropPosition.top).data("prev-left",dropPosition.left),"0"!==choice){var unplacedDrag=thisQ.getUnplacedChoice(thisQ.getGroup(input),choice),hiddenDrag=thisQ.getDragClone(unplacedDrag);if(hiddenDrag.length)if(unplacedDrag.hasClass("infinite")){var noOfDrags=thisQ.noOfDropsInGroup(thisQ.getGroup(unplacedDrag));if(thisQ.getInfiniteDragClones(unplacedDrag,!1).length<noOfDrags){var cloneDrag=unplacedDrag.clone();hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag)}else hiddenDrag.addClass("active")}else hiddenDrag.addClass("active");thisQ.sendDragToDrop(thisQ.getUnplacedChoice(thisQ.getGroup(input),choice),drop)}})),thisQ.questionAnswer=thisQ.getQuestionAnsweredValues()},DragDropToTextQuestion.prototype.getQuestionAnsweredValues=function(){let result={};return this.getRoot().find("input.placeinput").each(((i,inputNode)=>{result[inputNode.id]=inputNode.value})),result},DragDropToTextQuestion.prototype.isQuestionInteracted=function(){const oldAnswer=this.questionAnswer,newAnswer=this.getQuestionAnsweredValues();let isInteracted=!1;return JSON.stringify(newAnswer)!==JSON.stringify(oldAnswer)?(isInteracted=!0,isInteracted):(Object.keys(newAnswer).forEach((key=>{newAnswer[key]!==oldAnswer[key]&&(isInteracted=!0)})),isInteracted)},DragDropToTextQuestion.prototype.handleDragStart=function(e){var thisQ=this,drag=$(e.target).closest(".draghome");if(dragDrop.prepare(e).start&&!drag.hasClass("beingdragged")){drag.addClass("beingdragged");var currentPlace=this.getClassnameNumericSuffix(drag,"inplace");if(null!==currentPlace){this.setInputValue(currentPlace,0),drag.removeClass("inplace"+currentPlace);var hiddenDrop=thisQ.getDrop(drag,currentPlace);hiddenDrop.length&&(hiddenDrop.addClass("active"),drag.offset(hiddenDrop.offset()))}else{var hiddenDrag=thisQ.getDragClone(drag);if(hiddenDrag.length)if(drag.hasClass("infinite")){var noOfDrags=this.noOfDropsInGroup(this.getGroup(drag));if(this.getInfiniteDragClones(drag,!1).length<noOfDrags){var cloneDrag=drag.clone();cloneDrag.removeClass("beingdragged"),hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag),drag.offset(cloneDrag.offset())}else hiddenDrag.addClass("active"),drag.offset(hiddenDrag.offset())}else hiddenDrag.addClass("active"),drag.offset(hiddenDrag.offset())}dragDrop.start(e,drag,(function(x,y,drag){thisQ.dragMove(x,y,drag)}),(function(x,y,drag){thisQ.dragEnd(x,y,drag)}))}},DragDropToTextQuestion.prototype.dragMove=function(pageX,pageY,drag){var thisQ=this;this.getRoot().find("span.group"+this.getGroup(drag)).not(".beingdragged").each((function(i,dropNode){var drop=$(dropNode);thisQ.isPointInDrop(pageX,pageY,drop)?drop.addClass("valid-drag-over-drop"):drop.removeClass("valid-drag-over-drop")}))},DragDropToTextQuestion.prototype.dragEnd=function(pageX,pageY,drag){var thisQ=this,root=this.getRoot(),placed=!1;root.find("span.group"+this.getGroup(drag)).not(".beingdragged").each((function(i,dropNode){if(placed)return!1;const dropZone=$(dropNode);if(!thisQ.isPointInDrop(pageX,pageY,dropZone))return!0;let drop=null;return dropZone.hasClass("placed")?(dropZone.removeClass("valid-drag-over-drop"),drop=thisQ.getDrop(drag,thisQ.getClassnameNumericSuffix(dropZone,"inplace"))):drop=dropZone,drop.removeClass("valid-drag-over-drop"),thisQ.sendDragToDrop(drag,drop),placed=!0,!1})),placed||this.sendDragHome(drag)},DragDropToTextQuestion.prototype.sendDragToDrop=function(drag,drop){if(null!==this.getPlace(drop)){var oldDrag=this.getCurrentDragInPlace(this.getPlace(drop));if(0!==oldDrag.length){var currentPlace=this.getClassnameNumericSuffix(oldDrag,"inplace");if(this.hasDropSameDrag(currentPlace,drop,oldDrag,drag))return void this.sendDragHome(drag);var hiddenDrop=this.getDrop(oldDrag,currentPlace);hiddenDrop.addClass("active"),oldDrag.addClass("beingdragged"),oldDrag.offset(hiddenDrop.offset()),this.sendDragHome(oldDrag)}if(0===drag.length)this.setInputValue(this.getPlace(drop),0),drop.data("isfocus")&&drop.focus();else{if(this.getClassnameNumericSuffix(drag,"inplace"))return;this.setInputValue(this.getPlace(drop),this.getChoice(drag)),drag.removeClass("unplaced").addClass("placed inplace"+this.getPlace(drop)),drag.attr("tabindex",0),this.animateTo(drag,drop)}}else this.sendDragHome(drag)},DragDropToTextQuestion.prototype.hasDropSameDrag=function(currentPlace,drop,oldDrag,drag){return!!drag.hasClass("infinite")&&(drop.hasClass("place"+currentPlace)&&this.getGroup(drag)===this.getGroup(drop)&&this.getChoice(drag)===this.getChoice(oldDrag)&&this.getGroup(drag)===this.getGroup(oldDrag))},DragDropToTextQuestion.prototype.sendDragHome=function(drag){var currentPlace=this.getClassnameNumericSuffix(drag,"inplace");null!==currentPlace&&drag.removeClass("inplace"+currentPlace),drag.data("unplaced",!0),this.animateTo(drag,this.getDragHome(this.getGroup(drag),this.getChoice(drag)))},DragDropToTextQuestion.prototype.handleKeyPress=function(e){var drop=$(e.target).closest(".drop");if(0===drop.length){var placedDrag=$(e.target),currentPlace=this.getClassnameNumericSuffix(placedDrag,"inplace");null!==currentPlace&&(drop=this.getDrop(placedDrag,currentPlace))}var currentDrag=this.getCurrentDragInPlace(this.getPlace(drop)),nextDrag=$();switch(e.keyCode){case keys.space:case keys.arrowRight:case keys.arrowDown:nextDrag=this.getNextDrag(this.getGroup(drop),currentDrag);break;case keys.arrowLeft:case keys.arrowUp:nextDrag=this.getPreviousDrag(this.getGroup(drop),currentDrag);break;case keys.escape:break;default:return void(questionManager.isKeyboardNavigation=!1)}if(nextDrag.length){nextDrag.data("isfocus",!0),nextDrag.addClass("beingdragged");var hiddenDrag=this.getDragClone(nextDrag);if(hiddenDrag.length)if(nextDrag.hasClass("infinite")){var noOfDrags=this.noOfDropsInGroup(this.getGroup(nextDrag));if(this.getInfiniteDragClones(nextDrag,!1).length<noOfDrags){var cloneDrag=nextDrag.clone();cloneDrag.removeClass("beingdragged"),cloneDrag.removeAttr("tabindex"),hiddenDrag.after(cloneDrag),questionManager.addEventHandlersToDrag(cloneDrag),nextDrag.offset(cloneDrag.offset())}else hiddenDrag.addClass("active"),nextDrag.offset(hiddenDrag.offset())}else hiddenDrag.addClass("active"),nextDrag.offset(hiddenDrag.offset())}else drop.data("isfocus",!0);e.preventDefault(),this.sendDragToDrop(nextDrag,drop)},DragDropToTextQuestion.prototype.getNextDrag=function(group,drag){var choice,numChoices=this.noOfChoicesInGroup(group);choice=0===drag.length?1:this.getChoice(drag)+1;for(var next=this.getUnplacedChoice(group,choice);0===next.length&&choice<numChoices;)choice++,next=this.getUnplacedChoice(group,choice);return next},DragDropToTextQuestion.prototype.getPreviousDrag=function(group,drag){var choice;choice=0===drag.length?this.noOfChoicesInGroup(group):this.getChoice(drag)-1;for(var previous=this.getUnplacedChoice(group,choice);0===previous.length&&choice>1;)choice--,previous=this.getUnplacedChoice(group,choice);return previous},DragDropToTextQuestion.prototype.animateTo=function(drag,target){var currentPos=drag.offset(),targetPos=target.offset(),thisQ=this;M.util.js_pending("qtype_ddwtos-animate-"+thisQ.containerId),drag.animate({left:parseInt(drag.css("left"))+targetPos.left-currentPos.left,top:parseInt(drag.css("top"))+targetPos.top-currentPos.top},{duration:"fast",done:function(){$("body").trigger("qtype_ddwtos-dragmoved",[drag,target,thisQ]),M.util.js_complete("qtype_ddwtos-animate-"+thisQ.containerId)}})},DragDropToTextQuestion.prototype.isPointInDrop=function(pageX,pageY,drop){var position=drop.offset();return pageX>=position.left&&pageX<position.left+drop.width()&&pageY>=position.top&&pageY<position.top+drop.height()},DragDropToTextQuestion.prototype.setInputValue=function(place,choice){this.getRoot().find("input.placeinput.place"+place).val(choice)},DragDropToTextQuestion.prototype.getRoot=function(){return $(document.getElementById(this.containerId))},DragDropToTextQuestion.prototype.getDragHome=function(group,choice){return this.getRoot().find(".draghome.dragplaceholder.group"+group+".choice"+choice).is(":visible")?this.getRoot().find(".draghome.dragplaceholder.group"+group+".choice"+choice):this.getRoot().find(".draggrouphomes"+group+" span.draghome.infinite.choice"+choice+".group"+group)},DragDropToTextQuestion.prototype.getUnplacedChoice=function(group,choice){return this.getRoot().find(".draghome.group"+group+".choice"+choice+".unplaced").slice(0,1)},DragDropToTextQuestion.prototype.getCurrentDragInPlace=function(place){return this.getRoot().find("span.draghome.inplace"+place)},DragDropToTextQuestion.prototype.noOfDropsInGroup=function(group){return this.getRoot().find(".drop.group"+group).length},DragDropToTextQuestion.prototype.noOfChoicesInGroup=function(group){return this.getRoot().find(".draghome.group"+group).length},DragDropToTextQuestion.prototype.getClassnameNumericSuffix=function(node,prefix){var classes=node.attr("class");if(void 0!==classes&&""!==classes)for(var classesArr=classes.split(" "),index=0;index<classesArr.length;index++){if(new RegExp("^"+prefix+"([0-9])+$").test(classesArr[index])){var match=new RegExp("([0-9])+$").exec(classesArr[index]);return Number(match[0])}}return null},DragDropToTextQuestion.prototype.getChoice=function(drag){return this.getClassnameNumericSuffix(drag,"choice")},DragDropToTextQuestion.prototype.getGroup=function(node){return this.getClassnameNumericSuffix(node,"group")},DragDropToTextQuestion.prototype.getPlace=function(node){return this.getClassnameNumericSuffix(node,"place")},DragDropToTextQuestion.prototype.getDragClone=function(drag){return this.getRoot().find(".draggrouphomes"+this.getGroup(drag)+" span.draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".dragplaceholder")},DragDropToTextQuestion.prototype.getInfiniteDragClones=function(drag,inHome){return inHome?this.getRoot().find(".draggrouphomes"+this.getGroup(drag)+" span.draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".infinite").not(".dragplaceholder"):this.getRoot().find("span.draghome.choice"+this.getChoice(drag)+".group"+this.getGroup(drag)+".infinite").not(".dragplaceholder")},DragDropToTextQuestion.prototype.getDrop=function(drag,currentPlace){return this.getRoot().find(".drop.group"+this.getGroup(drag)+".place"+currentPlace)};var questionManager={eventHandlersInitialised:!1,dragEventHandlersInitialised:{},isKeyboardNavigation:!1,questions:{},init:function(containerId,readOnly){if(questionManager.questions[containerId]=new DragDropToTextQuestion(containerId,readOnly),questionManager.eventHandlersInitialised||(questionManager.setupEventHandlers(),questionManager.eventHandlersInitialised=!0),!questionManager.dragEventHandlersInitialised.hasOwnProperty(containerId)){questionManager.dragEventHandlersInitialised[containerId]=!0;var questionContainer=document.getElementById(containerId);questionContainer.classList.contains("ddwtos")&&!questionContainer.classList.contains("qtype_ddwtos-readonly")&&questionManager.addEventHandlersToDrag($(questionContainer).find("span.draghome"))}},setupEventHandlers:function(){$("body").on("keydown",".que.ddwtos:not(.qtype_ddwtos-readonly) span.drop",questionManager.handleKeyPress).on("keydown",".que.ddwtos:not(.qtype_ddwtos-readonly) span.draghome.placed:not(.beingdragged)",questionManager.handleKeyPress).on("qtype_ddwtos-dragmoved",questionManager.handleDragMoved)},addEventHandlersToDrag:function(element){element.unbind("mousedown touchstart"),element.on("mousedown touchstart",questionManager.handleDragStart)},handleDragStart:function(e){e.preventDefault();var question=questionManager.getQuestionForEvent(e);question&&question.handleDragStart(e)},handleKeyPress:function(e){if(!questionManager.isKeyboardNavigation){questionManager.isKeyboardNavigation=!0;var question=questionManager.getQuestionForEvent(e);question&&question.handleKeyPress(e)}},getQuestionForEvent:function(e){var containerId=$(e.currentTarget).closest(".que.ddwtos").attr("id");return questionManager.questions[containerId]},handleDragMoved:function(e,drag,target,thisQ){drag.removeClass("beingdragged"),drag.css("top","").css("left",""),target.after(drag),target.removeClass("active"),void 0!==drag.data("unplaced")&&!0===drag.data("unplaced")&&(drag.removeClass("placed").addClass("unplaced"),drag.removeAttr("tabindex"),drag.removeData("unplaced"),drag.hasClass("infinite")&&thisQ.getInfiniteDragClones(drag,!0).length>1&&thisQ.getInfiniteDragClones(drag,!0).first().remove()),void 0!==drag.data("isfocus")&&!0===drag.data("isfocus")&&(drag.focus(),drag.removeData("isfocus")),void 0!==target.data("isfocus")&&!0===target.data("isfocus")&&target.removeData("isfocus"),questionManager.isKeyboardNavigation&&(questionManager.isKeyboardNavigation=!1),thisQ.isQuestionInteracted()&&(questionManager.handleFormDirty(),thisQ.questionAnswer=thisQ.getQuestionAnsweredValues())},handleFormDirty:function(){const responseForm=document.getElementById("responseform");FormChangeChecker.markFormAsDirty(responseForm)}};return{init:questionManager.init}})); define("qtype_multichoice/answers",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Handles events related to the multiple-choice question type answers. * * @module qtype_multichoice/answers * @copyright 2020 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS_ANSWER_LABEL="[data-region=answer-label]";var _default={init:rootId=>{const root=document.getElementById(rootId);root.querySelectorAll(SELECTORS_ANSWER_LABEL).forEach((answerLabel=>{answerLabel.addEventListener("click",(e=>{const labelId=e.currentTarget.id;root.querySelector('[aria-labelledby="'.concat(labelId,'"]')).click()}))}))}};return _exports.default=_default,_exports.default})); /** * Manages 'Clear my choice' functionality actions. * * @module qtype_multichoice/clearchoice * @copyright 2019 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.7 */ define("qtype_multichoice/clearchoice",["jquery","core/custom_interaction_events"],(function($,CustomEvents){var SELECTORS_CHOICE_ELEMENT=".answer input",SELECTORS_LINK="a",SELECTORS_RADIO='input[type="radio"]',registerEventListeners=function(root,fieldPrefix){var clearChoiceContainer=function(root,fieldPrefix){return root.find('div[id="'+fieldPrefix+'"]')}(root,fieldPrefix);clearChoiceContainer.on(CustomEvents.events.activate,SELECTORS_LINK,(function(e,data){!function(clearChoiceContainer){clearChoiceContainer.find(SELECTORS_RADIO).prop("disabled",!1).prop("checked",!0)}(clearChoiceContainer),function(clearChoiceContainer){clearChoiceContainer.addClass("sr-only"),clearChoiceContainer.attr("aria-hidden",!0),clearChoiceContainer.find(SELECTORS_LINK).attr("tabindex",-1)}(clearChoiceContainer),data.originalEvent.preventDefault()})),root.on("change",SELECTORS_CHOICE_ELEMENT,(function(){!function(clearChoiceContainer){clearChoiceContainer.removeClass("sr-only"),clearChoiceContainer.removeAttr("aria-hidden"),clearChoiceContainer.find(SELECTORS_LINK).attr("tabindex",0),clearChoiceContainer.find(SELECTORS_RADIO).prop("disabled",!0)}(clearChoiceContainer)})),clearChoiceContainer.find(SELECTORS_RADIO).focus((function(){root.find(SELECTORS_CHOICE_ELEMENT).first().focus()}))};return{init:function(root,fieldPrefix){root=$("#"+root),registerEventListeners(root,fieldPrefix)}}})); define("qtype_ordering/reorder",["jquery","qtype_ordering/drag_reorder"],(function($,DragReorder){return{init:function(sortableid,responseid){new DragReorder({list:"ul#"+sortableid,item:"li.sortableitem",proxyHtml:'<div class="que ordering dragproxy"><ul class="%%LIST_CLASS_NAME%%"><li class="%%ITEM_CLASS_NAME%% item-moving">%%ITEM_HTML%%</li></ul></div>',itemMovingClass:"current-drop",idGetter:function(item){return $(item).attr("id")},nameGetter:function(item){return $(item).text},reorderStart:function(){},reorderEnd:function(){},reorderDone:function(list,item,newOrder){$("input#"+responseid)[0].value=newOrder.join(",")}})}}})); /* * JavaScript to handle drag operations, including automatic scrolling. * * This is a copy of a library that was added to Moodle core in Moodle 3.6, * so we can support older Moodle versions. * * Note: this module is defined statically. It is a singleton. You * can only have one use of it active at any time. However, you * can only drag one thing at a time, this is not a problem in practice. * * @module qtype_ordering/dragdrop * @class dragdrop * @package qtype_ordering * @copyright 2016 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("qtype_ordering/dragdrop",["jquery","qtype_ordering/autoscroll"],(function($,autoScroll){var dragdrop={eventCaptureOptions:{passive:!1,capture:!0},dragProxy:null,onMove:null,onDrop:null,initialPosition:null,initialX:null,initialY:null,touching:null,prepare:function(event){if(event.preventDefault(),"touchstart"===event.type?null===dragdrop.touching&&event.changedTouches.length>0:1===event.which){var details=dragdrop.getEventXY(event);return details.start=!0,details}return{start:!1}},start:function(event,dragProxy,onMove,onDrop){var xy=dragdrop.getEventXY(event);switch(dragdrop.initialX=xy.x,dragdrop.initialY=xy.y,dragdrop.initialPosition=dragProxy.offset(),dragdrop.dragProxy=dragProxy,dragdrop.onMove=onMove,dragdrop.onDrop=onDrop,event.type){case"mousedown":dragdrop.addEventSpecial("mousemove",dragdrop.mouseMove),dragdrop.addEventSpecial("mouseup",dragdrop.mouseUp);break;case"touchstart":dragdrop.addEventSpecial("touchend",dragdrop.touchEnd),dragdrop.addEventSpecial("touchcancel",dragdrop.touchEnd),dragdrop.addEventSpecial("touchmove",dragdrop.touchMove),dragdrop.touching=event.changedTouches[0].identifier;break;default:throw new Error("Unexpected event type: "+event.type)}autoScroll.start(dragdrop.scroll)},addEventSpecial:function(event,handler){try{window.addEventListener(event,handler,dragdrop.eventCaptureOptions)}catch(ex){dragdrop.eventCaptureOptions=!0,window.addEventListener(event,handler,dragdrop.eventCaptureOptions)}},getEventXY:function(event){switch(event.type){case"touchstart":return{x:event.changedTouches[0].pageX,y:event.changedTouches[0].pageY};case"mousedown":return{x:event.pageX,y:event.pageY};default:throw new Error("Unexpected event type: "+event.type)}},touchMove:function(e){e.preventDefault();for(var i=0;i<e.changedTouches.length;i++)e.changedTouches[i].identifier===dragdrop.touching&&dragdrop.handleMove(e.changedTouches[i].pageX,e.changedTouches[i].pageY)},mouseMove:function(e){dragdrop.handleMove(e.pageX,e.pageY)},handleMove:function(pageX,pageY){var current=dragdrop.dragProxy.offset(),topOffset=current.top-parseInt(dragdrop.dragProxy.css("top")),leftOffset=current.left-parseInt(dragdrop.dragProxy.css("left")),maxY=$(document).height()-dragdrop.dragProxy.outerHeight()-topOffset,maxX=$(document).width()-dragdrop.dragProxy.outerWidth()-leftOffset,minY=-topOffset,minX=-leftOffset,initial=dragdrop.initialPosition,position={top:Math.max(minY,Math.min(maxY,initial.top+(pageY-dragdrop.initialY)-topOffset)),left:Math.max(minX,Math.min(maxX,initial.left+(pageX-dragdrop.initialX)-leftOffset))};dragdrop.dragProxy.css(position),dragdrop.onMove(pageX,pageY,dragdrop.dragProxy)},touchEnd:function(e){e.preventDefault();for(var i=0;i<e.changedTouches.length;i++)e.changedTouches[i].identifier===dragdrop.touching&&dragdrop.handleEnd(e.changedTouches[i].pageX,e.changedTouches[i].pageY)},mouseUp:function(e){dragdrop.handleEnd(e.pageX,e.pageY)},handleEnd:function(pageX,pageY){null!==dragdrop.touching?(window.removeEventListener("touchend",dragdrop.touchEnd,dragdrop.eventCaptureOptions),window.removeEventListener("touchcancel",dragdrop.touchEnd,dragdrop.eventCaptureOptions),window.removeEventListener("touchmove",dragdrop.touchMove,dragdrop.eventCaptureOptions),dragdrop.touching=null):(window.removeEventListener("mousemove",dragdrop.mouseMove,dragdrop.eventCaptureOptions),window.removeEventListener("mouseup",dragdrop.mouseUp,dragdrop.eventCaptureOptions)),autoScroll.stop(),dragdrop.onDrop(pageX,pageY,dragdrop.dragProxy)},scroll:function(offset){var maxY=$(document).height()-dragdrop.dragProxy.outerHeight(),currentPosition=dragdrop.dragProxy.offset();currentPosition.top=Math.min(maxY,currentPosition.top+offset),dragdrop.dragProxy.css(currentPosition)}};return{prepare:dragdrop.prepare,start:dragdrop.start}})); /* * JavaScript to provide automatic scrolling, e.g. during a drag operation. * * This is a copy of a library that was added to Moodle core in Moodle 3.6, * so we can support older Moodle versions. * * Note: this module is defined statically. It is a singleton. You * can only have one use of it active at any time. However, since this * is usually used in relation to drag-drop, and since you only ever * drag one thing at a time, this is not a problem in practice. * * @module qtype_ordering/autoscroll * @class autoscroll * @package qtype_ordering * @copyright 2016 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.6 */ define("qtype_ordering/autoscroll",["jquery"],(function($){var autoscroll={SCROLL_THRESHOLD:30,SCROLL_FREQUENCY:1e3/60,SCROLL_SPEED:.5,scrollingId:null,scrollAmount:0,callback:null,start:function(callback){$(window).on("mousemove",autoscroll.mouseMove),$(window).on("touchmove",autoscroll.touchMove),autoscroll.callback=callback},stop:function(){$(window).off("mousemove",autoscroll.mouseMove),$(window).off("touchmove",autoscroll.touchMove),null!==autoscroll.scrollingId&&autoscroll.stopScrolling()},touchMove:function(e){for(var i=0;i<e.changedTouches.length;i++)autoscroll.handleMove(e.changedTouches[i].clientX,e.changedTouches[i].clientY)},mouseMove:function(e){autoscroll.handleMove(e.clientX,e.clientY)},handleMove:function(clientX,clientY){clientY<autoscroll.SCROLL_THRESHOLD?autoscroll.scrollAmount=-Math.min(autoscroll.SCROLL_THRESHOLD-clientY,autoscroll.SCROLL_THRESHOLD):clientY>$(window).height()-autoscroll.SCROLL_THRESHOLD?autoscroll.scrollAmount=Math.min(clientY-($(window).height()-autoscroll.SCROLL_THRESHOLD),autoscroll.SCROLL_THRESHOLD):autoscroll.scrollAmount=0,autoscroll.scrollAmount&&null===autoscroll.scrollingId?autoscroll.startScrolling():autoscroll.scrollAmount||null===autoscroll.scrollingId||autoscroll.stopScrolling()},startScrolling:function(){var maxScroll=$(document).height()-$(window).height();autoscroll.scrollingId=window.setInterval((function(){var y=$(window).scrollTop(),offset=Math.round(autoscroll.scrollAmount*autoscroll.SCROLL_SPEED);if(y+offset<0&&(offset=-y),y+offset>maxScroll&&(offset=maxScroll-y),0!==offset){$(window).scrollTop(y+offset);var realOffset=$(window).scrollTop()-y;0!==realOffset&&autoscroll.callback&&autoscroll.callback(realOffset)}}),autoscroll.SCROLL_FREQUENCY)},stopScrolling:function(){window.clearInterval(autoscroll.scrollingId),autoscroll.scrollingId=null}};return{start:autoscroll.start,stop:autoscroll.stop}})); /* * Generic library to allow things in a vertical list to be re-ordered using drag and drop. * * To make a set of things draggable, create a new instance of this object passing the * necessary config, as explained in the comment on the constructor. * * @package qtype_ordering * @copyright 2018 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qtype_ordering/drag_reorder",["jquery",require.specified("core/dragdrop")?"core/dragdrop":"qtype_ordering/dragdrop",require.specified("core/key_codes")?"core/key_codes":"qtype_ordering/key_codes"],(function($,drag,keys){return function(config){var outer,inner,combined,dragStart=null,originalOrder=null,itemDragging=null,itemMoving=null,proxy=null,orderList=null,dragMove=function(){var list=itemDragging.closest(config.list),closestItem=null,closestDistance=null;if(list.find(config.item).each((function(index,element){var distance=distanceBetweenElements(element,proxy);(null===closestItem||distance<closestDistance)&&(closestItem=$(element),closestDistance=distance)})),closestItem[0]!==itemDragging[0]){var offsetValue=0;midY(proxy)<midY(closestItem)?(offsetValue=20,window.console.log("For midY(proxy) < midY(closestItem) offset is: "+offsetValue)):(offsetValue=-20,window.console.log("For midY(proxy) < midY(closestItem) offset is: "+offsetValue)),midY(proxy)+offsetValue<midY(closestItem)?itemDragging.insertBefore(closestItem):itemDragging.insertAfter(closestItem),updateProxy(itemDragging)}},updateProxy=function(itemDragging){for(var items=itemDragging.closest("ol, ul").find("li"),count=items.length,i=0;i<count;++i)if(itemDragging[0]===items[i]){proxy.find("li").attr("value",i+1);break}},dragEnd=function(x,y){void 0!==config.reorderEnd&&config.reorderEnd(itemDragging.closest(config.list),itemDragging);var newOrder=getCurrentOrder();arrayEquals(originalOrder,newOrder)?(new Date).getTime()-dragStart.time<500&&Math.abs(dragStart.x-x)<10&&Math.abs(dragStart.y-y)<10&&itemDragging[0].focus():config.reorderDone(itemDragging.closest(config.list),itemDragging,newOrder),proxy.remove(),proxy=null,itemDragging.removeClass(config.itemMovingClass),itemDragging=null,dragStart=null},midX=function(jQuery){return jQuery.offset().left+jQuery.outerWidth()/2},midY=function(jQuery){return jQuery.offset().top+jQuery.outerHeight()/2},distanceBetweenElements=function(element1,element2){var e1=$(element1),e2=$(element2),dx=midX(e1)-midX(e2),dy=midY(e1)-midY(e2);return Math.sqrt(dx*dx+dy*dy)},getCurrentOrder=function(){return(itemDragging||itemMoving).closest(config.list).find(config.item).map((function(index,item){return config.idGetter(item)})).get()},arrayEquals=function(a1,a2){return a1.length===a2.length&&a1.every((function(v,i){return v===a2[i]}))};config.itemInPage=(outer=config.list,inner=config.item,combined=[],outer.split(",").forEach((function(firstSelector){inner.split(",").forEach((function(secondSelector){combined.push(firstSelector.trim()+" "+secondSelector.trim())}))})),combined.join(", ")),$(config.list).on("mousedown touchstart",config.item,(function(event){var details=drag.prepare(event);details.start&&function(event,details){orderList=$(config.list),dragStart={time:(new Date).getTime(),x:details.x,y:details.y},itemDragging=$(event.currentTarget).closest(config.itemInPage),void 0!==config.reorderStart&&config.reorderStart(itemDragging.closest(config.list),itemDragging),originalOrder=getCurrentOrder(),proxy=$(config.proxyHtml.replace("%%ITEM_HTML%%",itemDragging.html()).replace("%%ITEM_CLASS_NAME%%",itemDragging.attr("class")).replace("%%LIST_CLASS_NAME%%",orderList.attr("class"))),$(document.body).append(proxy),proxy.css("position","absolute"),proxy.css(itemDragging.offset()),proxy.width(itemDragging.outerWidth()),proxy.height(itemDragging.outerHeight()),itemDragging.addClass(config.itemMovingClass),updateProxy(itemDragging),drag.start(event,proxy,dragMove,dragEnd)}(event,details)})),$(config.list).on("keydown",config.item,(function(event){itemMoving=$(event.currentTarget).closest(config.itemInPage),originalOrder=getCurrentOrder(),function(e,current){switch(e.keyCode){case keys.space:case keys.arrowRight:case keys.arrowDown:e.preventDefault(),e.stopPropagation();var next=current.next();next.length&&next.insertBefore(current);break;case keys.arrowLeft:case keys.arrowUp:e.preventDefault(),e.stopPropagation();var prev=current.prev();prev.length&&prev.insertAfter(current)}}(event,itemMoving);var newOrder=getCurrentOrder();arrayEquals(originalOrder,newOrder)||config.reorderDone(itemMoving.closest(config.list),itemMoving,newOrder)})),$(config.itemInPage).attr("tabindex","0")}})); /* * A list of human readable names for the keycodes. * * This is a copy of a library that was added to Moodle core in Moodle 3.2, * so we can support older Moodle versions. * * @module qtype_ordering/key_codes * @class key_codes * @package qtype_ordering * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("qtype_ordering/key_codes",[],(function(){return{tab:9,enter:13,escape:27,space:32,end:35,home:36,arrowLeft:37,arrowUp:38,arrowRight:39,arrowDown:40,8:56,asterix:106,pageUp:33,pageDown:34}})); /** * Javascript controller for the "Actions" panel at the bottom of the page. * * @module mod_assign/grading_actions * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_actions",["jquery","mod_assign/grading_events"],(function($,GradingEvents){var GradingActions=function(selector){this._regionSelector=selector,this._region=$(selector),this.registerEventListeners()};return GradingActions.prototype._regionSelector=null,GradingActions.prototype._lastUserId=0,GradingActions.prototype._region=null,GradingActions.prototype._showActionsForm=function(event,userid){var form=this._region.find("[data-region=grading-actions-form]");userid!=this._lastUserId&&userid>0&&(this._lastUserId=userid),userid>0?form.removeClass("hide"):form.addClass("hide")},GradingActions.prototype._trigger=function(action){$(document).trigger(action)},GradingActions.prototype.getReviewPanelElement=function(){return $('[data-region="review-panel"]')},GradingActions.prototype.hasReviewPanelElement=function(){return this.getReviewPanelElement().length>0},GradingActions.prototype.getCollapseGradePanelButton=function(){return $('[data-region="grade-actions"] .collapse-grade-panel')},GradingActions.prototype.getCollapseReviewPanelButton=function(){return $('[data-region="grade-actions"] .collapse-review-panel')},GradingActions.prototype.getExpandAllPanelsButton=function(){return $('[data-region="grade-actions"] .collapse-none')},GradingActions.prototype.resetLayoutButtons=function(){this.getCollapseGradePanelButton().removeClass("active"),this.getCollapseReviewPanelButton().removeClass("active"),this.getExpandAllPanelsButton().removeClass("active")},GradingActions.prototype.collapseReviewPanel=function(){$(document).trigger(GradingEvents.COLLAPSE_REVIEW_PANEL),$(document).trigger(GradingEvents.EXPAND_GRADE_PANEL),this.resetLayoutButtons(),this.getCollapseReviewPanelButton().addClass("active")},GradingActions.prototype.collapseGradePanel=function(){$(document).trigger(GradingEvents.COLLAPSE_GRADE_PANEL),$(document).trigger(GradingEvents.EXPAND_REVIEW_PANEL),this.resetLayoutButtons(),this.getCollapseGradePanelButton().addClass("active")},GradingActions.prototype.expandAllPanels=function(){$(document).trigger(GradingEvents.EXPAND_GRADE_PANEL),$(document).trigger(GradingEvents.EXPAND_REVIEW_PANEL),this.resetLayoutButtons(),this.getExpandAllPanelsButton().addClass("active")},GradingActions.prototype.registerEventListeners=function(){if(this.hasReviewPanelElement()){var collapseReviewPanelButton=this.getCollapseReviewPanelButton();collapseReviewPanelButton.click(function(e){this.collapseReviewPanel(),e.preventDefault()}.bind(this)),collapseReviewPanelButton.keydown(function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||13!==e.keyCode&&32!==e.keyCode||(this.collapseReviewPanel(),e.preventDefault())}.bind(this));var collapseGradePanelButton=this.getCollapseGradePanelButton();collapseGradePanelButton.click(function(e){this.collapseGradePanel(),e.preventDefault()}.bind(this)),collapseGradePanelButton.keydown(function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||13!==e.keyCode&&32!==e.keyCode||(this.collapseGradePanel(),e.preventDefault())}.bind(this));var expandAllPanelsButton=this.getExpandAllPanelsButton();expandAllPanelsButton.click(function(e){this.expandAllPanels(),e.preventDefault()}.bind(this)),expandAllPanelsButton.keydown(function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||13!==e.keyCode&&32!==e.keyCode||(this.expandAllPanels(),e.preventDefault())}.bind(this))}$(document).on("user-changed",this._showActionsForm.bind(this)),this._region.find('[name="savechanges"]').on("click",this._trigger.bind(this,"save-changes")),this._region.find('[name="saveandshownext"]').on("click",this._trigger.bind(this,"save-and-show-next")),this._region.find('[name="resetbutton"]').on("click",this._trigger.bind(this,"reset")),this._region.find("form").on("submit",(function(e){e.preventDefault()}))},GradingActions})); /** * Events for the grading interface. * * @module mod_assign/grading_events * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_events",(function(){return{COLLAPSE_REVIEW_PANEL:"grading:collapse-review-panel",EXPAND_REVIEW_PANEL:"grading:expand-review-panel",COLLAPSE_GRADE_PANEL:"grading:collapse-grade-panel",EXPAND_GRADE_PANEL:"grading:expand-grade-panel"}})); /** * Simple method to check for changes to a form between two points in time. * * @module mod_assign/grading_form_change_checker * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_form_change_checker",["jquery"],(function($){return{saveFormState:function(selector){$(selector).trigger("save-form-state");var data=$(selector).serialize();$(selector).data("saved-form-state",data)},checkFormForChanges:function(selector){$(selector).trigger("save-form-state");var data=$(selector).serialize(),previousdata=$(selector).data("saved-form-state");return void 0!==previousdata&&previousdata!=data}}})); /** * Javascript controller for the "User summary" panel at the top of the page. * * @module mod_assign/grading_navigation_user_info * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_navigation_user_info",["jquery","core/notification","core/ajax","core/templates"],(function($,notification,ajax,templates){var UserInfo=function(selector){this._regionSelector=selector,this._region=$(selector),this._userCache={},$(document).on("user-changed",this._refreshUserInfo.bind(this))};return UserInfo.prototype._regionSelector=null,UserInfo.prototype._userCache=null,UserInfo.prototype._region=null,UserInfo.prototype._lastUserId=0,UserInfo.prototype._getAssignmentId=function(){return this._region.attr("data-assignmentid")},UserInfo.prototype._refreshUserInfo=function(event,userid){var promise=$.Deferred();this._region.attr("data-userid",userid),this._lastUserId!=userid&&(this._lastUserId=userid,templates.render("mod_assign/loading",{}).done(function(html,js){if(this._region.fadeOut("fast",function(){templates.replaceNodeContents(this._region,html,js),this._region.fadeIn("fast")}.bind(this)),userid<0)templates.render("mod_assign/grading_navigation_no_users",{}).done(function(html,js){userid==this._lastUserId&&this._region.fadeOut("fast",function(){templates.replaceNodeContents(this._region,html,js),this._region.fadeIn("fast")}.bind(this))}.bind(this)).fail(notification.exception);else{if(void 0!==this._userCache[userid])promise.resolve(this._userCache[userid]);else{var assignmentId=this._getAssignmentId();ajax.call([{methodname:"mod_assign_get_participant",args:{userid:userid,assignid:assignmentId,embeduser:!0}}])[0].done(function(participant){participant.hasOwnProperty("id")?(this._userCache[userid]=participant,promise.resolve(this._userCache[userid])):promise.reject("No users")}.bind(this)).fail(notification.exception)}promise.done(function(context){var identityfields=$("[data-showuseridentity]").data("showuseridentity").split(","),identity=[];context.courseid=$('[data-region="grading-navigation-panel"]').attr("data-courseid"),context.user&&($.each(identityfields,(function(i,k){void 0!==context.user[k]&&""!==context.user[k]&&(context.hasidentity=!0,identity.push(context.user[k]))})),context.identity=identity.join(", "),context.user.profileimageurl&&(context.profileimageurl=context.user.profileimageurl)),templates.render("mod_assign/grading_navigation_user_summary",context).done(function(html,js){userid==this._lastUserId&&this._region.fadeOut("fast",function(){templates.replaceNodeContents(this._region,html,js),this._region.fadeIn("fast")}.bind(this))}.bind(this)).fail(notification.exception)}.bind(this)).fail(function(){templates.render("mod_assign/grading_navigation_no_users",{}).done(function(html,js){this._region.fadeOut("fast",function(){templates.replaceNodeContents(this._region,html,js),this._region.fadeIn("fast")}.bind(this))}.bind(this)).fail(notification.exception)}.bind(this))}}.bind(this)).fail(notification.exception))},UserInfo})); /** * Javascript controller for the "Grading" panel at the right of the page. * * @module mod_assign/grading_panel * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_panel",["jquery","core/yui","core/notification","core/templates","core/fragment","core/ajax","core/str","mod_assign/grading_form_change_checker","mod_assign/grading_events","core_form/events","core/toast","core_form/changechecker"],(function($,Y,notification,templates,fragment,ajax,str,checker,GradingEvents,FormEvents,Toast,FormChangeChecker){var GradingPanel=function(selector){this._regionSelector=selector,this._region=$(selector),this._userCache=[],this.registerEventListeners()};return GradingPanel.prototype._regionSelector=null,GradingPanel.prototype._lastUserId=0,GradingPanel.prototype._lastAttemptNumber=-1,GradingPanel.prototype._region=null,GradingPanel.prototype.nextUserId=null,GradingPanel.prototype.nextUser=!1,GradingPanel.prototype._niceReplaceNodeContents=function(node,html,js){var promise=$.Deferred();return node.fadeOut("fast",(function(){templates.replaceNodeContents(node,html,js),node.fadeIn("fast",(function(){promise.resolve()}))})),promise.promise()},GradingPanel.prototype._saveFormState=function(){var checked=$('[data-region="grading-actions-form"] [name="sendstudentnotifications"]').prop("checked");$('.gradeform [name="sendstudentnotifications"]').val(checked)},GradingPanel.prototype._submitForm=function(event,nextUserId,nextUser){var commentAreaElement=document.querySelector(".comment-area");commentAreaElement&&(""!==commentAreaElement.querySelector(".db > textarea").value&&commentAreaElement.querySelector('.fd a[id^="comment-action-post-"]').click());var form=$(this._region.find("form.gradeform"));$('[data-region="overlay"]').show(),FormChangeChecker.markFormSubmitted(form[0]),form.trigger("save-form-state"),FormEvents.notifyFormSubmittedByJavascript(form[0]);var data=form.serialize(),assignmentid=this._region.attr("data-assignmentid");ajax.call([{methodname:"mod_assign_submit_grading_form",args:{assignmentid:assignmentid,userid:this._lastUserId,jsonformdata:JSON.stringify(data)},done:this._handleFormSubmissionResponse.bind(this,data,nextUserId,nextUser),fail:notification.exception}])},GradingPanel.prototype._handleFormSubmissionResponse=function(formdata,nextUserId,nextUser,response){if(void 0===nextUserId&&(nextUserId=this._lastUserId),response.length)$(document).trigger("reset",[this._lastUserId,formdata]);else{str.get_string("gradechangessaveddetail","mod_assign").then((function(str){return Toast.add(str),str})).catch(notification.exception);var form=$(this._region.find("form.gradeform"));FormChangeChecker.resetFormDirtyState(form[0]),nextUserId==this._lastUserId?$(document).trigger("reset",nextUserId):nextUser?$(document).trigger("done-saving-show-next",!0):$(document).trigger("user-changed",nextUserId)}$('[data-region="overlay"]').hide()},GradingPanel.prototype._resetForm=function(e,userid,formdata){var event=$.Event("custom");void 0===userid&&(userid=this._lastUserId),this._lastUserId=0,this._refreshGradingPanel(event,userid,formdata)},GradingPanel.prototype._chooseAttempt=function(e){var submissionsId=$(e.target).data("submissions"),formhtml=$(document.getElementById(submissionsId)).clone().wrap($("<form/>")).html();str.get_strings([{key:"viewadifferentattempt",component:"mod_assign"},{key:"view",component:"core"},{key:"cancel",component:"core"}]).done(function(strs){notification.confirm(strs[0],formhtml,strs[1],strs[2],function(){var attemptnumber=$("input:radio[name='select-attemptnumber']:checked").val();this._refreshGradingPanel(null,this._lastUserId,"",attemptnumber)}.bind(this))}.bind(this)).fail(notification.exception)},GradingPanel.prototype._addPopoutButtons=function(selector){var region=$(selector);templates.render("mod_assign/popout_button",{}).done(function(html){region.find('[data-fieldtype="filemanager"],[data-fieldtype="editor"],[data-fieldtype="grading"]').closest(".fitem").addClass("has-popout").find("label").parent().append(html),region.on("click",'[data-region="popout-button"]',this._togglePopout.bind(this))}.bind(this)).fail(notification.exception)},GradingPanel.prototype._togglePopout=function(event){event.preventDefault();var container=$(event.target).closest(".fitem");container.hasClass("popout")?$(".popout").removeClass("popout"):($(".popout").removeClass("popout"),container.addClass("popout"),container.addClass("moodle-has-zindex"))},GradingPanel.prototype._refreshGradingPanel=function(event,userid,submissiondata,attemptnumber){var contextid=this._region.attr("data-contextid");void 0===submissiondata&&(submissiondata=""),void 0===attemptnumber&&(attemptnumber=-1),this._lastUserId==userid&&this._lastAttemptNumber==attemptnumber&&""===submissiondata||(this._lastUserId=userid,this._lastAttemptNumber=attemptnumber,$(document).trigger("start-loading-user"),window.M.util.js_pending("mod-assign-loading-user"),templates.render("mod_assign/loading",{}).done(function(html,js){this._niceReplaceNodeContents(this._region,html,js).done(function(){if(userid>0){this._region.show();var params={userid:userid,attemptnumber:attemptnumber,jsonformdata:JSON.stringify(submissiondata)};fragment.loadFragment("mod_assign","gradingpanel",contextid,params).done(function(html,js){this._niceReplaceNodeContents(this._region,html,js).done(function(){checker.saveFormState('[data-region="grade-panel"] .gradeform'),$(document).on("editor-content-restored",(function(){checker.saveFormState('[data-region="grade-panel"] .gradeform')})),$('[data-region="attempt-chooser"]').on("click",this._chooseAttempt.bind(this)),this._addPopoutButtons('[data-region="grade-panel"] .gradeform'),$(document).trigger("finish-loading-user"),window.M.util.js_complete("mod-assign-loading-user")}.bind(this)).fail(notification.exception)}.bind(this)).fail(notification.exception),$('[data-region="review-panel"]').show()}else this._region.hide(),$('[data-region="review-panel"]').hide(),$(document).trigger("finish-loading-user"),window.M.util.js_complete("mod-assign-loading-user")}.bind(this))}.bind(this)).fail(notification.exception))},GradingPanel.prototype._getNextUser=function(event,data){this.nextUserId=data.nextUserId,this.nextUser=data.nextUser},GradingPanel.prototype._handleSaveAndShowNext=function(){this._submitForm(null,this.nextUserId,this.nextUser)},GradingPanel.prototype.getPanelElement=function(){return $('[data-region="grade-panel"]')},GradingPanel.prototype.collapsePanel=function(){this.getPanelElement().addClass("collapsed")},GradingPanel.prototype.expandPanel=function(){this.getPanelElement().removeClass("collapsed")},GradingPanel.prototype.registerEventListeners=function(){var docElement=$(document);$(this._region).on("submit","form",(function(e){e.preventDefault()})),docElement.on("next-user",this._getNextUser.bind(this)),docElement.on("user-changed",this._refreshGradingPanel.bind(this)),docElement.on("save-changes",this._submitForm.bind(this)),docElement.on("save-and-show-next",this._handleSaveAndShowNext.bind(this)),docElement.on("reset",this._resetForm.bind(this)),docElement.on("save-form-state",this._saveFormState.bind(this)),docElement.on(GradingEvents.COLLAPSE_GRADE_PANEL,function(){this.collapsePanel()}.bind(this)),docElement.on(GradingEvents.COLLAPSE_REVIEW_PANEL,function(){this.expandPanel()}.bind(this)),docElement.on(GradingEvents.EXPAND_GRADE_PANEL,function(){this.expandPanel()}.bind(this))},GradingPanel})); /** * Javascript controller for the "Review" panel at the left of the page. * * @module mod_assign/grading_review_panel * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_review_panel",["jquery","mod_assign/grading_events"],(function($,GradingEvents){var GradingReviewPanel=function(){this._region=$('[data-region="review-panel-content"]'),this.registerEventListeners()};return GradingReviewPanel.prototype._region=null,GradingReviewPanel.prototype.getReviewPanel=function(pluginname){return void 0===this._region.data("panel-owner")&&this._region.data("review-panel-plugin",pluginname),this._region.data("review-panel-plugin")==pluginname&&this._region[0]},GradingReviewPanel.prototype.getTogglePanelButton=function(){return this.getPanelElement().find('[data-region="review-panel-toggle"]')},GradingReviewPanel.prototype.getPanelElement=function(){return $('[data-region="review-panel"]')},GradingReviewPanel.prototype.getPanelContentElement=function(){return $('[data-region="review-panel-content"]')},GradingReviewPanel.prototype.togglePanel=function(){this.getPanelElement().hasClass("collapsed")?$(document).trigger(GradingEvents.EXPAND_REVIEW_PANEL):$(document).trigger(GradingEvents.COLLAPSE_REVIEW_PANEL)},GradingReviewPanel.prototype.collapsePanel=function(){this.getPanelElement().addClass("collapsed").removeClass("grade-panel-collapsed"),this.getPanelContentElement().attr("aria-hidden",!0)},GradingReviewPanel.prototype.expandPanel=function(){this.getPanelElement().removeClass("collapsed"),this.getPanelContentElement().removeAttr("aria-hidden")},GradingReviewPanel.prototype.registerEventListeners=function(){var toggleReviewPanelButton=this.getTogglePanelButton();toggleReviewPanelButton.click(function(e){this.togglePanel(),e.preventDefault()}.bind(this)),toggleReviewPanelButton.keydown(function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||13!==e.keyCode&&32!==e.keyCode||(this.togglePanel(),e.preventDefault())}.bind(this));var docElement=$(document);docElement.on(GradingEvents.COLLAPSE_REVIEW_PANEL,function(){this.collapsePanel()}.bind(this)),docElement.on(GradingEvents.COLLAPSE_GRADE_PANEL,function(){this.expandPanel(),this.getPanelElement().addClass("grade-panel-collapsed")}.bind(this)),docElement.on(GradingEvents.EXPAND_REVIEW_PANEL,function(){this.expandPanel()}.bind(this)),docElement.on(GradingEvents.EXPAND_GRADE_PANEL,function(){this.getPanelElement().removeClass("grade-panel-collapsed")}.bind(this))},GradingReviewPanel})); define("mod_assign/override_form",["exports","jquery","core_form/changechecker"],(function(_exports,_jquery,FormChangeChecker){var obj; /** * A javascript module to enhance the override form. * * @copyright 2019 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj},FormChangeChecker=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(FormChangeChecker);_exports.init=(formId,selectElementName)=>{const form=document.getElementById(formId),selectElement=form.querySelector('[name="'.concat(selectElementName,'"]'));(0,_jquery.default)(selectElement).on("change",(()=>{const inputElement=document.createElement("input");inputElement.setAttribute("type","hidden"),inputElement.setAttribute("name","userchange"),inputElement.setAttribute("value",!0),form.appendChild(inputElement),FormChangeChecker.markFormSubmitted(inputElement),form.submit()}))}})); /** * Javascript to handle changing users via the user selector in the header. * * @module mod_assign/grading_navigation * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_assign/grading_navigation",["jquery","core/notification","core/str","core/form-autocomplete","core/ajax","mod_assign/grading_form_change_checker"],(function($,notification,str,autocomplete,ajax,checker){var GradingNavigation=function(selector){this._regionSelector=selector,this._region=$(selector),this._filters=[],this._users=[],this._filteredUsers=[],this._lastXofYUpdate=0,this._firstLoadUsers=!0;let url=new URL(window.location);parseInt(url.searchParams.get("treset"))>0&&(url.searchParams.delete("treset"),window.history.replaceState({},"",url)),this._loadAllUsers(),this._region.find('[data-action="previous-user"]').on("click",this._handlePreviousUser.bind(this)),this._region.find('[data-action="next-user"]').on("click",this._handleNextUser.bind(this)),this._region.find('[data-action="change-user"]').on("change",this._handleChangeUser.bind(this)),this._region.find('[data-region="user-filters"]').on("click",this._toggleExpandFilters.bind(this)),this._region.find('[data-region="user-resettable"]').on("click",this._toggleResetTable.bind()),$(document).on("user-changed",this._refreshSelector.bind(this)),$(document).on("done-saving-show-next",this._handleNextUser.bind(this));var toggleLink=this._region.find('[data-region="user-filters"]');$(document.getElementById(toggleLink.attr("aria-controls"))).on("change","select",this._filterChanged.bind(this));var userid=$('[data-region="grading-navigation-panel"]').data("first-userid");userid&&this._selectUserById(userid),str.get_string("changeuser","mod_assign").done((function(s){autocomplete.enhance("[data-action=change-user]",!1,"mod_assign/participant_selector",s)})).fail(notification.exception),$(document).bind("start-loading-user",function(){this._isLoading=!0}.bind(this)),$(document).bind("finish-loading-user",function(){this._isLoading=!1}.bind(this))};return GradingNavigation.prototype._isLoading=!1,GradingNavigation.prototype._regionSelector=null,GradingNavigation.prototype._filters=null,GradingNavigation.prototype._users=null,GradingNavigation.prototype._region=null,GradingNavigation.prototype._lastFilters="",GradingNavigation.prototype._loadAllUsers=function(){var select=this._region.find("[data-action=change-user]"),assignmentid=select.attr("data-assignmentid"),groupid=select.attr("data-groupid"),filterPanel=this._region.find('[data-region="configure-filters"]'),filter=filterPanel.find('select[name="filter"]').val(),workflowFilter=filterPanel.find('select[name="workflowfilter"]');workflowFilter&&(filter+=","+workflowFilter.val());var markerFilter=filterPanel.find('select[name="markerfilter"]');return markerFilter&&(filter+=","+markerFilter.val()),this._lastFilters!=filter&&(this._lastFilters=filter,ajax.call([{methodname:"mod_assign_list_participants",args:{assignid:assignmentid,groupid:groupid,filter:"",onlyids:!0,tablesort:!0},done:this._usersLoaded.bind(this),fail:notification.exception}]),!0)},GradingNavigation.prototype._usersLoaded=function(users){if(this._firstLoadUsers=!1,this._filteredUsers=this._users=users,this._users.length){var toggleLink=this._region.find('[data-region="user-filters"]');$(document.getElementById(toggleLink.attr("aria-controls"))).find('select[name="filter"]').trigger("change")}else this._selectNoUser();this._triggerNextUserEvent()},GradingNavigation.prototype._checkClickOutsideConfigureFilters=function(event){var configPanel=this._region.find('[data-region="configure-filters"]');if(!configPanel.is(event.target)&&0===configPanel.has(event.target).length){var toggleLink=this._region.find('[data-region="user-filters"]');configPanel.hide(),configPanel.attr("aria-hidden","true"),toggleLink.attr("aria-expanded","false"),$(document).unbind("click.mod_assign_grading_navigation")}},GradingNavigation.prototype._updateFilterPreferences=function(userId,filterList,preferenceNames){var preferences=[],i=0;if(0==filterList.length||this._firstLoadUsers){var deferred=$.Deferred();return deferred.resolve(),deferred}for(i=0;i<filterList.length;i++){var newValue=filterList[i];"none"==newValue&&(newValue=""),preferences.push({userid:userId,name:preferenceNames[i],value:newValue})}return ajax.call([{methodname:"core_user_set_user_preferences",args:{preferences:preferences}}])[0]},GradingNavigation.prototype._filterChanged=function(){var filterPanel=this._region.find('[data-region="configure-filters"]'),filters=filterPanel.find("select"),preferenceNames=[];this._filters=[],filters.each(function(idx,ele){var element=$(ele);this._filters.push(element.val()),preferenceNames.push("assign_"+element.prop("name"))}.bind(this));var filterlist=[];filterPanel.find("option:checked").each((function(idx,ele){filterlist[filterlist.length]=$(ele).text()})),filterlist.length?this._region.find('[data-region="user-filters"] span').text(filterlist.join(", ")):str.get_string("nofilters","mod_assign").done(function(s){this._region.find('[data-region="user-filters"] span').text(s)}.bind(this)).fail(notification.exception);var select=this._region.find("[data-action=change-user]"),currentUserID=select.data("currentuserid");this._updateFilterPreferences(currentUserID,this._filters,preferenceNames).done(function(){if(!this._loadAllUsers()){var userid=parseInt(select.attr("data-selected"));let foundIndex=null;$.each(this._filteredUsers,(function(index,user){userid==user.id&&(foundIndex=index)})),this._filteredUsers.length&&null!==foundIndex?this._selectUserById(this._filteredUsers[foundIndex].id):this._selectNoUser()}}.bind(this)).fail(notification.exception),this._refreshCount()},GradingNavigation.prototype._selectNoUser=function(){this._isLoading||(checker.checkFormForChanges('[data-region="grade-panel"] .gradeform')?str.get_strings([{key:"unsavedchanges",component:"mod_assign"},{key:"unsavedchangesquestion",component:"mod_assign"},{key:"saveandcontinue",component:"mod_assign"},{key:"cancel",component:"core"}]).done((function(strs){notification.confirm(strs[0],strs[1],strs[2],strs[3],(function(){$(document).trigger("save-changes",-1)}))})):$(document).trigger("user-changed",-1))},GradingNavigation.prototype._selectUserById=function(userid){var select=this._region.find("[data-action=change-user]"),useridnumber=parseInt(userid,10);this._isLoading||(checker.checkFormForChanges('[data-region="grade-panel"] .gradeform')?str.get_strings([{key:"unsavedchanges",component:"mod_assign"},{key:"unsavedchangesquestion",component:"mod_assign"},{key:"saveandcontinue",component:"mod_assign"},{key:"cancel",component:"core"}]).done((function(strs){notification.confirm(strs[0],strs[1],strs[2],strs[3],(function(){$(document).trigger("save-changes",useridnumber)}))})):(select.attr("data-selected",userid),!isNaN(useridnumber)&&useridnumber>0&&$(document).trigger("user-changed",userid)))},GradingNavigation.prototype._toggleExpandFilters=function(event){event.preventDefault();var toggleLink=$(event.target).closest('[data-region="user-filters"]'),expanded="true"==toggleLink.attr("aria-expanded"),configPanel=$(document.getElementById(toggleLink.attr("aria-controls")));expanded?(configPanel.hide(),configPanel.attr("aria-hidden","true"),toggleLink.attr("aria-expanded","false"),$(document).unbind("click.mod_assign_grading_navigation")):(configPanel.css("display","inline-block"),configPanel.attr("aria-hidden","false"),toggleLink.attr("aria-expanded","true"),event.stopPropagation(),$(document).on("click.mod_assign_grading_navigation",this._checkClickOutsideConfigureFilters.bind(this)))},GradingNavigation.prototype._toggleResetTable=function(){let url=new URL(window.location);url.searchParams.set("treset","1"),window.location.href=url},GradingNavigation.prototype._handlePreviousUser=function(e){e.preventDefault();var currentUserId=this._region.find("[data-action=change-user]").attr("data-selected"),i=0,currentIndex=0;for(i=0;i<this._filteredUsers.length;i++)if(this._filteredUsers[i].id==currentUserId){currentIndex=i;break}var count=this._filteredUsers.length,newIndex=currentIndex-1;newIndex<0&&(newIndex=count-1),count&&this._selectUserById(this._filteredUsers[newIndex].id)},GradingNavigation.prototype._handleNextUser=function(e,saved){e.preventDefault();var select=this._region.find("[data-action=change-user]"),currentUserId=select.attr("data-selected"),i=0,currentIndex=0;for(i=0;i<this._filteredUsers.length;i++)if(this._filteredUsers[i].id==currentUserId){currentIndex=i;break}var count=this._filteredUsers.length,newIndex=(currentIndex+1)%count;if(saved&&count){var userid=this._filteredUsers[newIndex].id,useridnumber=parseInt(userid,10);select.attr("data-selected",userid),!isNaN(useridnumber)&&useridnumber>0&&$(document).trigger("user-changed",userid)}else count&&this._selectUserById(this._filteredUsers[newIndex].id)},GradingNavigation.prototype._setCountString=function(x,y){var updateNumber;this._lastXofYUpdate++,updateNumber=this._lastXofYUpdate;var param={x:x,y:y};str.get_string("xofy","mod_assign",param).done(function(s){updateNumber==this._lastXofYUpdate&&this._region.find('[data-region="user-count-summary"]').text(s)}.bind(this)).fail(notification.exception)},GradingNavigation.prototype._refreshCount=function(){var userid=this._region.find("[data-action=change-user]").attr("data-selected"),i=0,currentIndex=0;if(isNaN(userid)||userid<=0)this._region.find('[data-region="user-count"]').hide();else{for(this._region.find('[data-region="user-count"]').show(),i=0;i<this._filteredUsers.length;i++)if(this._filteredUsers[i].id==userid){currentIndex=i;break}var count=this._filteredUsers.length;if(count&&(currentIndex+=1),this._setCountString(currentIndex,count),currentIndex>0){var url=new URL(window.location);if(parseInt(url.searchParams.get("blindid"))>0){var newid=this._filteredUsers[currentIndex-1].recordid;url.searchParams.set("blindid",newid)}else url.searchParams.set("userid",userid);window.history.replaceState({},"",url)}}},GradingNavigation.prototype._refreshSelector=function(event,userid){var select=this._region.find("[data-action=change-user]");userid=parseInt(userid,10),!isNaN(userid)&&userid>0&&select.attr("data-selected",userid),this._refreshCount()},GradingNavigation.prototype._triggerNextUserEvent=function(){this._filteredUsers.length>1?$(document).trigger("next-user",{nextUserId:null,nextUser:!0}):$(document).trigger("next-user",{nextUser:!1})},GradingNavigation.prototype._handleChangeUser=function(){var select=this._region.find("[data-action=change-user]"),userid=parseInt(select.val(),10);this._isLoading||(checker.checkFormForChanges('[data-region="grade-panel"] .gradeform')?str.get_strings([{key:"unsavedchanges",component:"mod_assign"},{key:"unsavedchangesquestion",component:"mod_assign"},{key:"saveandcontinue",component:"mod_assign"},{key:"cancel",component:"core"}]).done((function(strs){notification.confirm(strs[0],strs[1],strs[2],strs[3],(function(){$(document).trigger("save-changes",userid)}))})):!isNaN(userid)&&userid>0&&(select.attr("data-selected",userid),$(document).trigger("user-changed",userid)))},GradingNavigation})); /** * Custom auto-complete adapter to load users from the assignment list_participants webservice. * * @module mod_assign/participants_selector * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_assign/participant_selector",["core/ajax","jquery","core/templates"],(function(ajax,$,templates){return{processResults:function(selector,data){return data},transport:function(selector,query,success,failure){var assignmentid=$(selector).attr("data-assignmentid"),groupid=$(selector).attr("data-groupid"),filters=$('[data-region="configure-filters"] input[type="checkbox"]'),filterstrings=[];filters.each((function(index,element){filterstrings[$(element).attr("name")]=$(element).prop("checked")})),ajax.call([{methodname:"mod_assign_list_participants",args:{assignid:assignmentid,groupid:groupid,filter:query,limit:30,includeenrolments:!1,tablesort:!0}}])[0].then((function(results){var promises=[],identityfields=$("[data-showuseridentity]").data("showuseridentity").split(",");return $.each(results,(function(index,user){var ctx=user,identity=[],show=!0;filterstrings.filter_submitted&&!user.submitted&&(show=!1),filterstrings.filter_notsubmitted&&user.submitted&&(show=!1),filterstrings.filter_requiregrading&&!user.requiregrading&&(show=!1),filterstrings.filter_grantedextension&&!user.grantedextension&&(show=!1),show&&($.each(identityfields,(function(i,k){void 0!==user[k]&&""!==user[k]&&(ctx.hasidentity=!0,identity.push(user[k]))})),ctx.identity=identity.join(", "),promises.push(templates.render("mod_assign/list_participant_user_summary",ctx).then((function(html){return{value:user.id,label:html}}))))})),$.when.apply($,promises)})).then((function(){var users=[];arguments[0]&&(users=Array.prototype.slice.call(arguments)),success(users)})).catch(failure)}}})); define("mod_assign/timer",["exports","core/notification","core/str"],(function(_exports,_notification,_str){var obj; /** * A javascript module for the time in the assign module. * * @copyright 2020 Matt Porritt <mattp@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj};let endTime=0,timeoutId=null,timer=null;const update=()=>{const now=(new Date).getTime(),secondsLeft=Math.floor((endTime-now)/1e3);if(secondsLeft<=0)return timer.classList.add("alert","alert-danger"),timer.innerHTML="00:00:00",document.getElementById("mod_assign_timelimit_block")&&(0,_str.get_string)("caneditsubmission","mod_assign").then((message=>_notification.default.addNotification({message:message}))).catch(_notification.default.exception),void(timeoutId&&clearTimeout(timeoutId));var secs;secondsLeft<300?(timer.classList.remove("alert-warning"),timer.classList.add("alert","alert-danger")):secondsLeft<900&&(timer.classList.remove("alert-danger"),timer.classList.add("alert","alert-warning")),timer.innerHTML=(secs=secondsLeft,[Math.floor(secs/3600),Math.floor(secs/60)%60,secs%60].filter(((value,index)=>0!==value||index>0)).map((value=>"".concat(value).padStart(2,"0"))).join(":")),timeoutId=setTimeout(update,500)};_exports.init=timerId=>{timer=document.getElementById(timerId),endTime=M.pageloadstarttime.getTime()+1e3*timer.dataset.starttime,update()}})); /** * Allows status form elements to be modified. * * @module mod_attendance * @author Sumaiya Javed <sumaiya.javed@catalyst.net.nz> * @copyright 2017 Dan Marsden http://danmarsden.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_attendance/statusset",[],(function(){return{init:function(){document.querySelectorAll(".custom-select").forEach((box=>{var studentbox="student"+box.name;1==box.value&&(document.getElementsByName(studentbox)[0].style.display="block"),box.addEventListener("change",(function(){1==box.value&&(document.getElementsByName(studentbox)[0].style.display="block",document.getElementsByName(studentbox)[0].placeholder="Minutes",document.getElementsByName(studentbox)[0].value=""),0==box.value&&(document.getElementsByName(studentbox)[0].style.display="none",document.getElementsByName(studentbox)[0].value=0),""==box.value&&(document.getElementsByName(studentbox)[0].value="")}))}))}}})); define("mod_bigbluebuttonbn/events",["exports","core/event_dispatcher"],(function(_exports,_event_dispatcher){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifySessionEnded=_exports.notifyCurrentSessionEnded=_exports.eventTypes=void 0; /** * Events for the mod_bigbluebuttonbn plugin. * * @module mod_bigbluebuttonbn/events * @copyright 2021 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const eventTypes={sessionEnded:"mod_bigbluebuttonbn/sessionEnded",currentSessionEnded:"mod_bigbluebuttonbn/currentSessionEnded"};_exports.eventTypes=eventTypes;_exports.notifySessionEnded=(bbbId,groupId)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.sessionEnded,{bbbId:bbbId,groupId:groupId});_exports.notifyCurrentSessionEnded=container=>(0,_event_dispatcher.dispatchEvent)(eventTypes.currentSessionEnded,{},container)})); define("mod_bigbluebuttonbn/index",["exports","./actions","./events"],(function(_exports,_actions,_events){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=()=>{document.addEventListener(_events.eventTypes.sessionEnded,(()=>{window.location.reload()}))}})); define("mod_bigbluebuttonbn/repository",["exports","core/ajax"],(function(_exports,_ajax){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateRecording=_exports.getMeetingInfo=_exports.fetchRecordingsToImport=_exports.fetchRecordings=_exports.endMeeting=_exports.completionValidate=void 0;_exports.fetchRecordings=(bigbluebuttonbnid,tools,groupid)=>{const args={bigbluebuttonbnid:bigbluebuttonbnid,tools:tools};return groupid&&(args.groupid=groupid),(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_get_recordings",args:args}])[0]};_exports.fetchRecordingsToImport=(destinationinstanceid,sourcebigbluebuttonbnid,sourcecourseid,tools,groupid)=>{const args={destinationinstanceid:destinationinstanceid,sourcebigbluebuttonbnid:sourcebigbluebuttonbnid,sourcecourseid:sourcecourseid,tools:tools};return groupid&&(args.groupid=groupid),(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_get_recordings_to_import",args:args}])[0]};_exports.updateRecording=args=>(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_update_recording",args:args}])[0];_exports.endMeeting=(bigbluebuttonbnid,groupid)=>(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_end_meeting",args:{bigbluebuttonbnid:bigbluebuttonbnid,groupid:groupid}}])[0];_exports.completionValidate=args=>(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_completion_validate",args:args}])[0];_exports.getMeetingInfo=function(bigbluebuttonbnid,groupid){let updatecache=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return(0,_ajax.call)([{methodname:"mod_bigbluebuttonbn_meeting_info",args:{bigbluebuttonbnid:bigbluebuttonbnid,groupid:groupid,updatecache:updatecache}}])[0]}})); define("mod_bigbluebuttonbn/rooms",["exports","./actions","./repository","./roomupdater","core/notification","./events"],(function(_exports,_actions,repository,roomUpdater,_notification,_events){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * JS actions for the rooms page for mod_bigbluebuttonbn. * * @module mod_bigbluebuttonbn/rooms * @copyright 2021 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setupWindowAutoClose=_exports.init=void 0,repository=_interopRequireWildcard(repository),roomUpdater=_interopRequireWildcard(roomUpdater);_exports.init=(bigbluebuttonbnid,pollInterval)=>{const completionElement=document.querySelector("a[href*=completion_validate]");completionElement&&completionElement.addEventListener("click",(()=>{repository.completionValidate(bigbluebuttonbnid).catch(_notification.exception)})),document.addEventListener("click",(e=>{const joinButton=e.target.closest('[data-action="join"]');joinButton&&(window.open(joinButton.href,"bigbluebutton_conference"),e.preventDefault(),setTimeout((()=>{roomUpdater.updateRoom(!0)}),pollInterval))})),document.addEventListener(_events.eventTypes.sessionEnded,(()=>{roomUpdater.stop(),roomUpdater.updateRoom(),(0,_notification.fetchNotifications)()})),window.addEventListener(_events.eventTypes.currentSessionEnded,(()=>{roomUpdater.stop(),roomUpdater.updateRoom(),(0,_notification.fetchNotifications)()})),roomUpdater.start(pollInterval)};_exports.setupWindowAutoClose=function(){let closeDelay=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;(0,_events.notifyCurrentSessionEnded)(window.opener),window.addEventListener("onbeforeunload",(()=>{window.opener.setTimeout((()=>{roomUpdater.updateRoom(!0)}),closeDelay)}),{once:!0}),window.close()}})); define("mod_bigbluebuttonbn/roomupdater",["exports","core/pending","core/templates","core/notification","./repository"],(function(_exports,_pending,_templates,_notification,_repository){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * JS room updater. * * @module mod_bigbluebuttonbn/roomupdater * @copyright 2021 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateRoom=_exports.stop=_exports.start=void 0,_pending=_interopRequireDefault(_pending),_templates=_interopRequireDefault(_templates);let timerReference=null,timerRunning=!1,pollInterval=0,pollIntervalFactor=1;const resetValues=()=>{timerRunning=!1,timerReference=null,pollInterval=0,pollIntervalFactor=1};_exports.start=interval=>{resetValues(),timerRunning=!0,pollInterval=interval,poll()};_exports.stop=()=>{timerReference&&clearTimeout(timerReference),resetValues()};const poll=()=>{timerRunning&&pollInterval&&updateRoom().then((updateOk=>(updateOk||(pollIntervalFactor=pollIntervalFactor<10?pollIntervalFactor+1:10),timerReference=setTimeout((()=>poll()),pollInterval*pollIntervalFactor),!0))).catch()},updateRoom=function(){let updatecache=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const bbbRoomViewElement=document.getElementById("bigbluebuttonbn-room-view");if(null===bbbRoomViewElement)return Promise.resolve(!1);const bbbId=bbbRoomViewElement.dataset.bbbId,groupId=bbbRoomViewElement.dataset.groupId,pendingPromise=new _pending.default("mod_bigbluebuttonbn/roomupdater:updateRoom");return(0,_repository.getMeetingInfo)(bbbId,groupId,updatecache).then((data=>(data.haspresentations=!(!data.presentations||!data.presentations.length),_templates.default.renderForPromise("mod_bigbluebuttonbn/room_view",data)))).then((_ref=>{let{html:html,js:js}=_ref;return _templates.default.replaceNode(bbbRoomViewElement,html,js)})).then((()=>pendingPromise.resolve())).catch(_notification.exception)};_exports.updateRoom=updateRoom})); define("mod_bigbluebuttonbn/actions",["./repository","core/notification","./events","core/str"],(function(_repository,_notification,_events,_str){let listening=!1;listening||((()=>{document.addEventListener("click",(e=>{const actionButton=e.target.closest('.bbb-btn-action[data-action="end"]');if(!actionButton)return;e.preventDefault();const bbbId=actionButton.dataset.bbbId,groupId=actionButton.dataset.groupId?actionButton.dataset.groupId:0;var title,question,saveLabel;(title=(0,_str.get_string)("end_session_confirm_title","mod_bigbluebuttonbn"),question=(0,_str.get_string)("end_session_confirm","mod_bigbluebuttonbn"),saveLabel=(0,_str.get_string)("yes","moodle"),new Promise((resolve=>{(0,_notification.saveCancel)(title,question,saveLabel,resolve)}))).then((()=>(0,_repository.endMeeting)(bbbId,groupId))).then((()=>{(0,_events.notifySessionEnded)(bbbId,groupId)})).catch(_notification.exception)}))})(),listening=!0)})); define("mod_bigbluebuttonbn/guest_access_modal",["exports","core/str","core_form/modalform","core/toast","core/notification"],(function(_exports,_str,_modalform,_toast,_notification){var obj; /** * Javascript module for importing presets. * * @module mod_bigbluebuttonbn/guest_access_modal * @copyright 2022 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=(obj=_modalform)&&obj.__esModule?obj:{default:obj};const selectors_showGuestAccessButton='[data-action="show-guest-access"]';_exports.init=guestInfo=>{const showGuestAccessButton=document.querySelector(selectors_showGuestAccessButton);if(null===showGuestAccessButton)return;const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("guestaccess_title","mod_bigbluebuttonbn"),large:!0},args:guestInfo,saveButtonText:(0,_str.get_string)("ok","core_moodle"),formClass:"mod_bigbluebuttonbn\\form\\guest_add"});showGuestAccessButton.addEventListener("click",(event=>{modalForm.show().then((()=>((0,_toast.addToastRegion)(modalForm.modal.getRoot()[0]),!0))).catch(_notification.exception),modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(e=>{modalForm.modal.getRoot()[0].querySelectorAll(".toast-wrapper").forEach((reg=>reg.remove())),e.detail.result?e.detail.emailcount>0&&(0,_toast.add)((0,_str.get_string)("guestaccess_invite_success","mod_bigbluebuttonbn",e.detail),{type:"success"}):(0,_toast.add)((0,_str.get_string)("guestaccess_invite_failure","mod_bigbluebuttonbn",e.detail),{type:"warning"})}),{once:!0}),event.stopPropagation()}))}})); define("mod_bigbluebuttonbn/modform",["exports","core/str","core/notification","core/templates"],(function(_exports,_str,_notification,_templates){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * JS for the mod_form page on mod_bigbluebuttonbn plugin. * * @module mod_bigbluebuttonbn/mod_form * @copyright 2021 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates);const ELEMENT_SELECTOR_instanceTypeSelection=()=>document.querySelector("select#id_type"),ELEMENT_SELECTOR_instanceTypeProfiles=()=>document.querySelector("[data-profile-types]"),ELEMENT_SELECTOR_participantData=()=>document.querySelector("[data-participant-data]"),ELEMENT_SELECTOR_participantList=()=>document.getElementsByName("participants")[0],ELEMENT_SELECTOR_participantTable=()=>document.getElementById("participant_list_table"),ELEMENT_SELECTOR_participantSelectionType=()=>document.getElementsByName("bigbluebuttonbn_participant_selection_type")[0],ELEMENT_SELECTOR_participantSelection=()=>document.getElementsByName("bigbluebuttonbn_participant_selection")[0],ELEMENT_SELECTOR_participantAddButton=()=>document.getElementsByName("bigbluebuttonbn_participant_selection_add")[0];_exports.init=info=>{const selectedType=ELEMENT_SELECTOR_instanceTypeSelection(),instanceTypeProfiles=JSON.parse(ELEMENT_SELECTOR_instanceTypeProfiles().dataset.profileTypes);let profileType=info.instanceTypeDefault;null!==selectedType&&-1!==selectedType.selectedIndex&&(profileType=selectedType.options[selectedType.selectedIndex].value);const isFeatureEnabled=(profileType,feature)=>-1!==instanceTypeProfiles[profileType].features.indexOf(feature);applyInstanceTypeProfile(profileType,isFeatureEnabled),selectedType.addEventListener("change",(e=>{applyInstanceTypeProfile(e.target.value,isFeatureEnabled)})),ELEMENT_SELECTOR_participantSelectionType().addEventListener("change",(e=>{const currentTypeSelect=e.target;updateSelectionFromType(currentTypeSelect)})),ELEMENT_SELECTOR_participantAddButton().addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault(),participantAddFromCurrentSelection()})),participantListInit()};const applyInstanceTypeProfile=(profileType,isFeatureEnabled)=>{let showAll=isFeatureEnabled(profileType,"all");const showFieldset=(id,show)=>{const node=document.querySelector("#"+id);node&&(node.style.display=show?"block":"none")},showInput=(id,show)=>{const node=document.querySelector("#"+id);if(node){var ancestor=node.closest("div").closest("div");ancestor.style.display=show?"block":"none"}},showFormGroup=(id,show)=>{const node=document.querySelector("#fgroup_id_"+id);node&&(show?node.classList.remove("hidden"):node.classList.add("hidden"))};showFieldset("id_room",showAll||isFeatureEnabled(profileType,"showroom")),showInput("id_record",showAll||isFeatureEnabled(profileType,"showroom")),showFieldset("id_recordings",showAll||isFeatureEnabled(profileType,"showrecordings")),showInput("id_recordings_imported",showAll||isFeatureEnabled(profileType,"showrecordings")),showFieldset("id_lock",showAll||isFeatureEnabled(profileType,"lock")),showFieldset("id_guestaccess",showAll||isFeatureEnabled(profileType,"showroom")),showFieldset("id_preuploadpresentation",showAll||isFeatureEnabled(profileType,"preuploadpresentation")),showFieldset("id_permissions",showAll||isFeatureEnabled(profileType,"permissions")),showFieldset("id_schedule",showAll||isFeatureEnabled(profileType,"schedule")),showFieldset("id_modstandardelshdr",showAll||isFeatureEnabled(profileType,"modstandardelshdr")),showFieldset("id_availabilityconditionsheader",showAll||isFeatureEnabled(profileType,"availabilityconditionsheader")),showFieldset("id_tagshdr",showAll||isFeatureEnabled(profileType,"tagshdr")),showFieldset("id_competenciessection",showAll||isFeatureEnabled(profileType,"competenciessection")),showFormGroup("completionattendancegroup",showAll||isFeatureEnabled(profileType,"completionattendance")),showFormGroup("completionengagementgroup",showAll||isFeatureEnabled(profileType,"completionengagement"))},participantListInit=()=>{const participantData=JSON.parse(ELEMENT_SELECTOR_participantData().dataset.participantData);getParticipantList().forEach((participant=>{const selectionTypeValue=participant.selectiontype,selectionValue=participant.selectionid,selectionRole=participant.role;"all"!==participant.selectiontype&&void 0===participantData[participant.selectiontype].children[participant.selectionid]||participantAddToForm(selectionTypeValue,selectionValue,selectionRole,!0).then()}))},participantAddToForm=async(selectionTypeValue,selectionValue,selectedRole,canRemove)=>{const participantData=JSON.parse(ELEMENT_SELECTOR_participantData().dataset.participantData);let roles={viewer:{id:"viewer",label:await(0,_str.get_string)("mod_form_field_participant_bbb_role_viewer","mod_bigbluebuttonbn")},moderator:{id:"moderator",label:await(0,_str.get_string)("mod_form_field_participant_bbb_role_moderator","mod_bigbluebuttonbn")}};roles[selectedRole].isselected=!0;try{const listTable=document.querySelector("#participant_list_table tbody"),templateContext={selectiontypevalue:selectionTypeValue,selectionvalue:selectionValue,participanttype:participantData[selectionTypeValue].name,participantvalue:"all"!==selectionTypeValue?participantData[selectionTypeValue].children[selectionValue].name:null,roles:Object.values(roles),canRemove:canRemove},{html:html,js:js}=await _templates.default.renderForPromise("mod_bigbluebuttonbn/participant_form_add",templateContext),newNode=_templates.default.appendNodeContents(listTable,html,js)[0];newNode.querySelector(".participant-select").addEventListener("change",(()=>{participantListRoleUpdate(selectionTypeValue,selectionValue)}));const removeNode=newNode.querySelector(".remove-button");removeNode&&removeNode.addEventListener("click",(()=>{participantRemove(selectionTypeValue,selectionValue)}))}catch(e){_notification.default.exception(e)}},participantListUpdate=list=>{ELEMENT_SELECTOR_participantList().value=JSON.stringify(list)},getParticipantList=()=>{const participantListValue=ELEMENT_SELECTOR_participantList().value;return participantListValue?JSON.parse(participantListValue):[]},participantRemove=(selectionTypeValue,selectionValue)=>{const pList=getParticipantList(),id="participant_list_tr_"+selectionTypeValue+"-"+selectionValue,participantListTable=ELEMENT_SELECTOR_participantTable(),selectionid=""===selectionValue?null:selectionValue;for(let i=0;i<pList.length;i++)pList[i].selectiontype===selectionTypeValue&&pList[i].selectionid===selectionid&&pList.splice(i,1);for(let i=0;i<participantListTable.rows.length;i++)participantListTable.rows[i].id===id&&participantListTable.deleteRow(i);participantListUpdate(pList)},participantListRoleUpdate=(type,id)=>{const participantListRoleSelection=document.querySelector("#participant_list_tr_".concat(type,"-").concat(id," .participant-select")),pList=getParticipantList();for(var i=0;i<pList.length;i++)pList[i].selectiontype===type&&pList[i].selectionid===id&&(pList[i].role=participantListRoleSelection.value);participantListUpdate(pList)},participantAddFromCurrentSelection=()=>{let selectionType=ELEMENT_SELECTOR_participantSelectionType(),selection=ELEMENT_SELECTOR_participantSelection();const pList=getParticipantList();for(var i=0;i<pList.length;i++)if(pList[i].selectiontype===selectionType.value&&pList[i].selectionid===selection.value)return;pList.push({selectiontype:selectionType.value,selectionid:selection.value,role:"viewer"}),participantAddToForm(selectionType.value,selection.value,"viewer",!0).then(),participantListUpdate(pList)},updateSelectionFromType=currentTypeSelect=>{const createNewOption=(selectItem,label,value)=>{const option=document.createElement("option");option.text=label,option.value=value,selectItem.add(option)},participantData=JSON.parse(ELEMENT_SELECTOR_participantData().dataset.participantData),participantSelect=ELEMENT_SELECTOR_participantSelection();for(;participantSelect.firstChild;)participantSelect.removeChild(participantSelect.firstChild);if(-1!==currentTypeSelect.selectedIndex){Object.values(participantData[currentTypeSelect.value].children).forEach((option=>{createNewOption(participantSelect,option.name,option.id)})),"all"===currentTypeSelect.value?(createNewOption(participantSelect,"---------------","all"),participantSelect.disabled=!0):participantSelect.disabled=!1}}})); define("mod_bigbluebuttonbn/recordings",["exports","./repository","core/notification","core/prefetch","core/str","core/loadingicon","core/modal_factory","core/modal_events","core/pending"],(function(_exports,repository,_notification,_prefetch,_str,_loadingicon,_modal_factory,_modal_events,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,repository=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * JS for the recordings page on mod_bigbluebuttonbn plugin. * * @module mod_bigbluebuttonbn/recordings * @copyright 2021 Blindside Networks Inc * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(repository),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_pending=_interopRequireDefault(_pending);const stringsWithKeys={first:"view_recording_yui_first",prev:"view_recording_yui_prev",next:"view_recording_yui_next",last:"view_recording_yui_last",goToLabel:"view_recording_yui_page",goToAction:"view_recording_yui_go",perPage:"view_recording_yui_rows",showAll:"view_recording_yui_show_all"};(0,_prefetch.prefetchStrings)("bigbluebuttonbn",Object.entries(stringsWithKeys).map((entry=>entry[1])));const getStringsForYui=()=>{const stringMap=Object.keys(stringsWithKeys).map((key=>({key:stringsWithKeys[key],component:"mod_bigbluebuttonbn"})));return(0,_str.get_strings)(stringMap).then((stringArray=>Object.assign({},...Object.keys(stringsWithKeys).map(((key,index)=>({[key]:stringArray[index]})))))).catch()},getFormattedData=response=>{const recordingData=response.tabledata;return JSON.parse(recordingData.data)},getTableNode=tableSelector=>document.querySelector(tableSelector),fetchRecordingData=tableSelector=>{const tableNode=getTableNode(tableSelector);return null===tableNode?Promise.resolve(!1):tableNode.dataset.importMode?repository.fetchRecordingsToImport(tableNode.dataset.bbbid,tableNode.dataset.bbbSourceInstanceId,tableNode.dataset.bbbSourceCourseId,tableNode.dataset.tools,tableNode.dataset.groupId):repository.fetchRecordings(tableNode.dataset.bbbid,tableNode.dataset.tools,tableNode.dataset.groupId)},getDataTableFunctions=(tableId,searchFormId,dataTable)=>{const bbbid=getTableNode(tableId).dataset.bbbid,updateTableFromResponse=response=>{if(!response||!response.status)return;dataTable.get("data").reset(getFormattedData(response)),dataTable.set("currentData",dataTable.get("data"));const currentFilter=dataTable.get("currentFilter");currentFilter&&filterByText(currentFilter)},refreshTableData=()=>fetchRecordingData(tableId).then(updateTableFromResponse),filterByText=value=>{const dataModel=dataTable.get("currentData");dataTable.set("currentFilter",value);const escapedRegex=value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rsearch=new RegExp("<span>.*?".concat(escapedRegex,".*?</span>"),"i");dataTable.set("data",dataModel.filter({asList:!0},(item=>{const name=item.get("recording");if(name&&rsearch.test(name))return!0;const description=item.get("description");return description&&rsearch.test(description)})))},recordingConfirmationMessage=async data=>{var _document$querySelect,_document$querySelect2;const playbackElement=document.querySelector("#playbacks-".concat(data.recordingid)),recordingType=await(0,_str.get_string)("true"===playbackElement.dataset.imported?"view_recording_link":"view_recording","bigbluebuttonbn"),confirmation=await(0,_str.get_string)("view_recording_".concat(data.action,"_confirmation"),"bigbluebuttonbn",recordingType);if("import"===data.action)return confirmation;const associatedLinkCount=null===(_document$querySelect=document.querySelector("a#recording-".concat(data.action,"-").concat(data.recordingid)))||void 0===_document$querySelect||null===(_document$querySelect2=_document$querySelect.dataset)||void 0===_document$querySelect2?void 0:_document$querySelect2.links;if(!associatedLinkCount||0===associatedLinkCount)return confirmation;return await(0,_str.get_string)("view_recording_".concat(data.action,1===associatedLinkCount?"_confirmation_warning_p":"_confirmation_warning_s"),"bigbluebuttonbn",associatedLinkCount)+"\n\n"+confirmation},processAction=e=>{const popoutLink=e.target.closest('[data-action="play"]');if(popoutLink){e.preventDefault();const videoPlayer=window.open("","_blank");return videoPlayer.opener=null,void(videoPlayer.location.href=popoutLink.href)}const clickedLink=e.target.closest("a[data-action]");if(clickedLink&&!clickedLink.classList.contains("disabled")){e.preventDefault();const iconPromise=(0,_loadingicon.addIconToContainerWithPromise)(dataTable.get("boundingBox").getDOMNode());(element=>{const getDataFromAction=(element,dataType)=>{const dataElement=element.closest("[data-".concat(dataType,"]"));return dataElement?dataElement.dataset[dataType]:null},elementData=element.dataset,payload={bigbluebuttonbnid:bbbid,recordingid:getDataFromAction(element,"recordingid"),additionaloptions:getDataFromAction(element,"additionaloptions"),action:elementData.action};if(payload.additionaloptions||(payload.additionaloptions={}),"import"===elementData.action){const bbbsourceid=getDataFromAction(element,"source-instance-id"),bbbcourseid=getDataFromAction(element,"source-course-id");payload.additionaloptions||(payload.additionaloptions={}),payload.additionaloptions.sourceid=bbbsourceid||0,payload.additionaloptions.bbbcourseid=bbbcourseid||0}return payload.additionaloptions=JSON.stringify(payload.additionaloptions),"1"===element.dataset.requireConfirmation?new Promise((resolve=>_modal_factory.default.create({title:(0,_str.get_string)("confirm"),body:recordingConfirmationMessage(payload),type:_modal_factory.default.types.SAVE_CANCEL}).then((async modal=>(modal.setSaveButtonText(await(0,_str.get_string)("ok","moodle")),modal.getRoot().on(_modal_events.default.save,(()=>{resolve(!0)})),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy(),resolve(!1)})),modal.show(),modal))).catch(_notification.exception))).then((proceed=>proceed?repository.updateRecording(payload):()=>null)):repository.updateRecording(payload)})(clickedLink).then(refreshTableData).then(iconPromise.resolve).catch(_notification.exception)}},processSearchSubmission=e=>{e.preventDefault();const searchInput=e.target.closest("div[role=search]").querySelector("input[name=search]");filterByText(searchInput.value)};return{filterByText:filterByText,refreshTableData:refreshTableData,registerEventListeners:()=>{dataTable.get("boundingBox").getDOMNode().addEventListener("click",processAction);if(document.querySelector(searchFormId)){document.querySelector(searchFormId+" button").addEventListener("click",processSearchSubmission)}}}},setupDatatable=(tableId,searchFormId,response)=>{if(!response)return Promise.resolve();if(!response.status)return Promise.resolve();const recordingData=response.tabledata,pendingPromise=new _pending.default("mod_bigbluebuttonbn/recordings/setupDatatable");return Promise.all([(lang=recordingData.locale,new Promise((resolve=>{YUI({lang:lang}).use("intl","datatable","datatable-sort","datatable-paginator","datatype-number",(Y=>{resolve(Y)}))}))),getStringsForYui()]).then((_ref=>{let[yuiInstance,strings]=_ref;return yuiInstance.Intl.add("datatable-paginator",yuiInstance.config.lang,{...strings}),yuiInstance.DataTable.BodyView.Formatters.customDate=()=>cell=>{return locale=recordingData.locale,date=cell.value,new Date(date).toLocaleDateString(locale,{weekday:"long",year:"numeric",month:"long",day:"numeric"});var locale,date},yuiInstance})).then((yuiInstance=>{const tableData=getFormattedData(response);return yuiInstance.RecordsPaginatorView=Y.Base.create("my-paginator-view",yuiInstance.DataTable.Paginator.View,[],{_modelChange:function(e){var changed=e.changed;changed&&changed.totalItems&&this._updateControlsUI(e.target.get("page"))}}),new yuiInstance.DataTable({paginatorView:"RecordsPaginatorView",width:"1195px",columns:recordingData.columns,data:tableData,rowsPerPage:10,paginatorLocation:["header","footer"],autoSync:!0})})).then((dataTable=>{dataTable.render(tableId);const{registerEventListeners:registerEventListeners}=getDataTableFunctions(tableId,searchFormId,dataTable);return registerEventListeners(),dataTable})).then((dataTable=>(pendingPromise.resolve(),dataTable)));var lang};_exports.init=(tableId,searchFormId)=>{const pendingPromise=new _pending.default("mod_bigbluebuttonbn/recordings:init");fetchRecordingData(tableId).then((response=>setupDatatable(tableId,searchFormId,response))).then((()=>pendingPromise.resolve())).catch(_notification.exception)}})); /** * Ticks or unticks all checkboxes when clicking the Select all or Deselect all elements when viewing the response overview. * * @module mod_choicegroup/select_all_choices * @copyright 2017 Marcus Fabriczy <marcus.fabriczy@blackboard.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_choicegroup/select_all_choices",["jquery"],(function($){return{init:function(){$(".selectallnone a").on("click",(function(e){e.preventDefault(),$("#attemptsform").find("input:checkbox").prop("checked",$(this).data("selectInfo"))}))}}})); define("mod_choicegroup/choicegroupdatadisplay",["jquery","core/str"],(function($,str){return{init:function(){$(".choicegroup-memberdisplay").click((function(e){e.preventDefault(),$(".choicegroups-membersnames").toggleClass("hidden");var showusersstring=str.get_string("showgroupmembers","mod_choicegroup"),hideusersstring=str.get_string("hidegroupmembers","mod_choicegroup");$(".choicegroups-membersnames").is(":visible")?$.when(hideusersstring).done((function(hidestring){$(".choicegroup-memberdisplay").html(hidestring)})):$.when(showusersstring).done((function(showstring){$(".choicegroup-memberdisplay").html(showstring)}))})),$(".choicegroup-descriptiondisplay").click((function(e){e.preventDefault(),$(".choicegroups-descriptions").toggleClass("hidden");var hidedescriptionstring=str.get_string("hidedescription","mod_choicegroup"),showdescriptionstring=str.get_string("showdescription","mod_choicegroup");$(".choicegroups-descriptions").is(":visible")?$.when(hidedescriptionstring).done((function(hidestring){$(".choicegroup-descriptiondisplay").html(hidestring)})):$.when(showdescriptionstring).done((function(showstring){$(".choicegroup-descriptiondisplay").html(showstring)}))}))}}})); define("mod_data/selectpreset",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Javascript module to control the form responsible for selecting a preset. * * @module mod_data/selectpreset * @copyright 2021 Mihail Geshoski <mihail@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const selectors_presetRadioButton='input[name="fullname"]',selectors_selectPresetButton='input[name="selectpreset"]',selectors_selectedPresetRadioButton='input[name="fullname"]:checked';_exports.init=()=>{const radioButton=document.querySelectorAll(selectors_presetRadioButton);disableUsePresetButton(),radioButton.forEach((elem=>{elem.addEventListener("change",(function(event){event.preventDefault(),disableUsePresetButton()}))}))};const disableUsePresetButton=()=>{let selectPresetButton=document.querySelector(selectors_selectPresetButton);const selectedRadioButton=document.querySelector(selectors_selectedPresetRadioButton);selectedRadioButton?(selectPresetButton.removeAttribute("disabled"),selectPresetButton.classList.remove("btn-secondary"),selectPresetButton.classList.add("btn-primary"),selectPresetButton.setAttribute("data-presetname",selectedRadioButton.getAttribute("value")),selectPresetButton.setAttribute("data-cmid",selectedRadioButton.getAttribute("data-cmid"))):(selectPresetButton.setAttribute("disabled",!0),selectPresetButton.classList.remove("btn-primary"),selectPresetButton.classList.add("btn-secondary"),selectPresetButton.removeAttribute("data-presetname"),selectPresetButton.removeAttribute("data-cmid"))}})); define("mod_data/deletepreset",["exports","core/notification","core/prefetch","core/str","core/ajax","core/url"],(function(_exports,_notification,_prefetch,_str,_ajax,_url){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for deleting a database as a preset. * * @module mod_data/deletepreset * @copyright 2022 Amaia Anabitarte <amaia@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_ajax=_interopRequireDefault(_ajax),_url=_interopRequireDefault(_url);const selectors_deletePresetButton='[data-action="deletepreset"]';_exports.init=()=>{(0,_prefetch.prefetchStrings)("mod_data",["deleteconfirm","deletewarning"]),(0,_prefetch.prefetchStrings)("core",["delete"]),registerEventListeners()};const registerEventListeners=()=>{document.addEventListener("click",(event=>{const deleteOption=event.target.closest(selectors_deletePresetButton);deleteOption&&(event.preventDefault(),deletePresetConfirm(deleteOption))}))},deletePresetConfirm=deleteOption=>{const presetName=deleteOption.getAttribute("data-presetname"),dataId=deleteOption.getAttribute("data-dataid");_notification.default.saveCancelPromise((0,_str.get_string)("deleteconfirm","mod_data",presetName),(0,_str.get_string)("deletewarning","mod_data"),(0,_str.get_string)("delete","core")).then((()=>async function(dataId,presetName){var request={methodname:"mod_data_delete_saved_preset",args:{dataid:dataId,presetnames:{presetname:presetName}}};try{await _ajax.default.call([request])[0],window.location.href=_url.default.relativeUrl("mod/data/preset.php",{d:dataId},!1)}catch(error){_notification.default.exception(error)}}(dataId,presetName))).catch((()=>{}))}})); define("mod_data/editpreset",["exports","core_form/modalform","core/notification","core/str"],(function(_exports,_modalform,_notification,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for editing a database preset. * * @module mod_data/editpreset * @copyright 2022 Sara Arjona <sara@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const selectors_editPresetButton='[data-action="editpreset"]';_exports.init=()=>{registerEventListeners()};const registerEventListeners=()=>{document.addEventListener("click",(event=>{const editAction=event.target.closest(selectors_editPresetButton);editAction&&(event.preventDefault(),showEditPresetModal(editAction))}))},showEditPresetModal=editAction=>{const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("editpreset","mod_data")},formClass:"mod_data\\form\\save_as_preset",args:{d:editAction.getAttribute("data-dataid"),action:editAction.getAttribute("data-action"),presetname:editAction.getAttribute("data-presetname"),presetdescription:editAction.getAttribute("data-presetdescription")},saveButtonText:(0,_str.get_string)("save"),returnFocus:editAction});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{event.detail.result?window.location.reload():_notification.default.addNotification({type:"error",message:event.detail.errors.join("<br>")})})),modalForm.show()}})); define("mod_data/importmappingdialogue",["exports","core/notification","core/ajax","core/url","core/templates","core/modal_factory","core/prefetch","core/str"],(function(_exports,_notification,_ajax,_url,_templates,_modal_factory,_prefetch,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for deleting a database as a preset. * * @module mod_data/importmappingdialogue * @copyright 2022 Amaia Anabitarte <amaia@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_ajax=_interopRequireDefault(_ajax),_url=_interopRequireDefault(_url),_templates=_interopRequireDefault(_templates),_modal_factory=_interopRequireDefault(_modal_factory),(0,_prefetch.prefetchStrings)("mod_data",["mapping:dialogtitle:usepreset"]);const selectors_selectPresetButton='input[name="selectpreset"]';_exports.init=()=>{registerEventListeners()};const registerEventListeners=()=>{document.addEventListener("click",(event=>{const usepreset=event.target.closest(selectors_selectPresetButton);usepreset&&(event.preventDefault(),showMappingDialogue(usepreset))}))},showMappingDialogue=usepreset=>{const presetName=usepreset.dataset.presetname,cmId=usepreset.dataset.cmid;getMappingInformation(cmId,presetName).then((result=>(result.data&&result.data.needsmapping?buildModal({title:(0,_str.get_string)("mapping:dialogtitle:usepreset","mod_data",result.data.presetname),body:_templates.default.render("mod_data/fields_mapping_body",result.data),footer:_templates.default.render("mod_data/fields_mapping_footer",getMappingButtons(cmId,presetName)),large:!0}):window.location.href=_url.default.relativeUrl("mod/data/field.php",{id:cmId,mode:"usepreset",fullname:presetName},!1),!0))).catch(_notification.default.exception)},buildModal=params=>_modal_factory.default.create({...params,type:_modal_factory.default.types.DEFAULT}).then((modal=>(modal.show(),modal.showFooter(),modal.registerCloseOnCancel(),modal))).catch(_notification.default.exception),getMappingButtons=(cmId,presetName)=>{const data={};return data.mapfieldsbutton=_url.default.relativeUrl("mod/data/field.php",{id:cmId,fullname:presetName,mode:"usepreset",action:"select"},!1),data.applybutton=_url.default.relativeUrl("mod/data/field.php",{id:cmId,fullname:presetName,mode:"usepreset",action:"notmapping"},!1),data},getMappingInformation=(cmId,presetName)=>{const request={methodname:"mod_data_get_mapping_information",args:{cmid:cmId,importedpreset:presetName}};return _ajax.default.call([request])[0]}})); define("mod_data/importpresets",["exports","core_form/modalform","core/notification","core/str"],(function(_exports,_modalform,_notification,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for importing presets. * * @module mod_data/importpreset * @copyright 2022 Laurent David <laurent.david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const selectors_importPresetButton='[data-action="importpresets"]';_exports.init=()=>{document.addEventListener("click",(event=>{const importPresetButton=event.target.closest(selectors_importPresetButton);if(!importPresetButton)return;event.preventDefault();const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("importpreset","mod_data")},formClass:"mod_data\\form\\import_presets",args:{cmid:importPresetButton.dataset.dataid},saveButtonText:(0,_str.get_string)("importandapply","mod_data")});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{event.detail.result?window.location.assign(event.detail.url):_notification.default.addNotification({type:"error",message:event.detail.errors.join("<br>")})})),modalForm.show()}))}})); define("mod_data/resetalltemplates",["exports","core/notification","core/prefetch","core/str"],(function(_exports,_notification,_prefetch,_str){var obj; /** * Javascript module for reseting all templates. * * @module mod_data/resetalltemplates * @copyright 2022 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj};const selectors_resetAllTemplatesAction='[data-action="resetalltemplates"]';_exports.init=()=>{(0,_prefetch.prefetchStrings)("mod_data",["resetalltemplatesconfirmtitle","resetalltemplatesconfirm"]),(0,_prefetch.prefetchStrings)("core",["reset"]),registerEventListeners()};const registerEventListeners=()=>{document.addEventListener("click",(event=>{const actionLink=event.target.closest(selectors_resetAllTemplatesAction);actionLink&&(event.preventDefault(),resetAllTemplatesConfirm(actionLink))}))},resetAllTemplatesConfirm=async actionLink=>{try{await _notification.default.saveCancelPromise((0,_str.get_string)("resetalltemplatesconfirmtitle","mod_data"),(0,_str.get_string)("resetalltemplatesconfirm","mod_data"),(0,_str.get_string)("reset","core")),window.location=actionLink.href}catch(error){return}}})); define("mod_data/saveaspreset",["exports","core_form/modalform","core/notification","core/str"],(function(_exports,_modalform,_notification,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for saving a database as a preset. * * @module mod_data/saveaspreset * @copyright 2021 Mihail Geshoski <mihail@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const selectors_saveAsPresetButton='[data-action="saveaspreset"]';_exports.init=()=>{document.addEventListener("click",(event=>{const saveAsPresetButton=event.target.closest(selectors_saveAsPresetButton);if(!saveAsPresetButton)return;event.preventDefault();const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("savedataaspreset","mod_data")},formClass:"mod_data\\form\\save_as_preset",args:{d:saveAsPresetButton.dataset.dataid},saveButtonText:(0,_str.get_string)("save"),returnFocus:saveAsPresetButton});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{event.detail.result?window.location.reload():_notification.default.addNotification({type:"error",message:event.detail.errors.join("<br>")})})),modalForm.show()}))}})); define("mod_data/templateseditor",["exports","core/str","core/prefetch","core/url","core/notification","core/templates"],(function(_exports,_str,_prefetch,_url,_notification,_templates){var obj; /** * Javascript module to control the template editor. * * @module mod_data/templateseditor * @copyright 2021 Mihail Geshoski <mihail@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_templates=(obj=_templates)&&obj.__esModule?obj:{default:obj},(0,_prefetch.prefetchStrings)("admin",["confirmation"]),(0,_prefetch.prefetchStrings)("mod_data",["resettemplateconfirmtitle","enabletemplateeditorcheck","editorenable"]),(0,_prefetch.prefetchStrings)("core",["reset"]);const selectors_toggleTemplateEditor='input[name="useeditor"]',selectors_resetTemplate='input[name="defaultform"]',selectors_resetAllTemplates='input[name="resetall"]',selectors_resetButton='input[name="resetbutton"]',selectors_resetAllCheck='input[name="resetallcheck"]',selectors_editForm="#edittemplateform",registerResetButton=mode=>{const editForm=document.querySelector(selectors_editForm),resetButton=document.querySelector(selectors_resetButton),resetTemplate=document.querySelector(selectors_resetTemplate),resetAllTemplates=document.querySelector(selectors_resetAllTemplates);resetButton&&resetTemplate&&editForm&&(resetButton.addEventListener("click",(async event=>{event.preventDefault();const params={resetallname:"resetallcheck",templatename:await(0,_str.get_string)(mode,"mod_data")};(0,_notification.saveCancel)((0,_str.get_string)("resettemplateconfirmtitle","mod_data"),_templates.default.render("mod_data/template_editor_resetmodal",params),(0,_str.get_string)("reset","core"),(()=>{resetTemplate.value="true",editForm.submit()}),null,{triggerElement:event.target})})),resetAllTemplates&&document.addEventListener("change",(event=>{event.target.matches(selectors_resetAllCheck)&&(resetAllTemplates.value=event.target.checked?"true":"")})))},registerEditorToggler=(instanceId,mode)=>{const toggleTemplateEditor=document.querySelector(selectors_toggleTemplateEditor);toggleTemplateEditor&&toggleTemplateEditor.addEventListener("click",(async event=>{event.preventDefault();event.target.checked?(0,_notification.saveCancel)((0,_str.get_string)("confirmation","admin"),(0,_str.get_string)("enabletemplateeditorcheck","mod_data"),(0,_str.get_string)("editorenable","mod_data"),(()=>{window.location=(0,_url.relativeUrl)("/mod/data/templates.php",{d:instanceId,mode:mode,useeditor:!0})}),null,{triggerElement:event.target}):window.location=(0,_url.relativeUrl)("/mod/data/templates.php",{d:instanceId,mode:mode,useeditor:!1})}))};_exports.init=(instanceId,mode)=>{((instanceId,mode)=>{registerResetButton(mode),registerEditorToggler(instanceId,mode)})(instanceId,mode)}})); define("mod_feedback/edit",["jquery","core/ajax","core/str","core/notification"],(function($,ajax,str,notification){var manager={deleteItem:function(e){e.preventDefault();var targetUrl=$(e.currentTarget).attr("href");str.get_strings([{key:"confirmation",component:"admin"},{key:"confirmdeleteitem",component:"mod_feedback"},{key:"yes",component:"moodle"},{key:"no",component:"moodle"}]).then((function(s){notification.confirm(s[0],s[1],s[2],s[3],(function(){window.location=targetUrl}))})).catch()},setup:function(){$("body").delegate('[data-action="delete"]',"click",manager.deleteItem)}};return{setup:manager.setup}})); define("mod_feedback/createtemplate",["exports","core_form/modalform","core/notification","core/str","core/toast"],(function(_exports,_modalform,_notification,_str,_toast){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for saving a new template. * * @module mod_feedback/createtemplate * @copyright 2021 Peter Dias * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const selectors_modaltrigger='[data-action="createtemplate"]';_exports.init=()=>{document.querySelector(selectors_modaltrigger).addEventListener("click",(event=>{event.preventDefault();const ele=event.currentTarget,modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("save_as_new_template","mod_feedback")},formClass:"mod_feedback\\form\\create_template_form",args:{id:ele.dataset.dataid},saveButtonText:(0,_str.get_string)("save","core")});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{event.detail.result?(0,_str.get_string)("template_saved","feedback").then(_toast.add).catch():(0,_str.get_string)("saving_failed","feedback").then((string=>_notification.default.addNotification({type:"error",message:string}))).catch()})),modalForm.show()}))}})); define("mod_feedback/usetemplate",["exports","core_form/modalform","core/notification","core/str"],(function(_exports,_modalform,_notification,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for using an existing template * * @module mod_feedback/usetemplate * @copyright 2021 Peter Dias * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const selectors_modaltrigger='[data-action="usetemplate"]';_exports.init=()=>{const trigger=document.querySelector(selectors_modaltrigger);trigger.addEventListener("click",(event=>{event.preventDefault();const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("use_this_template","mod_feedback")},formClass:"mod_feedback\\form\\use_template_form",args:{id:trigger.getAttribute("data-dataid"),templateid:trigger.getAttribute("data-templateid")},saveButtonText:(0,_str.get_string)("save","core")});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{event.detail.result?window.location.assign(event.detail.url):_notification.default.addNotification({type:"error",message:(0,_str.get_string)("saving_failed","mod_feedback")})})),modalForm.show()}))}})); /** * Handle discussion subscription toggling on a discussion list in * the forum view. * * @module mod_forum/favourite_toggle * @copyright 2019 Peter Dias <peter@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/favourite_toggle",["jquery","core/templates","core/notification","mod_forum/repository","mod_forum/selectors","core/str"],(function($,Templates,Notification,Repository,Selectors,String){return{init:function(root,preventDefault,callback){root.on("click",Selectors.favourite.toggle,(function(e){var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),subscriptionState=toggleElement.data("targetstate");Repository.setFavouriteDiscussionState(forumId,discussionId,subscriptionState).then((function(context){return callback(toggleElement,context)})).then((function(){return String.get_string("favouriteupdated","forum").done((function(s){return Notification.addNotification({message:s,type:"info"})}))})).catch(Notification.exception),preventDefault&&e.preventDefault()}))}}})); /** * Enrolled user selector module. * * @module mod_forum/form-user-selector * @copyright 2019 Shamim Rezaie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/form-user-selector",["jquery","core/ajax","core/templates"],(function($,Ajax,Templates){return{processResults:function(selector,results){var users=[];return $.each(results,(function(index,user){users.push({value:user.id,label:user._label})})),users},transport:function(selector,query,success,failure){var courseid=$(selector).attr("courseid");Ajax.call([{methodname:"core_enrol_search_users",args:{courseid:courseid,search:query,searchanywhere:!0,page:0,perpage:30}}])[0].then((function(results){var promises=[],i=0;return $.each(results,(function(index,user){promises.push(Templates.render("mod_forum/form-user-selector-suggestion",user))})),$.when.apply($.when,promises).then((function(){var args=arguments;$.each(results,(function(index,user){user._label=args[i],i++})),success(results)}))})).fail(failure)}}})); /** * Events for the forum activity. * * @module mod_forum/forum_events * @copyright 2019 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/forum_events",[],(function(){return{SUBSCRIPTION_TOGGLED:"mod_forum/subscription_toggle:subscriptionToggled"}})); define("mod_forum/grades/expandconversation",["exports","./grader/selectors","mod_forum/repository","core/notification","core/templates","core/modal_factory","core/modal_events"],(function(_exports,ForumSelectors,_repository,_notification,_templates,Modal,ModalEvents){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * This module handles the creation of a Modal that shows the user's post in context of the entire discussion. * * @module mod_forum/grades/expandconversation * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.registerEventListeners=void 0,ForumSelectors=_interopRequireWildcard(ForumSelectors),_repository=_interopRequireDefault(_repository),_templates=_interopRequireDefault(_templates),Modal=_interopRequireWildcard(Modal),ModalEvents=_interopRequireWildcard(ModalEvents);_exports.registerEventListeners=rootNode=>{rootNode.addEventListener("click",(e=>{const rootNode=e.target.closest(ForumSelectors.expandConversation);if(rootNode){e.preventDefault();try{!async function(rootNode){let{focusOnClose:focusOnClose=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const postId=rootNode.dataset.postid,discussionId=rootNode.dataset.discussionid,discussionName=rootNode.dataset.name,experimentalDisplayMode="1"==rootNode.dataset.experimentalDisplayMode,[allPosts,modal]=await Promise.all([_repository.default.getDiscussionPosts(parseInt(discussionId)),Modal.create({title:discussionName,large:!0,type:Modal.types.CANCEL})]),postsById=new Map(allPosts.posts.map((post=>(post.readonly=!0,post.hasreplies=!1,post.replies=[],[post.id,post]))));let posts=[];allPosts.posts.forEach((post=>{if(post.parentid){const parent=postsById.get(post.parentid);parent?(post.parentauthorname=parent.author.fullname,parent.hasreplies=!0,parent.replies.push(post)):posts.push(post)}else posts.push(post)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy();try{focusOnClose.focus()}catch(e){}})),modal.getRoot().on(ModalEvents.bodyRendered,(()=>{const relevantPost=modal.getRoot()[0].querySelector("#p".concat(postId));relevantPost&&relevantPost.scrollIntoView({behavior:"smooth"})})),modal.show();const templatePromise=_templates.default.render("mod_forum/grades/grader/discussion/post_modal",{posts:posts,experimentaldisplaymode:experimentalDisplayMode});modal.setBody(templatePromise)}(rootNode,{focusOnClose:e.target})}catch(err){(0,_notification.exception)(err)}}}))}})); define("mod_forum/grades/grader",["exports","./grader/selectors","mod_forum/repository","core/templates","../local/grades/grader","core/notification","core_course/repository","core/url"],(function(_exports,Selectors,_repository,_templates,Grader,_notification,_repository2,_url){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * This module will tie together all of the different calls the gradable module will make. * * @module mod_forum/grades/grader * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.registerLaunchListeners=void 0,Selectors=_interopRequireWildcard(Selectors),_repository=_interopRequireDefault(_repository),_templates=_interopRequireDefault(_templates),Grader=_interopRequireWildcard(Grader),_notification=_interopRequireDefault(_notification),_repository2=_interopRequireDefault(_repository2);const templateNames_contentRegion="mod_forum/grades/grader/discussion/posts",getContentForUserIdFunction=(cmid,experimentalDisplayMode)=>userid=>_repository.default.getDiscussionByUserID(userid,cmid).then((context=>(context.discussions=context.discussions.map(discussionPostMapper),context.experimentaldisplaymode=!!experimentalDisplayMode,_templates.default.render(templateNames_contentRegion,context)))).catch(_notification.default.exception),getUsersForCmidFunction=(cmid,groupID,onlyActive)=>async()=>(await _repository2.default.getUsersFromCourseModuleID(cmid,groupID,onlyActive)).users,findGradableNode=node=>node.closest(Selectors.gradableItem),discussionPostMapper=discussion=>{const parentMap=new Map;discussion.posts.parentposts.forEach((post=>parentMap.set(post.id,post)));const userPosts=discussion.posts.userposts.map((post=>{post.readonly=!0,post.hasreplies=!1,post.replies=[];const parent=post.parentid?parentMap.get(post.parentid):null;return parent&&(parent.hasreplies=!1,parent.replies=[],parent.readonly=!0,post.parentauthorname=parent.author.fullname),{parent:parent,post:post}}));return{...discussion,posts:userPosts}};_exports.registerLaunchListeners=()=>{document.addEventListener("click",(async e=>{if(e.target.matches(Selectors.launch)){const rootNode=findGradableNode(e.target);if(!rootNode)throw Error("Unable to find a gradable item");if(!rootNode.matches(Selectors.gradableItems.wholeForum))throw Error("Unable to find a valid gradable item");e.preventDefault();try{await async function(rootNode){let{focusOnClose:focusOnClose=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const data=rootNode.dataset,gradingPanelFunctions=await Grader.getGradingPanelFunctions("mod_forum",data.contextid,data.gradingComponent,data.gradingComponentSubtype,data.gradableItemtype),groupID=data.group?data.group:0,onlyActive=data.gradeOnlyActiveUsers;await Grader.launch(getUsersForCmidFunction(data.cmid,groupID,onlyActive),getContentForUserIdFunction(data.cmid,"1"==data.experimentalDisplayMode),gradingPanelFunctions.getter,gradingPanelFunctions.setter,{groupid:data.groupid,initialUserId:data.initialuserid,moduleName:data.name,courseName:data.courseName,courseUrl:(0,_url.relativeUrl)("/course/view.php",{id:data.courseId}),sendStudentNotifications:data.sendStudentNotifications,focusOnClose:focusOnClose})}(rootNode,{focusOnClose:e.target})}catch(error){_notification.default.exception(error)}}if(e.target.matches(Selectors.viewGrade)){e.preventDefault();const rootNode=findGradableNode(e.target);if(!rootNode)throw Error("Unable to find a gradable item");if(!rootNode.matches(Selectors.gradableItems.wholeForum))throw Error("Unable to find a valid gradable item");e.preventDefault();try{await async function(rootNode){let{focusOnClose:focusOnClose=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const data=rootNode.dataset,gradingPanelFunctions=await Grader.getGradingPanelFunctions("mod_forum",data.contextid,data.gradingComponent,data.gradingComponentSubtype,data.gradableItemtype);await Grader.view(gradingPanelFunctions.getter,data.userid,data.name,{focusOnClose:focusOnClose})}(rootNode,{focusOnClose:e.target})}catch(error){_notification.default.exception(error)}}}))}})); define("mod_forum/grades/grader/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={launch:'[data-grade-action="launch"]',gradableItem:"[data-gradable-itemtype]",gradableItems:{wholeForum:'[data-gradable-itemtype="forum"]'},expandConversation:'[data-action="view-context"]',posts:'[data-region="posts"]',viewGrade:'[data-grade-action="view"]'},_exports.default})); define("mod_forum/local/grades/local/grader/gradingpanel",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{}; /** * Grading panel functions. * * @module mod_forum/local/grades/local/grader/gradingpanel * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */return _exports.default=async(component,context,gradingComponent,gradingSubtype,itemName)=>{let gradingMethodHandler="".concat(gradingComponent,"/grades/grader/gradingpanel");gradingSubtype&&(gradingMethodHandler+="/".concat(gradingSubtype));const GradingMethod=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require([gradingMethodHandler],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require(gradingMethodHandler)):Promise.resolve(_systemImportTransformerGlobalIdentifier[gradingMethodHandler]));return{getter:userId=>GradingMethod.fetchCurrentGrade(component,context,itemName,userId),setter:(userId,notifyStudent,formData)=>GradingMethod.storeCurrentGrade(component,context,itemName,userId,notifyStudent,formData)}},_exports.default})); define("mod_forum/local/grades/local/grader/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0; /** * Define all of the selectors we will be using on the grading interface. * * @module mod_forum/local/grades/local/grader/selectors * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const getDataSelector=(name,value)=>"[data-".concat(name,'="').concat(value,'"]');var _default={buttons:{toggleFullscreen:getDataSelector("action","togglefullscreen"),closeGrader:getDataSelector("action","closegrader"),collapseGradingDrawer:getDataSelector("action","collapse-grading-drawer"),saveGrade:getDataSelector("action","savegrade"),selectUser:getDataSelector("action","select-user"),toggleSearch:getDataSelector("action","toggle-search")},regions:{bodyContainer:getDataSelector("region","body-container"),moduleContainer:getDataSelector("region","module_content_container"),moduleReplace:getDataSelector("region","module_content"),pickerRegion:getDataSelector("region","user_picker"),gradingInfoContainer:getDataSelector("region","grading-info-container"),gradingPanel:getDataSelector("region","grade"),gradingPanelContainer:getDataSelector("region","grading-panel-container"),gradingPanelErrors:getDataSelector("region","grade-errors"),searchResultsContainer:getDataSelector("region","search-results-container"),statusContainer:getDataSelector("region","status-container"),userSearchContainer:getDataSelector("region","user-search-container"),userSearchInput:getDataSelector("region","user-search-input")},values:{sendStudentNotifications:'[data-region="notification"] input[type="radio"]:checked'}};return _exports.default=_default,_exports.default})); define("mod_forum/local/grades/local/grader/user_picker/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={regions:{currentUser:'[data-region="user_picker/current_user"]',userRegion:'[data-region="user_picker/user"]'},actions:{changeUser:'[data-action="change-user"]'}},_exports.default})); define("mod_forum/local/grades/local/grader/user_picker",["exports","core/templates","./user_picker/selectors","core/str"],(function(_exports,_templates,_selectors,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * This module will tie together all of the different calls the gradable module will make. * * @module mod_forum/local/grades/local/grader/user_picker * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=_interopRequireDefault(_templates),_selectors=_interopRequireDefault(_selectors);class UserPicker{constructor(userList,showUserCallback,preChangeUserCallback){this.userList=userList,this.showUserCallback=showUserCallback,this.preChangeUserCallback=preChangeUserCallback,this.currentUserIndex=0,this.render=this.render.bind(this),this.setUserId=this.setUserId.bind(this)}setUserId(userId){const userIndex=this.userList.findIndex((user=>user.id===parseInt(userId)));if(-1===userIndex)throw Error("User with id ".concat(userId," not found"));this.currentUserIndex=userIndex}async render(){this.root=document.createElement("div");const{html:html,js:js}=await this.renderNavigator();_templates.default.replaceNodeContents(this.root,html,js),await this.showUser(this.currentUser),this.registerEventListeners()}renderNavigator(){return _templates.default.renderForPromise("".concat("mod_forum/local/grades/local/grader","/user_picker"),{})}renderUserChange(context){return _templates.default.renderForPromise("".concat("mod_forum/local/grades/local/grader","/user_picker/user"),context)}async showUser(user){const[{html:html,js:js}]=await Promise.all([this.renderUserChange(user),this.showUserCallback(user)]),userRegion=this.root.querySelector(_selectors.default.regions.userRegion);_templates.default.replaceNodeContents(userRegion,html,js);this.root.querySelector(_selectors.default.regions.currentUser).textContent=await(0,_str.get_string)("nowgradinguser","mod_forum",user.fullname)}registerEventListeners(){this.root.addEventListener("click",(async e=>{const button=e.target.closest(_selectors.default.actions.changeUser);if(button){(await this.preChangeUserCallback(this.currentUser)).failed||(this.updateIndex(parseInt(button.dataset.direction)),await this.showUser(this.currentUser))}}))}updateIndex(direction){return this.currentUserIndex+=direction,this.currentUserIndex<0?this.currentUserIndex=this.userList.length-1:this.currentUserIndex>this.userList.length-1&&(this.currentUserIndex=0),this.currentUserIndex}get currentUser(){return{...this.userList[this.currentUserIndex],total:this.userList.length,displayIndex:this.currentUserIndex+1}}get rootNode(){return this.root}}return _exports.default=async function(users,showUserCallback,preChangeUserCallback){let{initialUserId:initialUserId=null}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const userPicker=new UserPicker(users,showUserCallback,preChangeUserCallback);return initialUserId&&userPicker.setUserId(initialUserId),await userPicker.render(),userPicker},_exports.default})); define("mod_forum/local/grades/grader",["exports","core/templates","./local/grader/selectors","./local/grader/user_picker","mod_forum/local/layout/fullscreen","./local/grader/gradingpanel","core/toast","core/notification","core/str","core_grades/grades/grader/gradingpanel/normalise","core/loadingicon","core/utils","core_grades/grades/grader/gradingpanel/comparison","core/modal_factory","core/modal_events","core/pubsub","core/drawer_events"],(function(_exports,_templates,_selectors,_user_picker,_fullscreen,_gradingpanel,_toast,_notification,_str,_normalise,_loadingicon,_utils,_comparison,Modal,ModalEvents,_pubsub,_drawer_events){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * This module will tie together all of the different calls the gradable module will make. * * @module mod_forum/local/grades/grader * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"getGradingPanelFunctions",{enumerable:!0,get:function(){return _gradingpanel.default}}),_exports.view=_exports.launch=void 0,_templates=_interopRequireDefault(_templates),_selectors=_interopRequireDefault(_selectors),_user_picker=_interopRequireDefault(_user_picker),_gradingpanel=_interopRequireDefault(_gradingpanel),Modal=_interopRequireWildcard(Modal),ModalEvents=_interopRequireWildcard(ModalEvents),_drawer_events=_interopRequireDefault(_drawer_events);const templateNames_grader={app:"mod_forum/local/grades/grader",gradingPanel:{error:"mod_forum/local/grades/local/grader/gradingpanel/error"},searchResults:"mod_forum/local/grades/local/grader/user_picker/user_search",status:"mod_forum/local/grades/local/grader/status"},displayUserPicker=(root,html)=>{const pickerRegion=root.querySelector(_selectors.default.regions.pickerRegion);_templates.default.replaceNodeContents(pickerRegion,html,"")},fetchContentFromRender=(html,js)=>[html,js],getUpdateUserContentFunction=(root,getContentForUser,getGradeForUser,saveGradeForUser)=>{let firstLoad=!0;return async user=>{const spinner=firstLoad?null:(0,_loadingicon.addIconToContainerWithPromise)(root),[[html,js],userGrade]=await Promise.all([getContentForUser(user.id).then(fetchContentFromRender),getGradeForUser(user.id)]);_templates.default.replaceNodeContents(root.querySelector(_selectors.default.regions.moduleReplace),html,js);const[gradingPanelHtml,gradingPanelJS]=await _templates.default.render(userGrade.templatename,userGrade.grade).then(fetchContentFromRender),panelContainer=root.querySelector(_selectors.default.regions.gradingPanelContainer),panel=panelContainer.querySelector(_selectors.default.regions.gradingPanel);_templates.default.replaceNodeContents(panel,gradingPanelHtml,gradingPanelJS);const form=panel.querySelector("form");return(0,_comparison.fillInitialValues)(form),form.addEventListener("submit",(event=>{saveGradeForUser(user),event.preventDefault()})),panelContainer.scrollTop=0,firstLoad=!1,spinner&&spinner.resolve(),userGrade}},hideSearchResultContainer=(bodyContainer,userPickerContainer,searchResultsContainer)=>{bodyContainer.classList.remove("hidden"),userPickerContainer.classList.remove("hidden"),searchResultsContainer.classList.add("hidden")},hideUserSearchInput=(toggleSearchButton,searchContainer,searchInput)=>{searchContainer.classList.add("collapsed"),toggleSearchButton.setAttribute("aria-expanded","false"),toggleSearchButton.classList.add("collapse"),toggleSearchButton.classList.remove("expand"),toggleSearchButton.focus();searchContainer.parentElement.querySelector(_selectors.default.regions.gradingInfoContainer).removeAttribute("aria-hidden");const collapseGradingDrawer=searchContainer.parentElement.querySelector(_selectors.default.buttons.collapseGradingDrawer);collapseGradingDrawer.removeAttribute("aria-hidden"),collapseGradingDrawer.setAttribute("tabindex","0"),searchInput.value=""},renderSearchResults=async(searchResultsContainer,users)=>{const{html:html,js:js}=await _templates.default.renderForPromise(templateNames_grader.searchResults,{users:users});_templates.default.replaceNodeContents(searchResultsContainer,html,js)},registerEventListeners=(graderLayout,userPicker,saveGradeFunction,userList)=>{const graderContainer=graderLayout.getContainer(),toggleSearchButton=graderContainer.querySelector(_selectors.default.buttons.toggleSearch),searchInputContainer=graderContainer.querySelector(_selectors.default.regions.userSearchContainer),searchInput=searchInputContainer.querySelector(_selectors.default.regions.userSearchInput),bodyContainer=graderContainer.querySelector(_selectors.default.regions.bodyContainer),userPickerContainer=graderContainer.querySelector(_selectors.default.regions.pickerRegion),searchResultsContainer=graderContainer.querySelector(_selectors.default.regions.searchResultsContainer);graderContainer.addEventListener("click",(e=>{if(e.target.closest(_selectors.default.buttons.toggleFullscreen))return e.stopImmediatePropagation(),e.preventDefault(),void graderLayout.toggleFullscreen();if(e.target.closest(_selectors.default.buttons.closeGrader))return e.stopImmediatePropagation(),e.preventDefault(),void graderLayout.close();if(e.target.closest(_selectors.default.buttons.saveGrade)&&saveGradeFunction(userPicker.currentUser),e.target.closest(_selectors.default.buttons.toggleSearch))return void("true"===toggleSearchButton.getAttribute("aria-expanded")?(hideUserSearchInput(toggleSearchButton,searchInputContainer,searchInput),hideSearchResultContainer(bodyContainer,userPickerContainer,searchResultsContainer),searchResultsContainer.innerHTML=""):(((toggleSearchButton,searchContainer,searchInput)=>{searchContainer.classList.remove("collapsed"),toggleSearchButton.setAttribute("aria-expanded","true"),toggleSearchButton.classList.add("expand"),toggleSearchButton.classList.remove("collapse"),searchContainer.parentElement.querySelector(_selectors.default.regions.gradingInfoContainer).setAttribute("aria-hidden","true");const collapseGradingDrawer=searchContainer.parentElement.querySelector(_selectors.default.buttons.collapseGradingDrawer);collapseGradingDrawer.setAttribute("aria-hidden","true"),collapseGradingDrawer.setAttribute("tabindex","-1"),searchInput.focus()})(toggleSearchButton,searchInputContainer,searchInput),((bodyContainer,userPickerContainer,searchResultsContainer)=>{bodyContainer.classList.add("hidden"),userPickerContainer.classList.add("hidden"),searchResultsContainer.classList.remove("hidden")})(bodyContainer,userPickerContainer,searchResultsContainer),renderSearchResults(searchResultsContainer,userList)));const selectUserButton=e.target.closest(_selectors.default.buttons.selectUser);if(selectUserButton){const userId=selectUserButton.getAttribute("data-userid"),user=userList.find((user=>user.id==userId));userPicker.setUserId(userId),userPicker.showUser(user),hideUserSearchInput(toggleSearchButton,searchInputContainer,searchInput),hideSearchResultContainer(bodyContainer,userPickerContainer,searchResultsContainer),searchResultsContainer.innerHTML=""}})),searchInput.addEventListener("input",(0,_utils.debounce)((()=>{const users=((userList,searchTerm)=>""===searchTerm?userList:(searchTerm=searchTerm.toLowerCase(),userList.filter((user=>user.fullname.toLowerCase().includes(searchTerm)))))(userList,searchInput.value);renderSearchResults(searchResultsContainer,users)}),300)),(0,_pubsub.subscribe)(_drawer_events.default.DRAWER_HIDDEN,(drawerRoot=>{drawerRoot[0].querySelector(_selectors.default.regions.gradingPanel)&&setContentContainerMargin(graderContainer,0)})),(0,_pubsub.subscribe)(_drawer_events.default.DRAWER_SHOWN,(drawerRoot=>{const gradingPanel=drawerRoot[0];gradingPanel.querySelector(_selectors.default.regions.gradingPanel)&&setContentContainerMargin(graderContainer,gradingPanel.offsetWidth)}))},setContentContainerMargin=(graderContainer,rightMargin)=>{const contentContainer=graderContainer.querySelector(_selectors.default.regions.moduleContainer);contentContainer&&(contentContainer.style.marginRight="".concat(rightMargin,"px"))},getSaveUserGradeFunction=(root,setGradeForUser)=>async user=>{try{root.querySelector(_selectors.default.regions.gradingPanelErrors).innerHTML="";const result=await setGradeForUser(user.id,root.querySelector(_selectors.default.values.sendStudentNotifications).value,root.querySelector(_selectors.default.regions.gradingPanel));return result.success&&(0,_toast.add)(await(0,_str.get_string)("grades:gradesavedfor","mod_forum",user)),result.failed&&displayGradingError(root,user,result.error),result}catch(err){return displayGradingError(root,user,err),(0,_normalise.failedUpdate)(err)}},displayGradingError=async(root,user,err)=>{const[{html:html,js:js},errorString]=await Promise.all([_templates.default.renderForPromise(templateNames_grader.gradingPanel.error,{error:err}),await(0,_str.get_string)("grades:gradesavefailed","mod_forum",{error:err.message,...user})]);_templates.default.replaceNodeContents(root.querySelector(_selectors.default.regions.gradingPanelErrors),html,js),(0,_toast.add)(errorString,{type:"warning"})};_exports.launch=async function(getListOfUsers,getContentForUser,getGradeForUser,setGradeForUser){let{initialUserId:initialUserId=null,moduleName:moduleName,courseName:courseName,courseUrl:courseUrl,sendStudentNotifications:sendStudentNotifications,focusOnClose:focusOnClose=null}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const userList=await getListOfUsers();if(!userList.length)return void(0,_notification.addNotification)({message:await(0,_str.get_string)("nouserstograde","core_grades"),type:"error"});const[graderLayout,{html:html,js:js}]=await Promise.all([(0,_fullscreen.createLayout)({fullscreen:!1,showLoader:!1,focusOnClose:focusOnClose}),_templates.default.renderForPromise(templateNames_grader.app,{moduleName:moduleName,courseName:courseName,courseUrl:courseUrl,drawer:{show:!0},defaultsendnotifications:sendStudentNotifications})]),graderContainer=graderLayout.getContainer(),saveGradeFunction=getSaveUserGradeFunction(graderContainer,setGradeForUser);_templates.default.replaceNodeContents(graderContainer,html,js);const updateUserContent=getUpdateUserContentFunction(graderContainer,getContentForUser,getGradeForUser,saveGradeFunction),userIds=userList.map((user=>user.id)),statusContainer=graderContainer.querySelector(_selectors.default.regions.statusContainer),userPicker=await(0,_user_picker.default)(userList,(async user=>{const renderContext={status:(await updateUserContent(user)).hasgrade,index:userIds.indexOf(user.id)+1,total:userList.length};_templates.default.render(templateNames_grader.status,renderContext).then((html=>(statusContainer.innerHTML=html,html))).catch()}),saveGradeFunction,{initialUserId:initialUserId});registerEventListeners(graderLayout,userPicker,saveGradeFunction,userList),displayUserPicker(graderContainer,userPicker.rootNode)};_exports.view=async function(getGradeForUser,userid,moduleName){let{focusOnClose:focusOnClose=null}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const[userGrade,modal]=await Promise.all([getGradeForUser(userid),Modal.create({title:moduleName,large:!0,type:Modal.types.CANCEL})]),spinner=(0,_loadingicon.addIconToContainerWithPromise)(modal.getRoot());modal.getRoot().on(ModalEvents.hidden,(function(){if(modal.destroy(),focusOnClose)try{focusOnClose.focus()}catch(e){}})),modal.show();const output=document.createElement("div"),{html:html,js:js}=await _templates.default.renderForPromise("mod_forum/local/grades/view_grade",userGrade);_templates.default.replaceNodeContents(output,html,js);const[gradeHTML,gradeJS]=await renderGradeTemplate(userGrade),gradeReplace=output.querySelector('[data-region="grade-template"]');_templates.default.replaceNodeContents(gradeReplace,gradeHTML,gradeJS),modal.setBody(output.outerHTML),spinner.resolve()};const renderGradeTemplate=async userGrade=>{const{html:html,js:js}=await _templates.default.renderForPromise(userGrade.templatename,userGrade.grade);return[html,js]}})); define("mod_forum/local/layout/fullscreen",["exports","core/loadingicon","core/toast","core/local/aria/focuslock"],(function(_exports,_loadingicon,_toast,FocusLockManager){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.createLayout=void 0,FocusLockManager=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Full screen window layout. * * @module mod_forum/local/layout/fullscreen * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(FocusLockManager);_exports.createLayout=function(){let{fullscreen:fullscreen=!0,showLoader:showLoader=!1,focusOnClose:focusOnClose=null}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const container=document.createElement("div");document.body.append(container),container.classList.add("layout"),container.classList.add("fullscreen"),container.setAttribute("role","application"),(0,_toast.addToastRegion)(container),lockBodyScroll(),FocusLockManager.trapFocus(container);const helpers=getLayoutHelpers(container,FocusLockManager,focusOnClose);return showLoader&&helpers.showLoadingIcon(),fullscreen&&helpers.requestFullscreen(),helpers};const getLayoutHelpers=(layoutNode,FocusLockManager,focusOnClose)=>{const contentNode=document.createElement("div");layoutNode.append(contentNode);const loadingNode=document.createElement("div");layoutNode.append(loadingNode);const requestFullscreen=()=>{layoutNode.requestFullscreen?layoutNode.requestFullscreen():layoutNode.msRequestFullscreen?layoutNode.msRequestFullscreen():layoutNode.mozRequestFullscreen?layoutNode.mozRequestFullscreen():layoutNode.webkitRequestFullscreen?layoutNode.webkitRequestFullscreen():layoutNode.setTop(0)},exitFullscreen=()=>{if(document.exitRequestFullScreen){if(document.fullScreenElement!==layoutNode)return;document.exitRequestFullScreen()}else if(document.msExitFullscreen){if(document.msFullscreenElement!==layoutNode)return;document.msExitFullscreen()}else if(document.mozCancelFullScreen){if(document.mozFullScreenElement!==layoutNode)return;document.mozCancelFullScreen()}else if(document.webkitExitFullscreen){if(document.webkitFullscreenElement!==layoutNode)return;document.webkitExitFullscreen()}},hideLoadingIcon=()=>{let child=loadingNode.lastElementChild;for(;child;)loadingNode.removeChild(child),child=loadingNode.lastElementChild};return{close:()=>{if(exitFullscreen(),unlockBodyScroll(),FocusLockManager.untrapFocus(),layoutNode.remove(),focusOnClose)try{focusOnClose.focus()}catch(e){}},toggleFullscreen:()=>{document.exitRequestFullScreen?document.fullScreenElement===layoutNode?exitFullscreen():requestFullscreen():document.msExitFullscreen?document.msFullscreenElement===layoutNode?exitFullscreen():requestFullscreen():document.mozCancelFullScreen?document.mozFullScreenElement===layoutNode?exitFullscreen():requestFullscreen():document.webkitExitFullscreen&&(document.webkitFullscreenElement===layoutNode?exitFullscreen():requestFullscreen())},requestFullscreen:requestFullscreen,exitFullscreen:exitFullscreen,getContainer:()=>contentNode,setContent:content=>{hideLoadingIcon();let child=contentNode.lastElementChild;for(;child;)contentNode.removeChild(child),child=contentNode.lastElementChild;contentNode.append(content)},showLoadingIcon:()=>{(0,_loadingicon.addIconToContainer)(loadingNode)},hideLoadingIcon:hideLoadingIcon}},lockBodyScroll=()=>{document.querySelector("body").classList.add("overflow-hidden")},unlockBodyScroll=()=>{document.querySelector("body").classList.remove("overflow-hidden")}})); define("mod_forum/local/layouts",["exports","./layout/fullscreen"],(function(_exports,_fullscreen){Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"createFullScreenWindow",{enumerable:!0,get:function(){return _fullscreen.createLayout}})})); /** * Handle the manual locking of individual discussions * * @module mod_forum/lock_toggle * @copyright 2019 Peter Dias <peter@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/lock_toggle",["jquery","core/templates","core/notification","mod_forum/repository","mod_forum/selectors"],(function($,Templates,Notification,Repository,Selectors){return{init:function(root,preventDefault){root.on("click",Selectors.lock.toggle,(function(e){var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),state=toggleElement.data("state");Repository.setDiscussionLockState(forumId,discussionId,state).then((function(){return location.reload()})).catch(Notification.exception),preventDefault&&e.preventDefault()}))}}})); /** * This module is the highest level module for the calendar. It is * responsible for initialising all of the components required for * the calendar to run. It also coordinates the interaction between * components by listening for and responding to different events * triggered within the calendar UI. * * @module mod_forum/pin_toggle * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/pin_toggle",["jquery","core/ajax","core/str","core/templates","core/notification","mod_forum/repository","mod_forum/selectors","core/str"],(function($,Ajax,Str,Templates,Notification,Repository,Selectors,String){return{init:function(root,preventDefault,callback){root.on("click",Selectors.pin.toggle,(function(e){var toggleElement=$(this),forumid=toggleElement.data("forumid"),discussionid=toggleElement.data("discussionid"),pinstate=toggleElement.data("targetstate");Repository.setPinDiscussionState(forumid,discussionid,pinstate).then((function(context){return callback(toggleElement,context)})).then((function(){return String.get_string("pinupdated","forum").done((function(s){return Notification.addNotification({message:s,type:"info"})}))})).fail(Notification.exception),preventDefault&&e.preventDefault()}))}}})); /** * This module is the highest level module for the calendar. It is * responsible for initialising all of the components required for * the calendar to run. It also coordinates the interaction between * components by listening for and responding to different events * triggered within the calendar UI. * * @module mod_forum/posts_list * @copyright 2019 Peter Dias * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/posts_list",["jquery","core/templates","core/notification","core/pending","mod_forum/selectors","mod_forum/inpage_reply","core_form/changechecker"],(function($,Templates,Notification,Pending,Selectors,InPageReply,FormChangeChecker){return{init:function(root,throttlingwarningmsg){!function(root,throttlingwarningmsg){root.on("click",Selectors.post.inpageReplyLink,(function(e){if(e.preventDefault(),window.location.hash){var url=window.location.href.split("#")[0];history.pushState({},document.title,url)}var pending=new Pending("inpage-reply"),currentTarget=$(e.currentTarget).parents(Selectors.post.forumCoreContent),currentSubject=currentTarget.find(Selectors.post.forumSubject),currentRoot=$(e.currentTarget).parents(Selectors.post.forumContent),context={postid:$(currentRoot).data("post-id"),reply_url:$(e.currentTarget).attr("href"),sesskey:M.cfg.sesskey,parentsubject:currentSubject.data("replySubject"),canreplyprivately:$(e.currentTarget).data("can-reply-privately"),postformat:InPageReply.CONTENT_FORMATS.MOODLE,throttlingwarningmsg:throttlingwarningmsg};if(currentRoot.find(Selectors.post.inpageReplyContent).length){var form=currentRoot.find(Selectors.post.inpageReplyContent);form.slideToggle(300,pending.resolve),form.is(":visible")&&form.find("textarea").focus()}else Templates.render("mod_forum/inpage_reply",context).then((function(html,js){return Templates.appendNodeContents(currentTarget,html,js)})).then((function(){return currentRoot.find(Selectors.post.inpageReplyContent).slideToggle(300,pending.resolve).find("textarea").focus()})).then((function(){FormChangeChecker.watchFormById("inpage-reply-".concat(context.postid))})).catch(Notification.exception)}))}(root,throttlingwarningmsg),InPageReply.init(root)}}})); /** * Forum repository class to encapsulate all of the AJAX requests that subscribe or unsubscribe * can be sent for forum. * * @module mod_forum/repository * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/repository",["core/ajax"],(function(Ajax){return{setDiscussionSubscriptionState:function(forumId,discussionId,targetState){var request={methodname:"mod_forum_set_subscription_state",args:{forumid:forumId,discussionid:discussionId,targetstate:targetState}};return Ajax.call([request])[0]},addDiscussionPost:function(postid,subject,message,messageformat,isprivatereply,topreferredformat){var request={methodname:"mod_forum_add_discussion_post",args:{postid:postid,message:message,messageformat:messageformat,subject:subject,options:[{name:"private",value:isprivatereply},{name:"topreferredformat",value:topreferredformat}]}};return Ajax.call([request])[0]},setDiscussionLockState:function(forumId,discussionId,targetState){var request={methodname:"mod_forum_set_lock_state",args:{forumid:forumId,discussionid:discussionId,targetstate:targetState}};return Ajax.call([request])[0]},setFavouriteDiscussionState:function(forumId,discussionId,targetState){var request={methodname:"mod_forum_toggle_favourite_state",args:{discussionid:discussionId,targetstate:targetState}};return Ajax.call([request])[0]},setPinDiscussionState:function(forumid,discussionid,targetstate){var request={methodname:"mod_forum_set_pin_state",args:{discussionid:discussionid,targetstate:targetstate}};return Ajax.call([request])[0]},getDiscussionByUserID:function(userid,cmid){let sortby=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"modified",sortdirection=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"DESC";var request={methodname:"mod_forum_get_discussion_posts_by_userid",args:{userid:userid,cmid:cmid,sortby:sortby,sortdirection:sortdirection}};return Ajax.call([request])[0]},getDiscussionPosts:function(discussionId){let sortby=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"created",sortdirection=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"ASC";var request={methodname:"mod_forum_get_discussion_posts",args:{discussionid:discussionId,sortby:sortby,sortdirection:sortdirection}};return Ajax.call([request])[0]}}})); /** * Handle discussion subscription toggling on a discussion list in * the forum view. * * @module mod_forum/subscription_toggle * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/subscription_toggle",["jquery","core/templates","core/notification","mod_forum/repository","mod_forum/selectors","core/pubsub","mod_forum/forum_events"],(function($,Templates,Notification,Repository,Selectors,PubSub,ForumEvents){return{init:function(root,preventDefault,callback){root.on("click",Selectors.subscription.toggle,(function(e){var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),subscriptionState=toggleElement.data("targetstate");Repository.setDiscussionSubscriptionState(forumId,discussionId,subscriptionState).then((function(context){return PubSub.publish(ForumEvents.SUBSCRIPTION_TOGGLED,{discussionId:discussionId,subscriptionState:subscriptionState}),callback(toggleElement,context)})).catch(Notification.exception),preventDefault&&e.preventDefault()}))}}})); /** * Module for viewing a discussion. * * @module mod_forum/discussion_list * @copyright 2019 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/discussion",["jquery","core/custom_interaction_events","mod_forum/selectors","core/pubsub","mod_forum/forum_events","core/str","core/notification"],(function($,CustomEvents,Selectors,PubSub,ForumEvents,String,Notification){var isElementInInPageReplySection=function(element){return!!$(element).closest(Selectors.post.inpageReplyContent).length},initAccessibilityKeyboardNav=function(root){root.find(Selectors.post.post).each((function(index,post){var actions=$(post).find(Selectors.post.action),firstAction=actions.first();actions.attr("tabindex","-1"),firstAction.attr("tabindex",0)})),CustomEvents.define(root,[CustomEvents.events.up,CustomEvents.events.down,CustomEvents.events.next,CustomEvents.events.previous,CustomEvents.events.home,CustomEvents.events.end]),root.on(CustomEvents.events.up,(function(e,data){var activeElement=document.activeElement;if(!isElementInInPageReplySection(activeElement)){var focusPost=$(activeElement).closest(Selectors.post.post);focusPost.length?function(currentPost){var prevPost=currentPost.prev(Selectors.post.post);if(prevPost.length){var replyPost=prevPost.find(Selectors.post.post).last();replyPost.length?replyPost.focus():prevPost.focus()}else currentPost.parents(Selectors.post.post).first().focus()}(focusPost):root.find(Selectors.post.post).first().focus(),data.originalEvent.preventDefault()}})),root.on(CustomEvents.events.down,(function(e,data){var activeElement=document.activeElement;if(!isElementInInPageReplySection(activeElement)){var focusPost=$(activeElement).closest(Selectors.post.post);focusPost.length?function(currentPost){var replyPost=currentPost.find(Selectors.post.post).first();if(replyPost.length)replyPost.focus();else{var siblingPost=currentPost.next(Selectors.post.post);if(siblingPost.length)siblingPost.focus();else for(var parentPosts=currentPost.parents(Selectors.post.post).toArray(),i=0;i<parentPosts.length;i++){var ancestorSiblingPost=$(parentPosts[i]).next(Selectors.post.post);if(ancestorSiblingPost.length){ancestorSiblingPost.focus();break}}}}(focusPost):root.find(Selectors.post.post).first().focus(),data.originalEvent.preventDefault()}})),root.on(CustomEvents.events.home,(function(e,data){isElementInInPageReplySection(document.activeElement)||(root.find(Selectors.post.post).first().focus(),data.originalEvent.preventDefault())})),root.on(CustomEvents.events.end,(function(e,data){isElementInInPageReplySection(document.activeElement)||(root.find(Selectors.post.post).last().focus(),data.originalEvent.preventDefault())})),root.on(CustomEvents.events.next,Selectors.post.action,(function(e,data){var currentAction=$(e.target),actions=currentAction.closest(Selectors.post.actionsContainer).find(Selectors.post.action),nextAction=currentAction.next(Selectors.post.action);actions.attr("tabindex","-1"),nextAction.length||(nextAction=actions.first()),nextAction.attr("tabindex",0),nextAction.focus(),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.previous,Selectors.post.action,(function(e,data){var currentAction=$(e.target),actions=currentAction.closest(Selectors.post.actionsContainer).find(Selectors.post.action),nextAction=currentAction.prev(Selectors.post.action);actions.attr("tabindex","-1"),nextAction.length||(nextAction=actions.last()),nextAction.attr("tabindex",0),nextAction.focus(),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.home,Selectors.post.action,(function(e,data){var actions=$(e.target).closest(Selectors.post.actionsContainer).find(Selectors.post.action),firstAction=actions.first();actions.attr("tabindex","-1"),firstAction.attr("tabindex",0),firstAction.focus(),e.stopPropagation(),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.end,Selectors.post.action,(function(e,data){var actions=$(e.target).closest(Selectors.post.actionsContainer).find(Selectors.post.action),lastAction=actions.last();actions.attr("tabindex","-1"),lastAction.attr("tabindex",0),lastAction.focus(),e.stopPropagation(),data.originalEvent.preventDefault()})),PubSub.subscribe(ForumEvents.SUBSCRIPTION_TOGGLED,(function(data){var updateMessage=data.subscriptionState?"discussionsubscribed":"discussionunsubscribed";String.get_string(updateMessage,"forum").then((function(s){return Notification.addNotification({message:s,type:"info"})})).catch(Notification.exception)}))};return{init:function(root){initAccessibilityKeyboardNav(root)}}})); /** * Module for the list of discussions on when viewing a forum. * * @module mod_forum/discussion_list * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/discussion_list",["jquery","core/templates","core/str","core/notification","mod_forum/subscription_toggle","mod_forum/selectors","mod_forum/repository","core/pubsub","mod_forum/forum_events"],(function($,Templates,Str,Notification,SubscriptionToggle,Selectors,Repository,PubSub,ForumEvents){return{init:function(root){SubscriptionToggle.init(root,!1,(function(toggleElement,context){var toggleId=toggleElement.attr("id"),newTargetState=context.userstate.subscribed?0:1;toggleElement.data("targetstate",newTargetState);var stringKey=context.userstate.subscribed?"unsubscribediscussion":"subscribediscussion";return Str.get_string(stringKey,"mod_forum").then((function(string){return toggleElement.closest("td").find('label[for="'+toggleId+'"]').find("span").text(string),string}))})),function(root){PubSub.subscribe(ForumEvents.SUBSCRIPTION_TOGGLED,(function(data){var discussionId=data.discussionId,subscribed=data.subscriptionState,discussionListItem=root.find(Selectors.discussion.item+"[data-discussionid= "+discussionId+"]"),subscribedLabel=discussionListItem.find(Selectors.discussion.subscribedLabel);subscribed?(discussionListItem.addClass("subscribed"),subscribedLabel.removeAttr("hidden")):(discussionListItem.removeClass("subscribed"),subscribedLabel.attr("hidden",!0))})),root.on("click",Selectors.favourite.toggle,(function(e){e.preventDefault();var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),subscriptionState=toggleElement.data("targetstate");Repository.setFavouriteDiscussionState(forumId,discussionId,subscriptionState).then((function(){return location.reload()})).catch(Notification.exception)})),root.on("click",Selectors.pin.toggle,(function(e){e.preventDefault();var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),state=toggleElement.data("targetstate");Repository.setPinDiscussionState(forumId,discussionId,state).then((function(){return location.reload()})).catch(Notification.exception)})),root.on("click",Selectors.lock.toggle,(function(e){var toggleElement=$(this),forumId=toggleElement.data("forumid"),discussionId=toggleElement.data("discussionid"),state=toggleElement.data("state");Repository.setDiscussionLockState(forumId,discussionId,state).then((function(context){var icon=toggleElement.parents(Selectors.summary.actions).find(Selectors.lock.icon),lockedLabel=toggleElement.parents(Selectors.discussion.item).find(Selectors.discussion.lockedLabel);return context.locked?(icon.removeClass("hidden"),lockedLabel.removeAttr("hidden")):(icon.addClass("hidden"),lockedLabel.attr("hidden",!0)),context})).then((function(context){return context.forumid=forumId,Templates.render("mod_forum/discussion_lock_toggle",context)})).then((function(html,js){return Templates.replaceNode(toggleElement,html,js)})).then((function(){return Str.get_string("lockupdated","forum").done((function(s){return Notification.addNotification({message:s,type:"info"})}))})).catch(Notification.exception),e.preventDefault()}))}(root)}}})); define("mod_forum/discussion_nested_v2",["exports","jquery","core/auto_rows","core/custom_interaction_events","core_form/changechecker","core/notification","core/templates","mod_forum/discussion","mod_forum/inpage_reply","mod_forum/lock_toggle","mod_forum/favourite_toggle","mod_forum/pin_toggle","mod_forum/selectors","mod_forum/subscription_toggle"],(function(_exports,_jquery,_auto_rows,_custom_interaction_events,FormChangeChecker,_notification,_templates,_discussion,_inpage_reply,_lock_toggle,_favourite_toggle,_pin_toggle,_selectors,_subscription_toggle){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Module for viewing a discussion in nested v2 view. * * @module mod_Forum/discussion_nested_v2 * @copyright 2019 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_auto_rows=_interopRequireDefault(_auto_rows),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),FormChangeChecker=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(FormChangeChecker),_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates),_discussion=_interopRequireDefault(_discussion),_inpage_reply=_interopRequireDefault(_inpage_reply),_lock_toggle=_interopRequireDefault(_lock_toggle),_favourite_toggle=_interopRequireDefault(_favourite_toggle),_pin_toggle=_interopRequireDefault(_pin_toggle),_selectors=_interopRequireDefault(_selectors),_subscription_toggle=_interopRequireDefault(_subscription_toggle);const getPostContainer=element=>element.closest(_selectors.default.post.post),getPostContainerById=(element,id)=>element.find("".concat(_selectors.default.post.post,"[data-post-id=").concat(id,"]")),getPostContentContainer=postContainer=>postContainer.children().not(_selectors.default.post.repliesContainer).find(_selectors.default.post.forumCoreContent),getInPageReplyContainer=postContainer=>postContainer.children().filter(_selectors.default.post.inpageReplyContainer),getInPageReplyForm=postContainer=>getInPageReplyContainer(postContainer).find(_selectors.default.post.inpageReplyContent),getInPageReplyCreateButton=postContainer=>getPostContentContainer(postContainer).find(_selectors.default.post.inpageReplyCreateButton),getRepliesVisibilityToggleContainer=postContainer=>postContainer.children(_selectors.default.post.repliesVisibilityToggleContainer),getRepliesContainer=postContainer=>postContainer.children(_selectors.default.post.repliesContainer),hasReplies=postContainer=>getRepliesContainer(postContainer).children().length>0,getShowRepliesButton=replyVisibilityToggleContainer=>replyVisibilityToggleContainer.find(_selectors.default.post.showReplies),getHideRepliesButton=replyVisibilityToggleContainer=>replyVisibilityToggleContainer.find(_selectors.default.post.hideReplies),repliesVisible=postContainer=>getRepliesContainer(postContainer).is(":visible"),showReplies=function(postContainer){let postIdToSee=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const repliesContainer=getRepliesContainer(postContainer),replyVisibilityToggleContainer=getRepliesVisibilityToggleContainer(postContainer),showButton=getShowRepliesButton(replyVisibilityToggleContainer),hideButton=getHideRepliesButton(replyVisibilityToggleContainer);showButton.addClass("hidden"),hideButton.removeClass("hidden"),repliesContainer.slideDown({duration:150,queue:!1,complete:()=>{if(postIdToSee){const postContainerToSee=getPostContainerById(repliesContainer,postIdToSee);postContainerToSee.length&&postContainerToSee[0].scrollIntoView()}}}).css("display","none").fadeIn(150)},hideReplies=postContainer=>{const repliesContainer=getRepliesContainer(postContainer),replyVisibilityToggleContainer=getRepliesVisibilityToggleContainer(postContainer),showButton=getShowRepliesButton(replyVisibilityToggleContainer),hideButton=getHideRepliesButton(replyVisibilityToggleContainer);showButton.removeClass("hidden"),hideButton.addClass("hidden"),repliesContainer.slideUp({duration:150,queue:!1}).fadeOut(150)};let showInPageReplyForm=null;const hideInPageReplyForm=function(postContainer){let postIdToSee=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const inPageReplyForm=getInPageReplyForm(postContainer),inPageReplyCreateButton=getInPageReplyCreateButton(postContainer),repliesVisibilityToggleContainer=getRepliesVisibilityToggleContainer(postContainer);repliesVisibilityToggleContainer.length&&hasReplies(postContainer)&&(repliesVisibilityToggleContainer.fadeOut(150),repliesVisible(postContainer)||showReplies(postContainer,postIdToSee)),inPageReplyForm.slideUp({duration:150,queue:!1,complete:()=>{inPageReplyCreateButton.fadeIn(150)}}).fadeOut(200)},hasInPageReplyForm=inPageReplyContainer=>inPageReplyContainer.find(_selectors.default.post.inpageReplyContent).length>0,renderInPageReplyTemplate=(additionalTemplateContext,button,postContainer)=>{const postContentContainer=getPostContentContainer(postContainer),currentSubject=postContentContainer.find(_selectors.default.post.forumSubject).text(),currentAuthorName=postContentContainer.find(_selectors.default.post.authorName).text(),context={postid:postContainer.data("post-id"),reply_url:button.attr("data-href"),sesskey:M.cfg.sesskey,parentsubject:currentSubject,parentauthorname:currentAuthorName,canreplyprivately:button.data("can-reply-privately"),postformat:_inpage_reply.default.CONTENT_FORMATS.MOODLE,...additionalTemplateContext};return _templates.default.render("mod_forum/inpage_reply_v2",context)},registerEventListeners=root=>{_custom_interaction_events.default.define(root,[_custom_interaction_events.default.events.activate]),_auto_rows.default.init(root),root.on(_custom_interaction_events.default.events.activate,_selectors.default.post.inpageReplyCreateButton,((e,data)=>{data.originalEvent.preventDefault();const postContainer=getPostContainer((0,_jquery.default)(e.currentTarget));showInPageReplyForm(postContainer)})),root.on(_custom_interaction_events.default.events.activate,_selectors.default.post.inpageReplyCancelButton,((e,data)=>{data.originalEvent.preventDefault();const postContainer=getPostContainer((0,_jquery.default)(e.currentTarget));hideInPageReplyForm(postContainer)})),root.on(_custom_interaction_events.default.events.activate,_selectors.default.post.showReplies,((e,data)=>{data.originalEvent.preventDefault();const postContainer=getPostContainer((0,_jquery.default)(e.target));showReplies(postContainer)})),root.on(_custom_interaction_events.default.events.activate,_selectors.default.post.hideReplies,((e,data)=>{data.originalEvent.preventDefault();const postContainer=getPostContainer((0,_jquery.default)(e.target));hideReplies(postContainer)})),root.on(_inpage_reply.default.EVENTS.POST_CREATED,_selectors.default.post.inpageSubmitBtn,((e,newPostId)=>{const currentTarget=(0,_jquery.default)(e.currentTarget),postContainer=getPostContainer(currentTarget),postContainers=currentTarget.parents(_selectors.default.post.post);hideInPageReplyForm(postContainer,newPostId),postContainers.each(((index,container)=>{(postContainer=>{getRepliesVisibilityToggleContainer(postContainer).find(_selectors.default.post.replyCount).each(((index,element)=>{const currentCount=parseInt(element.innerText,10);element.innerText=currentCount+1}))})((0,_jquery.default)(container))}))}))};_exports.init=(root,context)=>{var additionalTemplateContext;additionalTemplateContext=context,showInPageReplyForm=async postContainer=>{const inPageReplyContainer=getInPageReplyContainer(postContainer),repliesVisibilityToggleContainer=getRepliesVisibilityToggleContainer(postContainer),inPageReplyCreateButton=getInPageReplyCreateButton(postContainer);if(!hasInPageReplyForm(inPageReplyContainer)){try{const html=await renderInPageReplyTemplate(additionalTemplateContext,inPageReplyCreateButton,postContainer);_templates.default.appendNodeContents(inPageReplyContainer,html,"")}catch(e){_notification.default.exception(e)}FormChangeChecker.watchForm(postContainer[0].querySelector("form"))}inPageReplyCreateButton.fadeOut(150,(()=>{const inPageReplyForm=getInPageReplyForm(postContainer);inPageReplyForm.slideDown({duration:150,queue:!1,complete:()=>{inPageReplyForm.find("textarea").focus()}}).css("display","none").fadeIn(150),repliesVisibilityToggleContainer.length&&hasReplies(postContainer)&&(repliesVisibilityToggleContainer.fadeIn(150),hideReplies(postContainer))}))},registerEventListeners(root),_discussion.default.init(root),_inpage_reply.default.init(root);const discussionToolsContainer=root.find(_selectors.default.discussion.tools);_lock_toggle.default.init(discussionToolsContainer,!1),_favourite_toggle.default.init(discussionToolsContainer,!1,((toggleElement,response)=>{const newTargetState=response.userstate.favourited?0:1;return toggleElement.data("targetstate",newTargetState)})),_pin_toggle.default.init(discussionToolsContainer,!1,((toggleElement,response)=>{const newTargetState=response.pinned?0:1;return toggleElement.data("targetstate",newTargetState)})),_subscription_toggle.default.init(discussionToolsContainer,!1,((toggleElement,response)=>{const newTargetState=response.userstate.subscribed?0:1;toggleElement.data("targetstate",newTargetState)}))}})); /** * This module handles the in page replying to forum posts. * * @module mod_forum/inpage_reply * @copyright 2019 Peter Dias * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/inpage_reply",["jquery","core/templates","core/notification","mod_forum/repository","mod_forum/selectors","core_form/changechecker"],(function($,Templates,Notification,Repository,Selectors,FormChangeChecker){var DISPLAYCONSTANTS_NESTED_V2=4,DISPLAYCONSTANTS_THREADED=2,DISPLAYCONSTANTS_NESTED=3,DISPLAYCONSTANTS_FLAT_NEWEST_FIRST=-1,EVENTS={POST_CREATED:"mod_forum-post-created"},CONTENT_FORMATS={MOODLE:0},hideSubmitButtonLoadingIcon=function(button){var textContainer=button.find(Selectors.post.inpageSubmitBtnText),loadingIconContainer=button.find(Selectors.post.loadingIconContainer);button.css("width",""),textContainer.removeClass("hidden"),loadingIconContainer.addClass("hidden")},registerEventListeners=function(root){root.on("click",Selectors.post.inpageSubmitBtn,(function(e){e.preventDefault();var newid,button,textContainer,loadingIconContainer,width,submitButton=$(e.currentTarget),allButtons=submitButton.parent().find(Selectors.post.inpageReplyButton),form=submitButton.parents(Selectors.post.inpageReplyForm).get(0),message=form.elements.post.value.trim(),messageformat=CONTENT_FORMATS.MOODLE,postid=form.elements.reply.value,subject=form.elements.subject.value,currentRoot=submitButton.closest(Selectors.post.post),isprivatereply=null!=form.elements.privatereply&&form.elements.privatereply.checked,modeSelector=root.find(Selectors.post.modeSelect),mode=modeSelector.length?parseInt(modeSelector.get(0).value):null;message.length&&(textContainer=(button=submitButton).find(Selectors.post.inpageSubmitBtnText),loadingIconContainer=button.find(Selectors.post.loadingIconContainer),width=button.outerWidth(),button.css("width",width),textContainer.addClass("hidden"),loadingIconContainer.removeClass("hidden"),allButtons.prop("disabled",!0),Repository.addDiscussionPost(postid,subject,message,messageformat,isprivatereply,!0).then((function(context){var message=context.messages.reduce((function(carry,message){return"success"==message.type&&(carry+="<p>"+message.message+"</p>"),carry}),"");return Notification.addNotification({message:message,type:"success"}),context})).then((function(context){form.reset();var post=context.post;switch(newid=post.id,mode){case DISPLAYCONSTANTS_NESTED_V2:var capabilities=post.capabilities,currentAuthorName=currentRoot.children().not(Selectors.post.repliesContainer).find(Selectors.post.authorName).text();return post.parentauthorname=currentAuthorName,post.showactionmenu=capabilities.view||capabilities.controlreadstatus||capabilities.edit||capabilities.split||capabilities.delete||capabilities.export||post.urls.viewparent,Templates.render("mod_forum/forum_discussion_nested_v2_post_reply",post);case DISPLAYCONSTANTS_THREADED:return Templates.render("mod_forum/forum_discussion_threaded_post",post);case DISPLAYCONSTANTS_NESTED:return Templates.render("mod_forum/forum_discussion_nested_post",post);default:return Templates.render("mod_forum/forum_discussion_post",post)}})).then((function(html,js){var repliesnode=currentRoot.find(Selectors.post.repliesContainer).first();return mode==DISPLAYCONSTANTS_FLAT_NEWEST_FIRST?Templates.prependNodeContents(repliesnode,html,js):Templates.appendNodeContents(repliesnode,html,js)})).then((function(){return submitButton.trigger(EVENTS.POST_CREATED,newid),hideSubmitButtonLoadingIcon(submitButton),allButtons.prop("disabled",!1),FormChangeChecker.resetFormDirtyState(submitButton[0]),currentRoot.find(Selectors.post.inpageReplyContent).hide()})).then((function(){location.href="#p"+newid,location.reload()})).catch((function(error){return hideSubmitButtonLoadingIcon(submitButton),allButtons.prop("disabled",!1),Notification.exception(error)})))}))};return{init:function(root){registerEventListeners(root)},CONTENT_FORMATS:CONTENT_FORMATS,EVENTS:EVENTS}})); /** * Common CSS selectors for the forum UI. * * @module mod_forum/selectors * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_forum/selectors",[],(function(){return{subscription:{toggle:"[data-type='subscription-toggle'][data-action='toggle']"},summary:{actions:"[data-container='discussion-summary-actions']"},post:{post:'[data-region="post"]',action:'[data-region="post-action"]',actionsContainer:'[data-region="post-actions-container"]',authorName:'[data-region="author-name"]',forumCoreContent:"[data-region-content='forum-post-core']",forumContent:"[data-content='forum-post']",forumSubject:"[data-region-content='forum-post-core-subject']",inpageReplyButton:"button",inpageReplyLink:"[data-action='collapsible-link']",inpageReplyCancelButton:"[data-action='cancel-inpage-reply']",inpageReplyCreateButton:"[data-action='create-inpage-reply']",inpageReplyContainer:'[data-region="inpage-reply-container"]',inpageReplyContent:"[data-content='inpage-reply-content']",inpageReplyForm:"form[data-content='inpage-reply-form']",inpageSubmitBtn:"[data-action='forum-inpage-submit']",inpageSubmitBtnText:"[data-region='submit-text']",loadingIconContainer:"[data-region='loading-icon-container']",repliesContainer:"[data-region='replies-container']",replyCount:'[data-region="reply-count"]',modeSelect:"select[name='mode']",showReplies:'[data-action="show-replies"]',hideReplies:'[data-action="hide-replies"]',repliesVisibilityToggleContainer:'[data-region="replies-visibility-toggle-container"]'},lock:{toggle:"[data-action='toggle'][data-type='lock-toggle']",icon:"[data-region='locked-icon']"},favourite:{toggle:"[data-type='favorite-toggle'][data-action='toggle']"},pin:{toggle:"[data-type='pin-toggle'][data-action='toggle']"},discussion:{tools:'[data-container="discussion-tools"]',item:'[data-region="discussion-list-item"]',lockedLabel:"[data-region='locked-label']",subscribedLabel:"[data-region='subscribed-label']",timedLabel:"[data-region='timed-label']"}}})); /** * Encapsules the behavior for creating a tool type from a cartridge URL * in Moodle. Manages the UI while operations are occuring. * * See template: mod_lti/cartridge_registration_form * * @module mod_lti/cartridge_registration_form * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/cartridge_registration_form",["jquery","core/ajax","core/notification","mod_lti/tool_type","mod_lti/events","mod_lti/keys","core/str"],(function($,ajax,notification,toolType,ltiEvents,KEYS,str){var SELECTORS_CONSUMER_KEY="#registration-key",SELECTORS_SHARED_SECRET="#registration-secret",SELECTORS_REGISTRATION_FORM="#cartridge-registration-form",SELECTORS_REGISTRATION_SUBMIT_BUTTON="#cartridge-registration-submit",SELECTORS_REGISTRATION_CANCEL_BUTTON="#cartridge-registration-cancel",getSubmitButton=function(){return $(SELECTORS_REGISTRATION_SUBMIT_BUTTON)},submitCartridgeURL=function(){if(getSubmitButton().hasClass("loading"))return!1;var url=$(SELECTORS_REGISTRATION_FORM).attr("data-cartridge-url");if(""===url)return!1;getSubmitButton().addClass("loading");var consumerKey=$(SELECTORS_CONSUMER_KEY).val(),sharedSecret=$(SELECTORS_SHARED_SECRET).val(),promise=toolType.create({cartridgeurl:url,key:consumerKey,secret:sharedSecret});return promise.done((function(){str.get_string("successfullycreatedtooltype","mod_lti").done((function(s){$(document).trigger(ltiEvents.NEW_TOOL_TYPE),$(document).trigger(ltiEvents.STOP_CARTRIDGE_REGISTRATION),$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,{message:s})})).fail(notification.exception)})).fail((function(){str.get_string("failedtocreatetooltype","mod_lti").done((function(s){$(document).trigger(ltiEvents.NEW_TOOL_TYPE),$(document).trigger(ltiEvents.STOP_CARTRIDGE_REGISTRATION),$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,{message:s,error:!0})})).fail(notification.exception)})).always((function(){getSubmitButton().removeClass("loading")})),promise},registerEventListeners=function(){$(SELECTORS_REGISTRATION_FORM).submit((function(e){e.preventDefault(),submitCartridgeURL()}));var cancelButton=$(SELECTORS_REGISTRATION_CANCEL_BUTTON);cancelButton.click((function(e){e.preventDefault(),$(document).trigger(ltiEvents.STOP_CARTRIDGE_REGISTRATION)})),cancelButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),cancelButton.click())}))};return{init:function(){registerEventListeners()}}})); /** * Launches the modal dialogue that contains the iframe that sends the Content-Item selection request to an * LTI tool provider that supports Content-Item type message. * * See template: mod_lti/contentitem * * @module mod_lti/contentitem * @copyright 2016 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("mod_lti/contentitem",["jquery","core/notification","core/str","core/templates","mod_lti/form-field","core/modal_factory","core/modal_events"],(function($,notification,str,templates,FormField,ModalFactory,ModalEvents){var dialogue,doneCallback,contentItem={init:function(url,postData,cb){doneCallback=cb;var context={url:url,postData:postData},bodyPromise=templates.render("mod_lti/contentitem",context);if(dialogue)return dialogue.setBody(bodyPromise),void dialogue.show();str.get_string("selectcontent","lti").then((function(title){return ModalFactory.create({title:title,body:bodyPromise,large:!0})})).then((function(modal){dialogue=modal,modal.getRoot().on(ModalEvents.hidden,(function(){modal.setBody(""),notification.fetchNotifications()})),modal.show()})).catch(notification.exception)}},ltiFormFields=[new FormField("name",FormField.TYPES.TEXT,!1,""),new FormField("introeditor",FormField.TYPES.EDITOR,!1,""),new FormField("toolurl",FormField.TYPES.TEXT,!0,""),new FormField("securetoolurl",FormField.TYPES.TEXT,!0,""),new FormField("instructorchoiceacceptgrades",FormField.TYPES.CHECKBOX,!0,!0),new FormField("instructorchoicesendname",FormField.TYPES.CHECKBOX,!0,!0),new FormField("instructorchoicesendemailaddr",FormField.TYPES.CHECKBOX,!0,!0),new FormField("instructorcustomparameters",FormField.TYPES.TEXT,!0,""),new FormField("icon",FormField.TYPES.TEXT,!0,""),new FormField("secureicon",FormField.TYPES.TEXT,!0,""),new FormField("launchcontainer",FormField.TYPES.SELECT,!0,0),new FormField("grade_modgrade_point",FormField.TYPES.TEXT,!1,""),new FormField("lineitemresourceid",FormField.TYPES.TEXT,!0,""),new FormField("lineitemtag",FormField.TYPES.TEXT,!0,""),new FormField("lineitemsubreviewurl",FormField.TYPES.TEXT,!0,""),new FormField("lineitemsubreviewparams",FormField.TYPES.TEXT,!0,"")];const hideElement=e=>{e.setAttribute("hidden","true"),e.setAttribute("aria-hidden","true"),e.setAttribute("tab-index","-1")},showElement=e=>{e.removeAttribute("hidden"),e.setAttribute("aria-hidden","false"),e.setAttribute("tab-index","1")};return window.processContentItemReturnData=function(returnData){var index;if(dialogue&&dialogue.hide(),returnData.multiple){for(index in ltiFormFields)ltiFormFields[index].setFieldValue("name"===ltiFormFields[index].name?"item":null);var variants=[];returnData.multiple.forEach((function(v){variants.push((config=>{const variant={};return["name","toolurl","securetoolurl","instructorcustomparameters","icon","secureicon","launchcontainer","lineitemresourceid","lineitemtag","lineitemsubreviewurl","lineitemsubreviewparams"].forEach((function(name){variant[name]=config[name]||""})),variant["introeditor[text]"]=config.introeditor?config.introeditor.text:"",variant["introeditor[format]"]=config.introeditor?config.introeditor.format:"",1===config.instructorchoiceacceptgrades?(variant.instructorchoiceacceptgrades="1",variant["grade[modgrade_point]"]=config.grade_modgrade_point||"100"):variant.instructorchoiceacceptgrades="0",variant})(v))})),async function(items){const form=document.querySelector("#region-main-box form"),toolArea=form.querySelector('[data-attribute="dynamic-import"]'),buttonGroup=form.querySelector("#fgroup_id_buttonar"),submitAndLaunch=form.querySelector("#id_submitbutton");Array.from(form.children).forEach(hideElement),hideElement(submitAndLaunch);const{html:html,js:js}=await templates.renderForPromise("mod_lti/tool_deeplinking_results",{items:items});await templates.replaceNodeContents(toolArea,html,js),showElement(toolArea),showElement(buttonGroup)}(returnData.multiple);const submitAndCourse=document.querySelector("#id_submitbutton2");submitAndCourse.onclick=e=>{e.preventDefault(),submitAndCourse.disabled=!0;const fd=new FormData(document.querySelector("#region-main-box form")),backToCourse=()=>{document.querySelector("#id_cancel").click()};variants.reduce(((promise,variant)=>{Object.entries(variant).forEach((entry=>fd.set(entry[0],entry[1])));const body=new URLSearchParams(fd),doPost=()=>fetch(document.location.pathname,{method:"post",body:body});return promise.then(doPost).catch(doPost)}),Promise.resolve()).then(backToCourse).catch(backToCourse)}}else{for(index in ltiFormFields){var field=ltiFormFields[index],value=null;void 0!==returnData[field.name]&&(value=returnData[field.name]),field.setFieldValue(value)}field.setFieldValue(value)}doneCallback&&doneCallback(returnData)},contentItem})); /** * Processes the result of LTI tool creation from a Content-Item message type. * * @module mod_lti/contentitem_return * @copyright 2016 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("mod_lti/contentitem_return",["jquery"],(function($){return{init:function(returnData){$(window).ready((function(){window!=top?parent.processContentItemReturnData(returnData):window.processContentItemReturnData(returnData)}))}}})); /** * Provides a list of events that can be triggered in the LTI management * page. * * @module mod_lti/events * @class events * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/events",[],(function(){return{NEW_TOOL_TYPE:"lti.tool.type.new",START_EXTERNAL_REGISTRATION:"lti.registration.external.start",STOP_EXTERNAL_REGISTRATION:"lti.registration.external.stop",START_CARTRIDGE_REGISTRATION:"lti.registration.cartridge.start",STOP_CARTRIDGE_REGISTRATION:"lti.registration.cartridge.stop",REGISTRATION_FEEDBACK:"lti.registration.feedback",CAPABILITIES_AGREE:"lti.tool.type.capabilities.agree",CAPABILITIES_DECLINE:"lti.tool.type.capabilities.decline"}})); /** * Encapsules the behavior for creating a tool type and tool proxy from a * registration url in Moodle. * * Manages the UI while operations are occuring, including rendering external * registration page within the iframe. * * See template: mod_lti/external_registration * * @module mod_lti/external_registration * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/external_registration",["jquery","core/ajax","core/notification","core/templates","mod_lti/events","mod_lti/tool_proxy","mod_lti/tool_type","mod_lti/keys","core/str"],(function($,ajax,notification,templates,ltiEvents,toolProxy,toolType,KEYS,str){var SELECTORS_EXTERNAL_REGISTRATION_CONTAINER="#external-registration-page-container",SELECTORS_EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER="#external-registration-template-container",SELECTORS_EXTERNAL_REGISTRATION_CANCEL_BUTTON="#cancel-external-registration",SELECTORS_TOOL_TYPE_CAPABILITIES_CONTAINER="#tool-type-capabilities-container",SELECTORS_TOOL_TYPE_CAPABILITIES_TEMPLATE_CONTAINER="#tool-type-capabilities-template-container",SELECTORS_CAPABILITIES_AGREE_CONTAINER=".capabilities-container",getExternalRegistrationCancelButton=function(){return $(SELECTORS_EXTERNAL_REGISTRATION_CANCEL_BUTTON)},getExternalRegistrationContainer=function(){return $(SELECTORS_EXTERNAL_REGISTRATION_CONTAINER)},getExternalRegistrationTemplateContainer=function(){return $(SELECTORS_EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER)},getToolTypeCapabilitiesContainer=function(){return $(SELECTORS_TOOL_TYPE_CAPABILITIES_CONTAINER)},stopLoadingCancel=function(){getExternalRegistrationCancelButton().removeClass("loading")},hideExternalRegistrationContent=function(){getExternalRegistrationContainer().addClass("hidden")},getToolProxyId=function(){return getExternalRegistrationCancelButton().attr("data-tool-proxy-id")},hasToolProxyId=function(){return!!getToolProxyId()},hasCreatedToolProxy=function(){return getExternalRegistrationCancelButton().attr("data-tool-proxy-new")&&hasToolProxyId()},cancelRegistration=function(){getExternalRegistrationCancelButton().addClass("loading");var promise=$.Deferred();if(hasCreatedToolProxy()){var id=getToolProxyId();toolProxy.delete(id).done((function(){promise.resolve()})).fail((function(failure){promise.reject(failure)}))}else promise.resolve();return promise.done((function(){finishExternalRegistration(),stopLoadingCancel()})).fail((function(failure){notification.exception(failure),finishExternalRegistration(),stopLoadingCancel(),str.get_string("failedtodeletetoolproxy","mod_lti").done((function(s){var feedback={message:s,error:!0};$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,feedback)})).fail(notification.exception)})),promise},renderExternalRegistrationWindow=function(registrationRequest){var promise=templates.render("mod_lti/tool_proxy_registration_form",registrationRequest);return promise.done((function(html,js){var container=getExternalRegistrationTemplateContainer();container.append(html),templates.runTemplateJS(js),container.find("form").submit(),getExternalRegistrationContainer().removeClass("hidden")})).fail(notification.exception),promise},promptForToolTypeCapabilitiesAgreement=function(typeData){var promise=$.Deferred();return templates.render("mod_lti/tool_type_capabilities_agree",typeData).done((function(html,js){var container=$(SELECTORS_TOOL_TYPE_CAPABILITIES_TEMPLATE_CONTAINER);hideExternalRegistrationContent(),getToolTypeCapabilitiesContainer().removeClass("hidden"),templates.replaceNodeContents(container,html,js);var choiceContainer=container.find(SELECTORS_CAPABILITIES_AGREE_CONTAINER);choiceContainer.on(ltiEvents.CAPABILITIES_AGREE,(function(){getToolTypeCapabilitiesContainer().addClass("loading"),function(typeData){return toolType.update({id:typeData.id,state:toolType.constants.state.configured})}(typeData).always((function(){getToolTypeCapabilitiesContainer().removeClass("loading"),container.empty(),promise.resolve()}))})),choiceContainer.on(ltiEvents.CAPABILITIES_DECLINE,(function(){container.empty(),promise.resolve()}))})).fail(promise.reject),promise.done((function(){getToolTypeCapabilitiesContainer().addClass("hidden")})).fail(notification.exception),promise},createAndRegisterToolProxy=function(url){var promise=$.Deferred();return url&&""!==url?toolProxy.create({regurl:url}).done((function(result){getExternalRegistrationCancelButton().attr("data-tool-proxy-new","new"),promise=registerProxy(result.id)})).fail((function(exception){cancelRegistration();var feedback={message:exception.message,error:!0};$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,feedback),promise.reject(exception)})):promise.resolve(),promise},registerProxy=function(id){var promise=$.Deferred();return function(id){getExternalRegistrationCancelButton().attr("data-tool-proxy-id",id)}(id),function(id){var request={methodname:"mod_lti_get_tool_proxy_registration_request",args:{id:id}};return ajax.call([request])[0]}(id).done((function(registrationRequest){renderExternalRegistrationWindow(registrationRequest).done((function(){promise.resolve()})).fail(promise.fail)})).fail(promise.fail),promise},finishExternalRegistration=function(){hasToolProxyId()&&getExternalRegistrationCancelButton().removeAttr("data-tool-proxy-id"),getExternalRegistrationCancelButton().removeAttr("data-tool-proxy-new"),hideExternalRegistrationContent(),getExternalRegistrationTemplateContainer().empty(),$(document).trigger(ltiEvents.STOP_EXTERNAL_REGISTRATION)};return{init:function(){!function(){$(document).on(ltiEvents.START_EXTERNAL_REGISTRATION,(function(event,data){data&&(data.url&&createAndRegisterToolProxy(data.url),data.proxyid&®isterProxy(data.proxyid))}));var cancelExternalRegistrationButton=getExternalRegistrationCancelButton();cancelExternalRegistrationButton.click((function(e){e.preventDefault(),cancelRegistration()})),cancelExternalRegistrationButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),cancelRegistration())})),window.triggerExternalRegistrationComplete=function(data){var promise=$.Deferred(),feedback={message:"",error:!1};if("success"==data.status){if(str.get_string("successfullycreatedtooltype","mod_lti").done((function(s){feedback.message=s})).fail(notification.exception),promise.done((function(){finishExternalRegistration(),$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,feedback),$(document).trigger(ltiEvents.NEW_TOOL_TYPE)})).fail(notification.exception),hasCreatedToolProxy()){var proxyId=getToolProxyId();toolType.getFromToolProxyId(proxyId).done((function(types){if(types&&types.length){var typeData=types[0];typeData.hascapabilitygroups?promptForToolTypeCapabilitiesAgreement(typeData).always((function(){promise.resolve()})):promise.resolve()}else promise.resolve()})).fail((function(){promise.resolve()}))}}else feedback.message=data.error,feedback.error=!0,promise.done((function(){cancelRegistration().always((function(){$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,feedback)}))})).fail(notification.exception),promise.resolve();return promise}}()}}})); /** * Handles the return params from the external registration page after it * redirects back to Moodle. * * See also: mod/lti/externalregistrationreturn.php * * @module mod_lti/external_registration_return * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/external_registration_return",[],(function(){return{init:function(message,error,id,status){window.parent&&window.parent.triggerExternalRegistrationComplete({message:message,error:error,id:id,status:status})}}})); /** * A module that enables the setting of form field values on the client side. * * @module mod_lti/form-field * @copyright 2016 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.2 */ define("mod_lti/form-field",["jquery"],(function($){var FormField=function(name,type,resetIfUndefined,defaultValue){this.name=name,this.id="id_"+this.name,this.selector="#"+this.id,this.type=type,this.resetIfUndefined=resetIfUndefined,this.defaultValue=defaultValue};return FormField.TYPES={TEXT:1,SELECT:2,CHECKBOX:3,EDITOR:4},FormField.prototype.setFieldValue=function(value){if(null===value){if(!this.resetIfUndefined)return;value=this.defaultValue}switch(this.type){case FormField.TYPES.CHECKBOX:value?$(this.selector).prop("checked",!0):$(this.selector).prop("checked",!1);break;case FormField.TYPES.EDITOR:if(void 0!==value.text){var attoEditor=$(this.selector+"editable");attoEditor.length?attoEditor.html(value.text):"undefined"!=typeof tinyMCE&&("3"==tinyMCE.majorVersion?tinyMCE.execInstanceCommand(this.id,"mceInsertContent",!1,value.text):tinyMCE.get(this.id).setContent(value.text)),$(this.selector).val(value.text)}break;default:$(this.selector).val(value)}},FormField})); /** * A list of keys and their keycodes that are used by the LTI modules. * * @module mod_lti/keys * @class keys * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/keys",[],(function(){return{ENTER:13,SPACE:32}})); /** * Controls all of the behaviour and interaction with a tool type card. These are * listed on the LTI tool type management page. * * See template: mod_lti/tool_card * * @module mod_lti/tool_card_controller * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/tool_card_controller",["jquery","core/ajax","core/notification","core/templates","core/modal_factory","mod_lti/tool_type","mod_lti/events","mod_lti/keys","core/str"],(function($,ajax,notification,templates,modalFactory,toolType,ltiEvents,KEYS,str){var SELECTORS_DELETE_BUTTON=".delete",SELECTORS_NAME_ELEMENT=".name",SELECTORS_DESCRIPTION_ELEMENT=".description",SELECTORS_CAPABILITIES_CONTAINER=".capabilities-container",SELECTORS_ACTIVATE_BUTTON=".tool-card-footer a.activate",getNameElement=function(element){return element.find(SELECTORS_NAME_ELEMENT)},getDescriptionElement=function(element){return element.find(SELECTORS_DESCRIPTION_ELEMENT)},getActivateButton=function(element){return element.find(SELECTORS_ACTIVATE_BUTTON)},getCapabilitiesContainer=function(element){return element.find(SELECTORS_CAPABILITIES_CONTAINER)},hasCapabilitiesContainer=function(element){return!!getCapabilitiesContainer(element).length},getTypeId=function(element){return element.attr("data-type-id")},clearAllAnnouncements=function(element){element.removeClass("announcement loading success fail capabilities")},startLoading=function(element){clearAllAnnouncements(element),element.addClass("announcement loading")},stopLoading=function(element){element.removeClass("announcement loading")},announceSuccess=function(element){var promise=$.Deferred();return clearAllAnnouncements(element),element.addClass("announcement success"),setTimeout((function(){element.removeClass("announcement success"),promise.resolve()}),2e3),promise},announceFailure=function(element){var promise=$.Deferred();return clearAllAnnouncements(element),element.addClass("announcement fail"),setTimeout((function(){element.removeClass("announcement fail"),promise.resolve()}),2e3),promise},setValueSnapshot=function(element,value){element.attr("data-val-snapshot",value)},getValueSnapshot=function(element){return element.attr("data-val-snapshot")},setStatusActive=function(element){var id=getTypeId(element);if(""===id)return $.Deferred().resolve();startLoading(element);var promise=toolType.update({id:id,state:toolType.constants.state.configured});return promise.then((function(toolTypeData){return stopLoading(element),announceSuccess(element),toolTypeData})).then((function(toolTypeData){return templates.render("mod_lti/tool_card",toolTypeData)})).then((function(html,js){templates.replaceNode(element,html,js)})).catch((function(){stopLoading(element),announceFailure(element)})),promise},registerEventListeners=function(element){var deleteButton=function(element){return element.find(SELECTORS_DELETE_BUTTON)}(element);deleteButton.click((function(e){e.preventDefault(),function(element){var promise=$.Deferred(),typeId=getTypeId(element);startLoading(element),""===typeId?$.Deferred().resolve():str.get_strings([{key:"delete",component:"mod_lti"},{key:"delete_confirmation",component:"mod_lti"},{key:"delete",component:"mod_lti"},{key:"cancel",component:"core"}]).done((function(strs){notification.confirm(strs[0],strs[1],strs[2],strs[3],(function(){toolType.delete(typeId).done((function(){stopLoading(element),announceSuccess(element).done((function(){element.remove()})).fail(notification.exception).always((function(){promise.resolve()}))})).fail((function(error){announceFailure(element),promise.reject(error)}))}),(function(){stopLoading(element),promise.resolve()}))})).fail((function(error){stopLoading(element),notification.exception(error),promise.reject(error)}))}(element)})),deleteButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),deleteButton.click())}));var descriptionElement=getDescriptionElement(element);descriptionElement.focus((function(e){e.preventDefault(),function(element){var descriptionElement=getDescriptionElement(element);if(!descriptionElement.hasClass("loading")){var description=descriptionElement.text().trim();setValueSnapshot(descriptionElement,description)}}(element)})),descriptionElement.blur((function(e){e.preventDefault(),function(element){var typeId=getTypeId(element);if(""===typeId)return $.Deferred().resolve();var descriptionElement=getDescriptionElement(element);if(descriptionElement.hasClass("loading"))return $.Deferred().resolve();var description=descriptionElement.text().trim();if(getValueSnapshot(descriptionElement)==description)return $.Deferred().resolve();descriptionElement.addClass("loading");var promise=toolType.update({id:typeId,description:description});promise.done((function(type){descriptionElement.removeClass("loading"),descriptionElement.text(type.description)})).fail(notification.exception),promise.fail((function(){descriptionElement.removeClass("loading")}))}(element)})),descriptionElement.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode==KEYS.ENTER&&(e.preventDefault(),descriptionElement.blur())}));var nameElement=getNameElement(element);if(nameElement.focus((function(e){e.preventDefault(),function(element){var nameElement=getNameElement(element);if(!nameElement.hasClass("loading")){var name=nameElement.text().trim();setValueSnapshot(nameElement,name)}}(element)})),nameElement.blur((function(e){e.preventDefault(),function(element){var typeId=getTypeId(element);if(""===typeId)return $.Deferred().resolve();var nameElement=getNameElement(element);if(nameElement.hasClass("loading"))return $.Deferred().resolve();var name=nameElement.text().trim();if(getValueSnapshot(nameElement)==name)return $.Deferred().resolve();nameElement.addClass("loading");var promise=toolType.update({id:typeId,name:name});promise.done((function(type){nameElement.removeClass("loading"),nameElement.text(type.name)})),promise.fail((function(){nameElement.removeClass("loading")}))}(element)})),nameElement.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode==KEYS.ENTER&&(e.preventDefault(),nameElement.blur())})),function(element){return!!getActivateButton(element).length}(element)){var activateButton=getActivateButton(element);activateButton.click((function(e){e.preventDefault(),function(element){hasCapabilitiesContainer(element)?function(element){element.addClass("announcement capabilities")}(element):setStatusActive(element)}(element)})),activateButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),activateButton.click())}))}if(hasCapabilitiesContainer(element)){var capabilitiesContainer=getCapabilitiesContainer(element);capabilitiesContainer.on(ltiEvents.CAPABILITIES_AGREE,(function(){setStatusActive(element)})),capabilitiesContainer.on(ltiEvents.CAPABILITIES_DECLINE,(function(){!function(element){element.removeClass("announcement capabilities")}(element)}))}};return{init:function(element){registerEventListeners(element),function(element){var trigger=$("#"+element.data("uniqid")+"-"+element.data("deploymentid")),context={uniqid:element.data("uniqid"),platformid:element.data("platformid"),clientid:element.data("clientid"),deploymentid:element.data("deploymentid"),urls:{publickeyset:element.data("publickeyseturl"),accesstoken:element.data("accesstokenurl"),authrequest:element.data("authrequesturl")}},bodyPromise=templates.render("mod_lti/tool_config_modal_body",context);context={mailto:"mailto:?subject="+encodeURIComponent(element.data("mailtosubject"))+"&body="+encodeURIComponent(element.data("platformidstr"))+":%20"+encodeURIComponent(element.data("platformid"))+"%0D%0A"+encodeURIComponent(element.data("clientidstr"))+":%20"+encodeURIComponent(element.data("clientid"))+"%0D%0A"+encodeURIComponent(element.data("deploymentidstr"))+":%20"+encodeURIComponent(element.data("deploymentid"))+"%0D%0A"+encodeURIComponent(element.data("publickeyseturlstr"))+":%20"+encodeURIComponent(element.data("publickeyseturl"))+"%0D%0A"+encodeURIComponent(element.data("accesstokenurlstr"))+":%20"+encodeURIComponent(element.data("accesstokenurl"))+"%0D%0A"+encodeURIComponent(element.data("authrequesturlstr"))+":%20"+encodeURIComponent(element.data("authrequesturl"))+"%0D%0A"};var footerPromise=templates.render("mod_lti/tool_config_modal_footer",context);modalFactory.create({large:!0,title:element.data("modaltitle"),body:bodyPromise,footer:footerPromise},trigger)}(element)}}})); /** * 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 mod_lti/tool_configure_controller * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/tool_configure_controller",["jquery","core/ajax","core/paged_content_factory","core/notification","core/templates","mod_lti/events","mod_lti/keys","mod_lti/tool_types_and_proxies","mod_lti/tool_type","mod_lti/tool_proxy","core/str","core/config"],(function($,ajax,pagedContentFactory,notification,templates,ltiEvents,KEYS,toolTypesAndProxies,toolType,toolProxy,str,config){var SELECTORS_EXTERNAL_REGISTRATION_CONTAINER="#external-registration-container",SELECTORS_EXTERNAL_REGISTRATION_PAGE_CONTAINER="#external-registration-page-container",SELECTORS_EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER="#external-registration-template-container",SELECTORS_CARTRIDGE_REGISTRATION_CONTAINER="#cartridge-registration-container",SELECTORS_CARTRIDGE_REGISTRATION_FORM="#cartridge-registration-form",SELECTORS_TOOL_CARD_CONTAINER="#tool-card-container",SELECTORS_TOOL_LIST_CONTAINER="#tool-list-container",SELECTORS_TOOL_CREATE_BUTTON="#tool-create-button",SELECTORS_TOOL_CREATE_LTILEGACY_BUTTON="#tool-createltilegacy-button",SELECTORS_REGISTRATION_CHOICE_CONTAINER="#registration-choice-container",SELECTORS_TOOL_URL="#tool-url",getToolListContainer=function(){return $(SELECTORS_TOOL_LIST_CONTAINER)};var getExternalRegistrationContainer=function(){return $(SELECTORS_EXTERNAL_REGISTRATION_CONTAINER)},getCartridgeRegistrationContainer=function(){return $(SELECTORS_CARTRIDGE_REGISTRATION_CONTAINER)},getRegistrationChoiceContainer=function(){return $(SELECTORS_REGISTRATION_CHOICE_CONTAINER)},closeLTIAdvRegistration=function(e){e.data&&"org.imsglobal.lti.close"===e.data.subject&&($(SELECTORS_EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER).empty(),hideExternalRegistration(),showRegistrationChoices(),showToolList(),showRegistrationChoices(),reloadToolList())},getToolURL=function(){return $(SELECTORS_TOOL_URL).val()},hideExternalRegistration=function(){getExternalRegistrationContainer().addClass("hidden")},hideCartridgeRegistration=function(){getCartridgeRegistrationContainer().addClass("hidden")},hideRegistrationChoices=function(){getRegistrationChoiceContainer().addClass("hidden")},showExternalRegistration=function(){hideCartridgeRegistration(),hideRegistrationChoices(),getExternalRegistrationContainer().removeClass("hidden"),screenReaderAnnounce(getExternalRegistrationContainer())},showRegistrationChoices=function(){hideExternalRegistration(),hideCartridgeRegistration(),getRegistrationChoiceContainer().removeClass("hidden"),screenReaderAnnounce(getRegistrationChoiceContainer())},screenReaderAnnounce=function(element){element.children().detach().appendTo(element)},hideToolList=function(){getToolListContainer().addClass("hidden")},showToolList=function(){getToolListContainer().removeClass("hidden")},startLoading=function(element){element.addClass("loading")},stopLoading=function(element){element.removeClass("loading")},reloadToolList=function(){M.util.js_pending("reloadToolList");const cardContainer=$(SELECTORS_TOOL_CARD_CONTAINER),listContainer=getToolListContainer();fetchToolCount().done((function(data){pagedContentFactory.createWithTotalAndLimit(data.count,60,(function(pagesData){return pagesData.map((function(pageData){return fetchToolData(pageData.limit,pageData.offset).then((function(data){return renderToolData(data)}))}))}),{showFirstLast:!0}).done((function(html,js){templates.replaceNodeContents(cardContainer,html,js)})).always((function(){stopLoading(listContainer),M.util.js_complete("reloadToolList")}))})),startLoading(listContainer)};const fetchToolCount=function(){return toolTypesAndProxies.count({orphanedonly:!0}).done((function(data){return data})).catch((function(error){return notification.exception(error),{count:0}}))},fetchToolData=function(limit,offset){const args={orphanedonly:!0};return null===limit||Number.isNaN(limit)||(args.limit=limit),null===offset||Number.isNaN(offset)||(args.offset=offset),toolTypesAndProxies.query(args).done((function(data){return data})).catch((function(error){return notification.exception(error),{types:[],proxies:[],limit:limit,offset:offset}}))},renderToolData=function(data){const context={tools:data.types,proxies:data.proxies};return templates.render("mod_lti/tool_list",context).done((function(html,js){return{html:html,js:js}}))};var addLTIAdvTool=function(){var url=getToolURL().trim();url&&($(SELECTORS_TOOL_URL).val(""),hideToolList(),function(url){$(SELECTORS_EXTERNAL_REGISTRATION_PAGE_CONTAINER).removeClass("hidden"),$(SELECTORS_EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER).append($("<iframe src='startltiadvregistration.php?url="+encodeURIComponent(url)+"&sesskey="+config.sesskey+"'></iframe>")),showExternalRegistration(),window.addEventListener("message",closeLTIAdvRegistration,!1)}(url))},registerEventListeners=function(){$(document).on(ltiEvents.NEW_TOOL_TYPE,(function(){reloadToolList()})),$(document).on(ltiEvents.START_EXTERNAL_REGISTRATION,(function(){showExternalRegistration(),$(SELECTORS_TOOL_URL).val(""),hideToolList()})),$(document).on(ltiEvents.STOP_EXTERNAL_REGISTRATION,(function(){showToolList(),showRegistrationChoices()})),$(document).on(ltiEvents.START_CARTRIDGE_REGISTRATION,(function(event,url){!function(url){hideExternalRegistration(),hideRegistrationChoices();var container=getCartridgeRegistrationContainer();container.find("input").val(""),container.removeClass("hidden"),container.find(SELECTORS_CARTRIDGE_REGISTRATION_FORM).attr("data-cartridge-url",url),screenReaderAnnounce(container)}(url)})),$(document).on(ltiEvents.STOP_CARTRIDGE_REGISTRATION,(function(){getCartridgeRegistrationContainer().find(SELECTORS_CARTRIDGE_REGISTRATION_FORM).removeAttr("data-cartridge-url"),showRegistrationChoices()})),$(document).on(ltiEvents.REGISTRATION_FEEDBACK,(function(event,data){!function(data){var type=data.error?"error":"success";notification.addNotification({message:data.message,type:type})}(data)})),$(SELECTORS_TOOL_CREATE_LTILEGACY_BUTTON).click((function(e){e.preventDefault(),function(){var url=getToolURL().trim();if(""===url)return $.Deferred().resolve();var toolButton=$(SELECTORS_TOOL_CREATE_LTILEGACY_BUTTON);startLoading(toolButton);var promise=toolType.isCartridge(url);promise.always((function(){stopLoading(toolButton)})),promise.done((function(result){result.iscartridge?($(SELECTORS_TOOL_URL).val(""),$(document).trigger(ltiEvents.START_CARTRIDGE_REGISTRATION,url)):$(document).trigger(ltiEvents.START_EXTERNAL_REGISTRATION,{url:url})})),promise.fail((function(){str.get_string("errorbadurl","mod_lti").done((function(s){$(document).trigger(ltiEvents.REGISTRATION_FEEDBACK,{message:s,error:!0})})).fail(notification.exception)}))}()})),$(SELECTORS_TOOL_CREATE_BUTTON).click((function(e){e.preventDefault(),addLTIAdvTool()}))};return{init:function(){registerEventListeners(),reloadToolList()}}})); /** * Provides an interface for a tool proxy in the Moodle server. * * @module mod_lti/tool_proxy * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/tool_proxy",["core/ajax","core/notification"],(function(ajax,notification){return{query:function(args){var request={methodname:"mod_lti_get_tool_proxies",args:args||{}},promise=ajax.call([request])[0];return promise.fail(notification.exception),promise},delete:function(id){var request={methodname:"mod_lti_delete_tool_proxy",args:{id:id}},promise=ajax.call([request])[0];return promise.fail(notification.exception),promise},create:function(args){var request={methodname:"mod_lti_create_tool_proxy",args:args};return ajax.call([request])[0]}}})); /** * Controls all of the behaviour and interaction with a tool type card. These are * listed on the LTI tool type management page. * * See template: mod_lti/tool_proxy_card * * @module mod_lti/tool_proxy_card_controller * @copyright 2016 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/tool_proxy_card_controller",["jquery","core/ajax","core/notification","core/templates","mod_lti/tool_proxy","mod_lti/events","mod_lti/keys","core/str"],(function($,ajax,notification,templates,toolProxy,ltiEvents,KEYS,str){var SELECTORS_DELETE_BUTTON=".delete",SELECTORS_ACTIVATE_BUTTON=".tool-card-footer a.activate",getTypeId=function(element){return element.attr("data-proxy-id")},clearAllAnnouncements=function(element){element.removeClass("announcement loading success fail capabilities")},stopLoading=function(element){element.removeClass("announcement loading")},deleteType=function(element){var promise=$.Deferred(),typeId=getTypeId(element);return function(element){clearAllAnnouncements(element),element.addClass("announcement loading")}(element),""===typeId?$.Deferred().resolve():(str.get_strings([{key:"delete",component:"mod_lti"},{key:"delete_confirmation",component:"mod_lti"},{key:"delete",component:"mod_lti"},{key:"cancel",component:"core"}]).done((function(strs){notification.confirm(strs[0],strs[1],strs[2],strs[3],(function(){toolProxy.delete(typeId).done((function(){stopLoading(element),function(element){var promise=$.Deferred();return clearAllAnnouncements(element),element.addClass("announcement success"),setTimeout((function(){element.removeClass("announcement success"),promise.resolve()}),2e3),promise}(element).done((function(){element.remove(),promise.resolve()})).fail(notification.exception)})).fail((function(error){!function(element){var promise=$.Deferred();clearAllAnnouncements(element),element.addClass("announcement fail"),setTimeout((function(){element.removeClass("announcement fail"),promise.resolve()}),2e3)}(element),promise.reject(error)}))}),(function(){stopLoading(element),promise.resolve()}))})).fail((function(error){stopLoading(element),notification.exception(error),promise.reject(error)})),promise)},registerEventListeners=function(element){var deleteButton=function(element){return element.find(SELECTORS_DELETE_BUTTON)}(element);deleteButton.click((function(e){e.preventDefault(),deleteType(element)})),deleteButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),deleteButton.click())}));var activateButton=function(element){return element.find(SELECTORS_ACTIVATE_BUTTON)}(element);activateButton.click((function(e){e.preventDefault(),function(element){var data={proxyid:getTypeId(element)};$(document).trigger(ltiEvents.START_EXTERNAL_REGISTRATION,data)}(element)})),activateButton.keypress((function(e){e.metaKey||e.shiftKey||e.altKey||e.ctrlKey||e.keyCode!=KEYS.ENTER&&e.keyCode!=KEYS.SPACE||(e.preventDefault(),activateButton.click())}))};return{init:function(element){registerEventListeners(element)}}})); /** * Provides an interface for a tool type in the Moodle server. * * @module mod_lti/tool_type * @copyright 2015 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_lti/tool_type",["core/ajax","core/notification"],(function(ajax,notification){return{query:function(args){var request={methodname:"mod_lti_get_tool_types",args:args||{}},promise=ajax.call([request])[0];return promise.fail(notification.exception),promise},create:function(args){var request={methodname:"mod_lti_create_tool_type",args:args};return ajax.call([request])[0]},update:function(args){var request={methodname:"mod_lti_update_tool_type",args:args},promise=ajax.call([request])[0];return promise.fail(notification.exception),promise},delete:function(id){var request={methodname:"mod_lti_delete_tool_type",args:{id:id}},promise=ajax.call([request])[0];return promise.fail(notification.exception),promise},getFromToolProxyId:function(id){return this.query({toolproxyid:id})},isCartridge:function(url){var request={methodname:"mod_lti_is_cartridge",args:{url:url}};return ajax.call([request])[0]},constants:{state:{configured:1,pending:2,rejected:3}}}})); define("mod_lti/tool_types_and_proxies",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * Provides an interface for external tools in the Moodle server. * * @module mod_lti/tool_types_and_proxies * @class tool_types_and_proxies * @copyright 2020 Andrew Madden <andrewmadden@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.0 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.query=_exports.count=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.query=args=>{const request={methodname:"mod_lti_get_tool_types_and_proxies",args:args||{}};return _ajax.default.call([request])[0]};_exports.count=args=>{const request={methodname:"mod_lti_get_tool_types_and_proxies_count",args:args||{}};return _ajax.default.call([request])[0]}})); /** * Initialise the an add question modal on the quiz page. * * @module mod_quiz/add_question_modal_launcher * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/add_question_modal_launcher",["jquery","core/notification","core/modal_factory"],(function($,Notification,ModalFactory){return{init:function(modalType,selector,contextId,preShowCallback){let showNewCategory=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];var body=$("body");let templateContext={hidden:showNewCategory};return ModalFactory.create({type:modalType,large:!0,templateContext:templateContext,preShowCallback:function(triggerElement,modal){triggerElement=$(triggerElement),modal.setContextId(contextId),modal.setAddOnPageId(triggerElement.attr("data-addonpage")),modal.setTitle(triggerElement.attr("data-header")),preShowCallback&&preShowCallback(triggerElement,modal)}},[body,selector]).fail(Notification.exception)}}})); /** * JavaScript for the add_random_form class. * * @module mod_quiz/add_random_form * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/add_random_form",["jquery","mod_quiz/random_question_form_preview"],(function($,RandomQuestionFormPreview){var SELECTORS_PREVIEW_CONTAINER='[data-region="random-question-preview-container"]',SELECTORS_CATEGORY_FORM_ELEMENT='[name="category"]',SELECTORS_SUBCATEGORY_FORM_ELEMENT='[name="includesubcategories"]',SELECTORS_TAG_IDS_FORM_ELEMENT='[name="fromtags[]"]',getCategorySelectValue=function(form){return form.find(SELECTORS_CATEGORY_FORM_ELEMENT).val()},shouldIncludeSubcategories=function(form,topCategories){return!!function(form,topCategories){var selectedValue=getCategorySelectValue(form);return topCategories.indexOf(selectedValue)>-1}(form,topCategories)||form.find(SELECTORS_SUBCATEGORY_FORM_ELEMENT).is(":checked")},reloadQuestionPreview=function(form,contextId,topCategories){var previewContainer=form.find(SELECTORS_PREVIEW_CONTAINER);RandomQuestionFormPreview.reload(previewContainer,function(form){return getCategorySelectValue(form).split(",")[0]}(form),shouldIncludeSubcategories(form,topCategories),function(form){return form.find(SELECTORS_TAG_IDS_FORM_ELEMENT).val().map((function(value){return value.split(",")[0]}))}(form),contextId)},addEventListeners=function(form,contextId,topCategories){var reloadTimerId=null;const tagsFilter=form.find(SELECTORS_TAG_IDS_FORM_ELEMENT);form.add(tagsFilter).on("change",(function(e){var element;((element=$(e.target)).closest(SELECTORS_CATEGORY_FORM_ELEMENT).length>0||element.closest(SELECTORS_SUBCATEGORY_FORM_ELEMENT).length>0||element.closest(SELECTORS_TAG_IDS_FORM_ELEMENT).length>0)&&(RandomQuestionFormPreview.showLoadingIcon(form),reloadTimerId&&clearTimeout(reloadTimerId),reloadTimerId=setTimeout((function(){reloadQuestionPreview(form,contextId,topCategories)}),2e3))}))};return{init:function(formId,contextId,topCategories,isTagsEnabled){if(1==isTagsEnabled){var form=$("#"+formId);reloadQuestionPreview(form,contextId,topCategories),addEventListeners(form,contextId,topCategories)}}}})); /** * Initialise the add random question modal on the quiz page. * * @module mod_quiz/add_random_question * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/add_random_question",["mod_quiz/add_question_modal_launcher","mod_quiz/modal_add_random_question"],(function(AddQuestionModalLauncher,ModalAddRandomQuestion){return{init:function(contextId,category,returnUrl,cmid){let showNewCategory=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];AddQuestionModalLauncher.init(ModalAddRandomQuestion.TYPE,'.menu [data-action="addarandomquestion"]',contextId,(function(triggerElement,modal){modal.setCategory(category),modal.setReturnUrl(returnUrl),modal.setCMID(cmid)}),showNewCategory)}}})); /** * This class manages the confirmation pop-up (also called the pre-flight check) * that is sometimes shown when a use clicks the start attempt button. * * This is also responsible for opening the pop-up window, if the quiz requires to be in one. * * @module mod_quiz/preflightcheck * @copyright 2016 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("mod_quiz/preflightcheck",["jquery","core/yui","core_form/changechecker"],(function($,Y,FormChangeChecker){var t={confirmDialogue:null,init:function(startButton,confirmationTitle,confirmationForm,popupoptions){var finalStartButton=startButton;Y.use("moodle-core-notification",(function(){Y.one(confirmationForm)&&(t.confirmDialogue=new M.core.dialogue({headerContent:confirmationTitle,bodyContent:Y.one(confirmationForm),draggable:!0,visible:!1,center:!0,modal:!0,width:null,extraClasses:["mod_quiz_preflight_popup"]}),Y.one(startButton).on("click",t.displayDialogue),Y.one("#id_cancel").on("click",t.hideDialogue),finalStartButton=t.confirmDialogue.get("boundingBox").one('[name="submitbutton"]')),popupoptions&&Y.one(finalStartButton).on("click",t.launchQuizPopup,t,popupoptions)}))},displayDialogue:function(e){e&&e.halt(),t.confirmDialogue.show()},hideDialogue:function(e){e&&e.halt(),t.confirmDialogue.hide(e)},launchQuizPopup:function(e,popupoptions){e.halt(),Y.use("io-form",(function(){var form=e.target.ancestor("form");FormChangeChecker.resetFormDirtyState(form.getDOMNode()),window.openpopup(e,{url:form.get("action")+"?"+Y.IO.stringify(form).replace(/\bcancel=/,"x="),windowname:"quizpopup",options:popupoptions,fullscreen:!0})}))}};return t})); define("mod_quiz/question_slot",["exports","core/ajax","core/notification"],(function(_exports,_ajax,_notification){var obj; /** * Render the question slot template for each question in the quiz edit view. * * @module mod_quiz/question_slot * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Guillermo Gomez Arias <guillermogomez@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj};const registerEventListeners=()=>{document.addEventListener("change",(e=>{if(!e.target.matches('[data-action="mod_quiz-select_slot"][data-slot-id]'))return;((slotId,newVersion)=>(0,_ajax.call)([{methodname:"mod_quiz_set_question_version",args:{slotid:slotId,newversion:newVersion}}])[0])(e.target.dataset.slotId,parseInt(e.target.value)).then((()=>{location.reload()})).catch(_notification.default.exception)}))};_exports.init=()=>{registerEventListeners()}})); /** * Initialise the question bank modal on the quiz page. * * @module mod_quiz/quizquestionbank * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/quizquestionbank",["mod_quiz/add_question_modal_launcher","mod_quiz/modal_quiz_question_bank"],(function(AddQuestionModalLauncher,ModalQuizQuestionBank){return{init:function(contextId){AddQuestionModalLauncher.init(ModalQuizQuestionBank.TYPE,'.menu [data-action="questionbank"]',contextId)}}})); /** * JavaScript for the random_question_form_preview of the * add_random_form class. * * @module mod_quiz/random_question_form_preview * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/random_question_form_preview",["jquery","core/ajax","core/str","core/notification","core/templates","core/paged_content_factory"],(function($,Ajax,Str,Notification,Templates,PagedContentFactory){var TEMPLATE_NAME="mod_quiz/random_question_form_preview_question_list",SELECTORS_LOADING_ICON_CONTAINER='[data-region="overlay-icon-container"]',SELECTORS_QUESTION_COUNT_CONTAINER='[data-region="question-count-container"]',SELECTORS_QUESTION_LIST_CONTAINER='[data-region="question-list-container"]',showLoadingIcon=function(root){root.find(SELECTORS_LOADING_ICON_CONTAINER).removeClass("hidden")},hideLoadingIcon=function(root){root.find(SELECTORS_LOADING_ICON_CONTAINER).addClass("hidden")},requestQuestions=function(categoryId,includeSubcategories,tagIds,contextId,limit,offset){var request={methodname:"core_question_get_random_question_summaries",args:{categoryid:categoryId,includesubcategories:includeSubcategories,tagids:tagIds,contextid:contextId,limit:limit,offset:offset}};return Ajax.call([request])[0]};return{reload:function(root,categoryId,includeSubcategories,tagIds,contextId){return showLoadingIcon(root),requestQuestions(categoryId,includeSubcategories,tagIds,contextId,5,0).then((function(response){var totalCount=response.totalcount;return function(root,questionCount){Str.get_string("questionsmatchingfilter","mod_quiz",questionCount).then((function(string){root.find(SELECTORS_QUESTION_COUNT_CONTAINER).html(string)})).fail(Notification.exception)}(root,totalCount),response})).then((function(response){var totalQuestionCount=response.totalcount,questions=response.questions;return questions.length?function(categoryId,includeSubcategories,tagIds,contextId,totalQuestionCount,firstPageQuestions){return PagedContentFactory.createFromAjax(totalQuestionCount,5,(function(pagesData){return pagesData.map((function(pageData){var limit=pageData.limit,offset=pageData.offset;return 0==offset?Templates.render(TEMPLATE_NAME,{questions:firstPageQuestions}):requestQuestions(categoryId,includeSubcategories,tagIds,contextId,limit,offset).then((function(response){var questions=response.questions;return Templates.render(TEMPLATE_NAME,{questions:questions})})).fail(Notification.exception)}))}))}(categoryId,includeSubcategories,tagIds,contextId,totalQuestionCount,questions):$.Deferred().resolve("","")})).then((function(html,js){var container=root.find(SELECTORS_QUESTION_LIST_CONTAINER);Templates.replaceNodeContents(container,html,js)})).always((function(){hideLoadingIcon(root)})).fail(Notification.exception)},showLoadingIcon:showLoadingIcon,hideLoadingIcon:hideLoadingIcon}})); /** * Initialise the repaginate dialogue on quiz editing page. * * @module mod_quiz/repaginate * @copyright 2019 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/repaginate",["jquery","core/modal_factory"],(function($,ModalFactory){var SELECTORS_REPAGINATECOMMAND="#repaginatecommand",SELECTORS_HEADER="header",SELECTORS_BODY="form";return{init:function(){ModalFactory.create({title:$(SELECTORS_REPAGINATECOMMAND).data(SELECTORS_HEADER),body:$(SELECTORS_REPAGINATECOMMAND).data(SELECTORS_BODY),large:!1},$(SELECTORS_REPAGINATECOMMAND))}}})); /** * Contain the logic for the add random question modal. * * @module mod_quiz/modal_add_random_question * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/modal_add_random_question",["jquery","core/notification","core/modal","core/modal_events","core/modal_registry","core/fragment","core/templates","core_form/changechecker"],(function($,Notification,Modal,ModalEvents,ModalRegistry,Fragment,Templates,FormChangeChecker){var registered=!1,SELECTORS_EXISTING_CATEGORY_CONTAINER='[data-region="existing-category-container"]',SELECTORS_EXISTING_CATEGORY_FORM_ELEMENT="#id_existingcategoryheader",SELECTORS_NEW_CATEGORY_CONTAINER='[data-region="new-category-container"]',SELECTORS_NEW_CATEGORY_FORM_ELEMENT="#id_newcategoryheader",SELECTORS_TAB_CONTENT='[data-region="tab-content"]',SELECTORS_ADD_ON_PAGE_FORM_ELEMENT='[name="addonpage"]',SELECTORS_SUBMIT_BUTTON_ELEMENT='input[type="submit"]',SELECTORS_CANCEL_BUTTON_ELEMENT='input[type="submit"][name="cancel"]',SELECTORS_FORM_HEADER="legend",SELECTORS_BUTTON_CONTAINER=".fitem",ModalAddRandomQuestion=function(root){Modal.call(this,root),this.contextId=null,this.addOnPageId=null,this.category=null,this.returnUrl=null,this.cmid=null,this.loadedForm=!1};return ModalAddRandomQuestion.TYPE="mod_quiz-quiz-add-random-question",(ModalAddRandomQuestion.prototype=Object.create(Modal.prototype)).constructor=ModalAddRandomQuestion,ModalAddRandomQuestion.prototype.setContextId=function(id){this.contextId=id},ModalAddRandomQuestion.prototype.getContextId=function(){return this.contextId},ModalAddRandomQuestion.prototype.setAddOnPageId=function(id){this.addOnPageId=id,this.getBody().find(SELECTORS_ADD_ON_PAGE_FORM_ELEMENT).val(id)},ModalAddRandomQuestion.prototype.getAddOnPageId=function(){return this.addOnPageId},ModalAddRandomQuestion.prototype.setCategory=function(category){this.category=category},ModalAddRandomQuestion.prototype.getCategory=function(){return this.category},ModalAddRandomQuestion.prototype.setReturnUrl=function(url){this.returnUrl=url},ModalAddRandomQuestion.prototype.getReturnUrl=function(){return this.returnUrl},ModalAddRandomQuestion.prototype.setCMID=function(id){this.cmid=id},ModalAddRandomQuestion.prototype.getCMID=function(){return this.cmid},ModalAddRandomQuestion.prototype.moveFormElementIntoTab=function(formElement,tabElement){var submitButtons=formElement.find(SELECTORS_SUBMIT_BUTTON_ELEMENT),footer=$('<div class="modal-footer mt-1" data-region="footer"></div>');formElement.find(SELECTORS_FORM_HEADER).addClass("hidden"),formElement.wrap(tabElement),submitButtons.closest(SELECTORS_BUTTON_CONTAINER).remove(),submitButtons.appendTo(footer),footer.appendTo(formElement)},ModalAddRandomQuestion.prototype.moveTabsIntoTabContent=function(form){var tabContent=this.getBody().find(SELECTORS_TAB_CONTENT).empty();form.find('[role="tabpanel"]').wrapAll(tabContent)},ModalAddRandomQuestion.prototype.moveCancelButtonToTabs=function(form){var cancelButton=form.find(SELECTORS_CANCEL_BUTTON_ELEMENT).addClass("ml-1"),tabFooters=form.find('[data-region="footer"]');cancelButton.closest(SELECTORS_BUTTON_CONTAINER).remove(),cancelButton.clone().appendTo(tabFooters)},ModalAddRandomQuestion.prototype.loadForm=function(){return Fragment.loadFragment("mod_quiz","add_random_question_form",this.getContextId(),{addonpage:this.getAddOnPageId(),cat:this.getCategory(),returnurl:this.getReturnUrl(),cmid:this.getCMID()}).then(function(html,js){var form=$(html),existingCategoryFormElement=form.find(SELECTORS_EXISTING_CATEGORY_FORM_ELEMENT),existingCategoryTab=this.getBody().find(SELECTORS_EXISTING_CATEGORY_CONTAINER),newCategoryFormElement=form.find(SELECTORS_NEW_CATEGORY_FORM_ELEMENT),newCategoryTab=this.getBody().find(SELECTORS_NEW_CATEGORY_CONTAINER);this.moveFormElementIntoTab(existingCategoryFormElement,existingCategoryTab),this.moveFormElementIntoTab(newCategoryFormElement,newCategoryTab),this.moveTabsIntoTabContent(form),this.moveCancelButtonToTabs(form),Templates.replaceNode(this.getBody().find(SELECTORS_TAB_CONTENT),form,js)}.bind(this)).then((function(){FormChangeChecker.disableAllChecks()})).fail(Notification.exception)},ModalAddRandomQuestion.prototype.show=function(){Modal.prototype.show.call(this),this.loadedForm||(this.loadForm(),this.loadedForm=!0)},registered||(ModalRegistry.register(ModalAddRandomQuestion.TYPE,ModalAddRandomQuestion,"mod_quiz/modal_add_random_question"),registered=!0),ModalAddRandomQuestion})); /** * Contain the logic for the question bank modal. * * @module mod_quiz/modal_quiz_question_bank * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_quiz/modal_quiz_question_bank",["jquery","core/notification","core/modal","core/modal_events","core/modal_registry","core/fragment","core_form/changechecker"],(function($,Notification,Modal,ModalEvents,ModalRegistry,Fragment,FormChangeChecker){var registered=!1,SELECTORS_ADD_TO_QUIZ_CONTAINER="td.addtoquizaction",SELECTORS_ANCHOR="a[href]",SELECTORS_PREVIEW_CONTAINER="td.previewaction",SELECTORS_SEARCH_OPTIONS="#advancedsearch",SELECTORS_DISPLAY_OPTIONS="#displayoptions",SELECTORS_ADD_QUESTIONS_FORM="form#questionsubmit",ModalQuizQuestionBank=function(root){Modal.call(this,root),this.contextId=null,this.addOnPageId=null};return ModalQuizQuestionBank.TYPE="mod_quiz-quiz-question-bank",(ModalQuizQuestionBank.prototype=Object.create(Modal.prototype)).constructor=ModalQuizQuestionBank,ModalQuizQuestionBank.prototype.setContextId=function(id){this.contextId=id},ModalQuizQuestionBank.prototype.getContextId=function(){return this.contextId},ModalQuizQuestionBank.prototype.setAddOnPageId=function(id){this.addOnPageId=id},ModalQuizQuestionBank.prototype.getAddOnPageId=function(){return this.addOnPageId},ModalQuizQuestionBank.prototype.show=function(){return this.reloadBodyContent(window.location.search),Modal.prototype.show.call(this)},ModalQuizQuestionBank.prototype.reloadBodyContent=function(queryString){var promise=Fragment.loadFragment("mod_quiz","quiz_question_bank",this.getContextId(),{querystring:queryString}).fail(Notification.exception);this.setBody(promise)},ModalQuizQuestionBank.prototype.handleAddToQuizEvent=function(e,anchorElement){var href=anchorElement.attr("href")+"&addonpage="+this.getAddOnPageId();anchorElement.attr("href",href)},ModalQuizQuestionBank.prototype.handlePreviewContainerEvent=function(e,anchorElement){window.openpopup(e,{url:anchorElement.attr("href"),name:"questionpreview",options:["height=600","width=800","top=0","left=0","menubar=0","location=0","scrollbars","resizable","toolbar","status","directories=0","fullscreen=0","dependent"].join(",")})},ModalQuizQuestionBank.prototype.handleDisplayOptionFormEvent=function(e){e.stopPropagation(),e.preventDefault();var queryString="?"+$(e.target).closest(SELECTORS_DISPLAY_OPTIONS).serialize();this.reloadBodyContent(queryString)},ModalQuizQuestionBank.prototype.registerDisplayOptionListeners=function(){this.getModal().on("change",SELECTORS_DISPLAY_OPTIONS,function(e){$(e.target).attr("aria-autocomplete")||this.handleDisplayOptionFormEvent(e)}.bind(this)),this.getModal().on("submit",SELECTORS_DISPLAY_OPTIONS,function(e){this.handleDisplayOptionFormEvent(e)}.bind(this))},ModalQuizQuestionBank.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.registerDisplayOptionListeners(),this.getModal().on("submit",SELECTORS_ADD_QUESTIONS_FORM,function(e){var formElement=$(e.currentTarget);$("<input />").attr("type","hidden").attr("name","addonpage").attr("value",this.getAddOnPageId()).appendTo(formElement)}.bind(this)),this.getModal().on("click",SELECTORS_ANCHOR,function(e){var anchorElement=$(e.currentTarget);anchorElement.closest(SELECTORS_ADD_TO_QUIZ_CONTAINER).length?this.handleAddToQuizEvent(e,anchorElement):anchorElement.closest(SELECTORS_PREVIEW_CONTAINER).length?this.handlePreviewContainerEvent(e,anchorElement):anchorElement.closest(SELECTORS_SEARCH_OPTIONS).length||(e.preventDefault(),this.reloadBodyContent(anchorElement.prop("search")))}.bind(this)),this.getRoot().on(ModalEvents.bodyRendered,(function(){FormChangeChecker.disableAllChecks()}))},registered||(ModalRegistry.register(ModalQuizQuestionBank.TYPE,ModalQuizQuestionBank,"core/modal"),registered=!0),ModalQuizQuestionBank})); define("mod_quiz/submission_confirmation",["exports","core/notification","core/prefetch","core/templates","core/str"],(function(_exports,_notification,_prefetch,_templates,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A javascript module to handle submission confirmation for quiz. * * @module mod_quiz/submission_confirmation * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 4.1 */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_prefetch=_interopRequireDefault(_prefetch),_templates=_interopRequireDefault(_templates);const SELECTOR_attemptSubmitButton=".path-mod-quiz .btn-finishattempt button",SELECTOR_attemptSubmitForm="form#frm-finishattempt",TEMPLATES_submissionConfirmation="mod_quiz/submission_confirmation";_exports.init=unAnsweredQuestions=>{_prefetch.default.prefetchStrings("core",["submit"]),_prefetch.default.prefetchStrings("core_admin",["confirmation"]),_prefetch.default.prefetchStrings("quiz",["submitallandfinish","submission_confirmation"]),_prefetch.default.prefetchTemplate(TEMPLATES_submissionConfirmation),(unAnsweredQuestions=>{const submitAction=document.querySelector(SELECTOR_attemptSubmitButton);submitAction&&submitAction.addEventListener("click",(async e=>{e.preventDefault();try{await(0,_notification.saveCancelPromise)((0,_str.get_string)("submission_confirmation","quiz"),_templates.default.render(TEMPLATES_submissionConfirmation,{hasunanswered:unAnsweredQuestions>0,totalunanswered:unAnsweredQuestions}),(0,_str.get_string)("submitallandfinish","quiz")),submitAction.closest(SELECTOR_attemptSubmitForm).submit()}catch{return}}))})(unAnsweredQuestions)}})); /** * Javascript to handle survey validation. * * @module mod_survey/validation * @copyright 2017 Dan Poltawski <dan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.3 */ define("mod_survey/validation",["jquery","core/str","core/modal_factory","core/notification"],(function($,Str,ModalFactory,Notification){return{ensureRadiosChosen:function(formid){var modalPromise=Str.get_strings([{key:"error",component:"moodle"},{key:"questionsnotanswered",component:"survey"}]).then((function(strings){return ModalFactory.create({type:ModalFactory.types.CANCEL,title:strings[0],body:strings[1]})})).catch(Notification.exception),form=$("#"+formid);form.submit((function(e){return 0===form.find('input:radio[data-survey-default="true"]:checked').length||(e.preventDefault(),modalPromise.then((function(modal){return modal.show(),!1})))}))}}})); define('mod_turnitintooltwo/modal_migration_tool', ["jquery","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events","core/config","mod_turnitintooltwo/migration_tool_migrate"],function(a,b,c,d,e,f,g,h){var i=!1,j={MIGRATE_BUTTON:'[data-action="migrate-assignment"]',CANCEL_BUTTON:'[data-action="cancel"]'},k=function(a){d.call(this,a)};return k.TYPE="mod_turnitintooltwo-migration_tool",k.prototype=Object.create(d.prototype),k.prototype.constructor=k,k.prototype.registerEventListeners=function(){d.prototype.registerEventListeners.call(this),this.getModal().on(c.events.activate,j.MIGRATE_BUTTON,function(){a(".asktomigrate").hide(),a(".migrating").show(),h.migration_tool_migrate(a("#migrate_type").data("courseid"),a("#migrate_type").data("turnitintoolid"))}.bind(this)),this.getModal().on(c.events.activate,j.CANCEL_BUTTON,function(b,c){var d=a.Event(f.cancel);this.getRoot().trigger(d,this),d.isDefaultPrevented()||(this.hide(),c.originalEvent.preventDefault())}.bind(this))},i||(e.register(k.TYPE,k,"mod_turnitintooltwo/modal_migration_tool"),i=!0),k}); define('mod_turnitintooltwo/migration_tool_migrate', ["jquery"],function(a){return{migration_tool_migrate:function(b,c){a.ajax({dataType:"json",type:"POST",url:M.cfg.wwwroot+"/mod/turnitintooltwo/ajax.php",data:{action:"begin_migration",courseid:b,turnitintoolid:c,sesskey:M.cfg.sesskey},success:function(a){window.location.href=M.cfg.wwwroot+"/mod/turnitintooltwo/view.php?id="+a.id},error:function(b){var c=b.responseJSON;a("#turnitintool_style").prepend('<div id="full-error" class="box generalbox noticebox">'+c.error+" "+c.message+"</div>")}})}}}); define('mod_turnitintooltwo/migration_tool_launch', ["jquery","core/templates","core/modal_factory","core/modal_events","mod_turnitintooltwo/modal_migration_tool","mod_turnitintooltwo/migration_tool_migrate"],function(a,b,c,d,e,f){return{migration_tool_launch:function(){a.ajax({dataType:"json",type:"POST",url:M.cfg.wwwroot+"/mod/turnitintooltwo/ajax.php",data:{action:"check_migrated",turnitintoolid:a("#migrate_type").data("turnitintoolid"),sesskey:M.cfg.sesskey},success:function(b){b.migrated===!0?window.location.href=M.cfg.wwwroot+"/mod/turnitintooltwo/view.php?id="+b.v2id:c.create({type:e.TYPE}).then(function(b){b.show(),2===a("#migrate_type").data("migratetype")&&(a(".asktomigrate").hide(),a(".migrating").show(),f.migration_tool_migrate(a("#migrate_type").data("courseid"),a("#migrate_type").data("turnitintoolid")))})}})}}}); /** * Additional javascript for the Workshop module form. * * @module mod_workshop/modform * @copyright The Open University 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_workshop/modform",["jquery"],(function($){var submissionTypes={text:{available:null,required:null,requiredHidden:null},file:{available:null,required:null,requiredHidden:null}};function checkAvailability(checkUnavailable,checkAvailable){checkUnavailable.available.prop("checked")||(checkUnavailable.required.prop("disabled",!0),checkUnavailable.required.prop("checked",!1),checkAvailable.available.prop("checked")&&(checkAvailable.required.prop("disabled",!0),checkAvailable.required.prop("checked",!0),checkAvailable.requiredHidden.val(1)))}function enableRequired(submissionType){submissionType.required.prop("disabled",!1),submissionType.required.prop("checked",!1),submissionType.requiredHidden.val(0)}function submissionTypeChanged(){checkAvailability(submissionTypes.file,submissionTypes.text),checkAvailability(submissionTypes.text,submissionTypes.file),submissionTypes.text.available.prop("checked")&&submissionTypes.file.available.prop("checked")&&(enableRequired(submissionTypes.text),enableRequired(submissionTypes.file))}return{init:function(){submissionTypes.text.available=$("#id_submissiontypetextavailable"),submissionTypes.text.required=$("#id_submissiontypetextrequired"),submissionTypes.text.requiredHidden=$('input[name="submissiontypetextrequired"][type="hidden"]'),submissionTypes.file.available=$("#id_submissiontypefileavailable"),submissionTypes.file.required=$("#id_submissiontypefilerequired"),submissionTypes.file.requiredHidden=$('input[name="submissiontypefilerequired"][type="hidden"]'),submissionTypes.text.available.on("change",submissionTypeChanged),submissionTypes.file.available.on("change",submissionTypeChanged),submissionTypeChanged()}}})); /** * Sets the equal height to the user plan widget boxes. * * @module mod_workshop/workshopview * @category output * @copyright Loc Nguyen <loc.nguyendinh@harveynash.vn> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_workshop/workshopview",["jquery"],(function($){function equalHeight(group){var tallest=0;group.height("auto"),group.each((function(){var thisHeight=$(this).height();thisHeight>tallest&&(tallest=thisHeight)})),group.height(tallest)}return{init:function(){var $dt=$(".path-mod-workshop .userplan dt"),$dd=$(".path-mod-workshop .userplan dd");equalHeight($dt),equalHeight($dd),$(window).on("resize",(function(){equalHeight($dt),equalHeight($dd)}))}}})); define("mod_zoom/scheduleforchooser",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Schedule for selection handler. * * @module mod_zoom/scheduleforchooser * @copyright 2022 Antonio Duran Terres <antonio@joomdle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const Selectors_fields={selector:'[data-scheduleforchooser-field="selector"]',updateButton:'[data-scheduleforchooser-field="updateButton"]'};_exports.init=()=>{document.querySelector(Selectors_fields.selector).addEventListener("change",(e=>{const form=e.target.closest("form"),updateButton=form.querySelector(Selectors_fields.updateButton),fieldset=updateButton.closest("fieldset"),url=new URL(form.action);url.hash=fieldset.id,form.action=url.toString(),updateButton.click()}))}})); /** * Populates or de-populates password field based on whether the * password is required or not. * * @copyright 2018 UC Regents * @author Kubilay Agi * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("mod_zoom/form",["jquery","core/form-autocomplete","core/str","core/notification"],(function($,autocomplete,str,notification){var SELECTORS_REPEAT_SELECT='select[name="recurrence_type"]',SELECTORS_REPEAT_INTERVAL=".repeat_interval",SELECTORS_REPEAT_INTERVAL_DAILY="#interval_daily",SELECTORS_REPEAT_INTERVAL_WEEKLY="#interval_weekly",SELECTORS_REPEAT_INTERVAL_MONTHLY="#interval_monthly",SELECTORS_REPEAT_INTERVAL_OPTIONS='select[name="repeat_interval"] option',SELECTORS_START_TIME='select[name*="start_time"]',SELECTORS_DURATION='*[name*="duration"]',SELECTORS_RECURRING='input[name="recurring"][type!="hidden"]',SELECTORS_OPTION_JBH='input[name="option_jbh"][type!="hidden"]',SELECTORS_OPTION_WAITING_ROOM='input[name="option_waiting_room"][type!="hidden"]',REPEAT_OPTIONS_REPEAT_OPTION_NONE=0,REPEAT_OPTIONS_REPEAT_OPTION_DAILY=1,REPEAT_OPTIONS_REPEAT_OPTION_WEEKLY=2,REPEAT_OPTIONS_REPEAT_OPTION_MONTHLY=3,REPEAT_MAX_OPTIONS_REPEAT_OPTION_WEEKLY=12,REPEAT_MAX_OPTIONS_REPEAT_OPTION_MONTHLY=3,toggleStartTimeDuration=function(){var disabled=!1,repeatVal=parseInt($(SELECTORS_REPEAT_SELECT).val(),10);$(SELECTORS_RECURRING).prop("checked")&&repeatVal===REPEAT_OPTIONS_REPEAT_OPTION_NONE&&(disabled=!0),$(SELECTORS_START_TIME).prop("disabled",disabled),$(SELECTORS_DURATION).prop("disabled",disabled)},toggleRepeatIntervalText=function(){$(SELECTORS_REPEAT_INTERVAL).hide();var repeatSelectVal=parseInt($(SELECTORS_REPEAT_SELECT).val(),10);repeatSelectVal===REPEAT_OPTIONS_REPEAT_OPTION_DAILY?$(SELECTORS_REPEAT_INTERVAL_DAILY).show():repeatSelectVal===REPEAT_OPTIONS_REPEAT_OPTION_WEEKLY?$(SELECTORS_REPEAT_INTERVAL_WEEKLY).show():repeatSelectVal===REPEAT_OPTIONS_REPEAT_OPTION_MONTHLY&&$(SELECTORS_REPEAT_INTERVAL_MONTHLY).show()},limitRepeatValues=function(){var selectedValue=parseInt($(SELECTORS_REPEAT_SELECT).val(),10);$(SELECTORS_REPEAT_INTERVAL_OPTIONS).each((function(){selectedValue===REPEAT_OPTIONS_REPEAT_OPTION_WEEKLY?this.value>REPEAT_MAX_OPTIONS_REPEAT_OPTION_WEEKLY&&$(this).hide():selectedValue===REPEAT_OPTIONS_REPEAT_OPTION_MONTHLY?this.value>REPEAT_MAX_OPTIONS_REPEAT_OPTION_MONTHLY&&$(this).hide():$(this).show()}))},TabsComponent=function(tabsColumn,tabsContentColumn,initialTabsCount,emptyAlert){this.tabsColumn=tabsColumn,this.tabsContentColumn=tabsContentColumn,this.emptyAlert=emptyAlert,this.countTabs=initialTabsCount,this.buildTab=function(item){var tab=item.tab.element,tabLink=$(".nav-link",tab);return tab.attr("id","tab-"+this.countTabs),$(".tab-name",tabLink).text(item.tab.name),tabLink.attr("href","#link"+this.countTabs),$("li a",this.tabsColumn).removeClass("active"),tabLink.addClass("active"),tab},this.buildTabContent=function(item){var tabContent=item.tabContent.element;return tabContent.attr("id","link"+this.countTabs),$(".tab-pane",this.tabsContentColumn).removeClass("active"),tabContent.addClass("active"),tabContent},this.addTab=function(item){var tab=this.buildTab(item),tabContent=this.buildTabContent(item);return this.emptyAlert.addClass("hidden"),$("ul",this.tabsColumn).append(tab),$(".tab-content",this.tabsContentColumn).append(tabContent),{element:tab,content:tabContent}},this.deleteTab=function(item){var tab=item,tabContent=$($("a",tab).attr("href"));(tab.remove(),tabContent.remove(),$("li",this.tabsColumn).length)?$("li a.active",this.tabsColumn).length||$("li:first-child a",this.tabsColumn).trigger("click"):this.emptyAlert.removeClass("hidden")}},BreakoutroomsEditor=function(){this.roomsListColumn=$("#meeting-rooms-list"),this.roomsList=$("ul",this.roomsListColumn),this.addBtn=$("#add-room",this.roomsListColumn),this.emptyAlert=$(".empty-alert",this.roomsListColumn),this.deleteBtn=$(".delete-room",this.roomsListColumn),this.roomsDataColumn=$("#meeting-rooms-data"),this.roomItemToClone=$("#rooms-list-item").html(),this.roomItemDataToClone=$("#rooms-list-item-data").html(),this.initialRoomsCount=parseInt(this.roomsListColumn.attr("data-initial-rooms-count")),this.tabsComponent=new TabsComponent(this.roomsListColumn,this.roomsDataColumn,this.initialRoomsCount,this.emptyAlert),this.init=function(){str.get_strings([{key:"room",component:"zoom"}]).then((function(){return null})).fail(notification.exception),this.addRoomEvent(),this.deleteRoomEvent(),$("li",this.roomsListColumn).length?(this.changeRoomNameEvent(),this.buildAutocompleteComponents()):this.emptyAlert.removeClass("hidden")},this.addRoomEvent=function(){var thisObject=this;thisObject.addBtn.click((function(){thisObject.tabsComponent.countTabs++;var newRoomName=M.util.get_string("room","zoom")+" "+thisObject.tabsComponent.countTabs,newRoomElement=$(thisObject.roomItemToClone),newRoomDataElement=$(thisObject.roomItemDataToClone),newRoomIndex=thisObject.tabsComponent.countTabs,roomNameInputId="room-name-"+newRoomIndex;$("input[type=text]",newRoomDataElement).prev().attr("for",roomNameInputId),$("input[type=text]",newRoomDataElement).attr("id",roomNameInputId),$("input[type=text]",newRoomDataElement).attr("name",roomNameInputId),$("input[type=text]",newRoomDataElement).val(newRoomName),$("input[type=text]",newRoomDataElement).next().attr("name","rooms["+newRoomIndex+"]"),$("input[type=text]",newRoomDataElement).next().val(newRoomName);var roomParticipantsSelectId="participants-"+newRoomIndex;$(".room-participants",newRoomDataElement).attr("id",roomParticipantsSelectId),$(".room-participants",newRoomDataElement).attr("name","roomsparticipants["+newRoomIndex+"][]");var roomGroupsSelectId="groups-"+newRoomIndex;$(".room-groups",newRoomDataElement).attr("id",roomGroupsSelectId),$(".room-groups",newRoomDataElement).attr("name","roomsgroups["+newRoomIndex+"][]");var newRoom={tab:{name:newRoomName,element:newRoomElement},tabContent:{element:newRoomDataElement}},addedTab=thisObject.tabsComponent.addTab(newRoom);$("li:last .delete-room",thisObject.roomsList).click((function(){var thisItem=$(this).closest("li");thisObject.tabsComponent.deleteTab(thisItem)})),$("input[type=text]",addedTab.content).on("change keyup paste",(function(){var newHiddenValue=this.value;$(this).next().val(newHiddenValue),$(".tab-name",addedTab.element).text(this.value)})),thisObject.buildAutocompleteComponent(roomParticipantsSelectId,"addparticipant"),thisObject.buildAutocompleteComponent(roomGroupsSelectId,"addparticipantgroup")}))},this.deleteRoomEvent=function(){var thisObject=this;thisObject.deleteBtn.click((function(){var thisItem=$(this).closest("li");thisObject.tabsComponent.deleteTab(thisItem)}))},this.changeRoomNameEvent=function(){var thisObject=this;$("li",this.roomsListColumn).each((function(){var tabIndex=$(this).attr("id").split("-")[1];$('input[name="room-name-'+tabIndex+'"]',thisObject.roomsDataColumn).on("change keyup paste",(function(){var newHiddenValue=this.value;$(this).next().val(newHiddenValue),$("#tab-"+tabIndex+" .tab-name").text(this.value)}))}))},this.buildAutocompleteComponents=function(){var thisObject=this;$(".room-participants",thisObject.roomsDataColumn).each((function(){var thisItemId=$(this).attr("id");thisObject.buildAutocompleteComponent(thisItemId,"addparticipant")})),$(".room-groups",thisObject.roomsDataColumn).each((function(){var thisItemId=$(this).attr("id");thisObject.buildAutocompleteComponent(thisItemId,"addparticipantgroup")}))},this.buildAutocompleteComponent=function(id,placeholder){var stringkeys=[{key:placeholder,component:"zoom"},{key:"selectionarea",component:"zoom"}];str.get_strings(stringkeys).then((function(langstrings){var placeholderString=langstrings[0],noSelectionString=langstrings[1];return autocomplete.enhance("#"+id,!1,"",placeholderString,!1,!0,noSelectionString,!0),null})).fail(notification.exception)}};return{init:function(){var optionJoinBeforeHost=$(SELECTORS_OPTION_JBH),optionWaitingRoom=$(SELECTORS_OPTION_WAITING_ROOM);optionJoinBeforeHost.change((function(){!0===optionJoinBeforeHost.is(":checked")&&optionWaitingRoom.prop("checked",!1)})),optionWaitingRoom.change((function(){!0===optionWaitingRoom.is(":checked")&&optionJoinBeforeHost.prop("checked",!1)})),toggleStartTimeDuration(),toggleRepeatIntervalText(),limitRepeatValues(),$(SELECTORS_REPEAT_SELECT).change((function(){toggleStartTimeDuration(),toggleRepeatIntervalText(),limitRepeatValues()})),$(SELECTORS_RECURRING).change((function(){toggleStartTimeDuration()})),(new BreakoutroomsEditor).init()}}})); define("mod_zoom/toggle_text",["exports","core/str"],(function(_exports,_str){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=()=>{const button=document.querySelector("#show-more-button");if(null!==button){const body=document.querySelector("#show-more-body");button.addEventListener("click",(async()=>{""===body.style.display?(body.style.display="none",button.innerHTML=await(0,_str.get_string)("meeting_invite_show","mod_zoom")):(body.style.display="",button.innerHTML=await(0,_str.get_string)("meeting_invite_hide","mod_zoom"))}))}}})); define("enrol_lti/content_select",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=()=>{document.addEventListener("change",(e=>{if(e.target.matches("input[type='checkbox'][name^='modules']")){const value=e.target.value,gradecheckbox=document.querySelector("input[type='checkbox'][name^='grades'][value='"+value+"']");gradecheckbox&&(gradecheckbox.checked=e.target.checked)}if(e.target.matches("input[type='checkbox'][name^='grades']")){const value=e.target.value,modcheckbox=document.querySelector("input[type='checkbox'][name^='modules'][value='"+value+"']");e.target.checked&&(modcheckbox.checked=!0)}}))}})); define("enrol_lti/tool_endpoints",["exports","core/copy_to_clipboard"],(function(_exports,_copy_to_clipboard){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Module supporting the dynamic and manual registration URLs in the tool registration admin setting. * * @module enrol_lti/tool_endpoints * @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS_URL_VALUE='[id^="lti_tool_endpoint_url_"]',focusURLHandler=event=>{const triggerElement=event.target.closest(SELECTORS_URL_VALUE);null!==triggerElement&&(event.preventDefault(),triggerElement.select())};_exports.init=()=>{document.addEventListener("focusin",focusURLHandler)}})); /** * Potential user selector module. * * @module enrol_manual/form-potential-user-selector * @copyright 2016 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("enrol_manual/form-potential-user-selector",["jquery","core/ajax","core/templates","core/str"],(function($,Ajax,Templates,Str){return{processResults:function(selector,results){var users=[];return $.isArray(results)?($.each(results,(function(index,user){users.push({value:user.id,label:user._label})})),users):results},transport:function(selector,query,success,failure){var courseid=$(selector).attr("courseid"),userfields=$(selector).attr("userfields").split(",");void 0===courseid&&(courseid="1");var enrolid=$(selector).attr("enrolid");void 0===enrolid&&(enrolid="");var perpage=parseInt($(selector).attr("perpage"));isNaN(perpage)&&(perpage=100),Ajax.call([{methodname:"core_enrol_get_potential_users",args:{courseid:courseid,enrolid:enrolid,search:query,searchanywhere:!0,page:0,perpage:perpage+1}}])[0].then((function(results){var promises=[],i=0;if(results.length<=perpage){const profileRegex=/^profile_field_(.*)$/;return $.each(results,(function(index,user){var ctx=user,identity=[];$.each(userfields,(function(i,k){const result=profileRegex.exec(k);result?user.customfields&&user.customfields.forEach((function(customfield){customfield.shortname===result[1]&&(ctx.hasidentity=!0,identity.push(customfield.value))})):void 0!==user[k]&&""!==user[k]&&(ctx.hasidentity=!0,identity.push(user[k]))})),ctx.identity=identity.join(", "),promises.push(Templates.render("enrol_manual/form-user-selector-suggestion",ctx))})),$.when.apply($.when,promises).then((function(){var args=arguments;$.each(results,(function(index,user){user._label=args[i],i++})),success(results)}))}return Str.get_string("toomanyuserstoshow","core",">"+perpage).then((function(toomanyuserstoshow){success(toomanyuserstoshow)}))})).fail(failure)}}})); define("enrol_manual/quickenrolment",["exports","core_table/dynamic","core/str","core/toast","core/config","core/fragment","core/modal_events","core/modal_factory","core/notification","jquery","core/pending","core/prefetch"],(function(_exports,DynamicTable,Str,Toast,_config,_fragment,_modal_events,_modal_factory,_notification,_jquery,_pending,_prefetch){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Quick enrolment AMD module. * * @module enrol_manual/quickenrolment * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,DynamicTable=_interopRequireWildcard(DynamicTable),Str=_interopRequireWildcard(Str),Toast=_interopRequireWildcard(Toast),_config=_interopRequireDefault(_config),_fragment=_interopRequireDefault(_fragment),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification),_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending),_prefetch=_interopRequireDefault(_prefetch);const Selectors_cohortSelector="#id_cohortlist",Selectors_triggerButtons=".enrolusersbutton.enrol_manual_plugin [type='submit']",Selectors_unwantedHiddenFields="input[value='_qf__force_multiselect_submission']",Selectors_buttonWrapper='[data-region="wrapper"]',getBodyForContext=contextId=>_fragment.default.loadFragment("enrol_manual","enrol_users_form",contextId,{}),registerEventListeners=contextId=>{document.addEventListener("click",(e=>{if(e.target.closest(Selectors_triggerButtons))return e.preventDefault(),void showModal((element=>{const wrapper=element.closest(Selectors_buttonWrapper);return DynamicTable.getTableFromId(wrapper.dataset.tableUniqueid)})(e.target),contextId)}))},showModal=(dynamicTable,contextId)=>{const pendingPromise=new _pending.default("enrol_manual/quickenrolment:showModal");return _modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,large:!0,title:Str.get_string("enrolusers","enrol_manual"),body:getBodyForContext(contextId),buttons:{save:Str.get_string("enrolusers","enrol_manual")}}).then((modal=>(modal.getRoot().on(_modal_events.default.save,(e=>{e.preventDefault(),modal.getRoot().find("form").submit()})),modal.getRoot().on("submit","form",(e=>{e.preventDefault(),submitFormAjax(dynamicTable,modal)})),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy()})),modal.show(),modal))).then((modal=>Promise.all([modal,modal.getBodyPromise()]))).then((_ref=>{let[modal,body]=_ref;return body.get(0).querySelector(Selectors_cohortSelector)?modal.setSaveButtonText(Str.get_string("enroluserscohorts","enrol_manual")).then((()=>modal)):modal})).then((modal=>(pendingPromise.resolve(),modal))).catch(_notification.default.exception)},submitFormAjax=(dynamicTable,modal)=>{const form=modal.getRoot().find("form");form.get(0).querySelectorAll(Selectors_unwantedHiddenFields).forEach((hiddenField=>hiddenField.remove())),modal.hide(),modal.destroy(),_jquery.default.ajax("".concat(_config.default.wwwroot,"/enrol/manual/ajax.php?").concat(form.serialize()),{type:"GET",processData:!1,contentType:"application/json"}).then((response=>{if(response.error)throw new Error(response.error);return response.count})).then((count=>Promise.all([Str.get_string("totalenrolledusers","enrol",count),DynamicTable.refreshTableContent(dynamicTable)]))).then((_ref2=>{let[notificationBody]=_ref2;return notificationBody})).then((notificationBody=>Toast.add(notificationBody))).catch((error=>{_notification.default.addNotification({message:error.message,type:"error"})}))};_exports.init=_ref3=>{let{contextid:contextid}=_ref3;registerEventListeners(contextid),_prefetch.default.prefetchStrings("enrol_manual",["enrolusers","enroluserscohorts"]),_prefetch.default.prefetchString("enrol","totalenrolledusers")}})); /** * Controls the content area of the notification area on the * notification page. * * @module message_popup/notification_area_content_area * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("message_popup/notification_area_content_area",["jquery","core/templates","core/notification","core/custom_interaction_events","message_popup/notification_repository","message_popup/notification_area_events"],(function($,Templates,DebugNotification,CustomEvents,NotificationRepo,NotificationAreaEvents){var SELECTORS={CONTAINER:'[data-region="notification-area"]',CONTENT:'[data-region="content"]',HEADER:'[data-region="header"]',FOOTER:'[data-region="footer"]',TOGGLE_MODE:'[data-action="toggle-mode"]'},TEMPLATES_HEADER="message_popup/notification_area_content_area_header",TEMPLATES_CONTENT="message_popup/notification_area_content_area_content",TEMPLATES_FOOTER="message_popup/notification_area_content_area_footer",ContentArea=function(root,userId){this.root=$(root),this.container=this.root.closest(SELECTORS.CONTAINER),this.userId=userId,this.header=this.root.find(SELECTORS.HEADER),this.content=this.root.find(SELECTORS.CONTENT),this.footer=this.root.find(SELECTORS.FOOTER),this.registerEventListeners()};return ContentArea.prototype.getRoot=function(){return this.root},ContentArea.prototype.getContainer=function(){return this.container},ContentArea.prototype.getUserId=function(){return this.userId},ContentArea.prototype.getHeader=function(){return this.header},ContentArea.prototype.getContent=function(){return this.content},ContentArea.prototype.getFooter=function(){return this.footer},ContentArea.prototype.show=function(){this.getContainer().addClass("show-content-area")},ContentArea.prototype.hide=function(){this.getContainer().removeClass("show-content-area")},ContentArea.prototype.setHeaderHTML=function(html){this.getHeader().empty().html(html)},ContentArea.prototype.setContentHTML=function(html){this.getContent().empty().html(html)},ContentArea.prototype.setFooterHTML=function(html){this.getFooter().empty().html(html)},ContentArea.prototype.showNotification=function(notification){var headerPromise=Templates.render(TEMPLATES_HEADER,notification).done(function(html){this.setHeaderHTML(html)}.bind(this)),contentPromise=Templates.render(TEMPLATES_CONTENT,notification).done(function(html){this.setContentHTML(html)}.bind(this)),footerPromise=Templates.render(TEMPLATES_FOOTER,notification).done(function(html){this.setFooterHTML(html)}.bind(this));return $.when(headerPromise,contentPromise,footerPromise).done(function(){this.show(),this.getContainer().trigger(NotificationAreaEvents.notificationShown,[notification])}.bind(this))},ContentArea.prototype.registerEventListeners=function(){CustomEvents.define(this.getRoot(),[CustomEvents.events.activate]),this.getRoot().on(CustomEvents.events.activate,SELECTORS.VIEW_TOGGLE,function(){this.hide()}.bind(this)),this.getContainer().on(NotificationAreaEvents.showNotification,function(e,notification){this.showNotification(notification)}.bind(this))},ContentArea})); /** * Controls the notification area on the notification page. * * @module message_popup/notification_area_control_area * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("message_popup/notification_area_control_area",["jquery","core/templates","core/notification","core/custom_interaction_events","message_popup/notification_repository","message_popup/notification_area_events"],(function($,Templates,DebugNotification,CustomEvents,NotificationRepo,NotificationAreaEvents){var SELECTORS_CONTAINER='[data-region="notification-area"]',SELECTORS_CONTENT='[data-region="content"]',SELECTORS_NOTIFICATION='[data-region="notification-content-item-container"]',SELECTORS_CAN_RECEIVE_FOCUS='input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',TEMPLATES_NOTIFICATION="message_popup/notification_content_item",ControlArea=function(root,userId){this.root=$(root),this.container=this.root.closest(SELECTORS_CONTAINER),this.userId=userId,this.content=this.root.find(SELECTORS_CONTENT),this.offset=0,this.limit=20,this.initialLoad=!1,this.isLoading=!1,this.loadedAll=!1,this.notifications={},this.registerEventListeners()};return ControlArea.prototype.getRoot=function(){return this.root},ControlArea.prototype.getContainer=function(){return this.container},ControlArea.prototype.getUserId=function(){return this.userId},ControlArea.prototype.getContent=function(){return this.content},ControlArea.prototype.getOffset=function(){return this.offset},ControlArea.prototype.getLimit=function(){return this.limit},ControlArea.prototype.setOffset=function(value){this.offset=value},ControlArea.prototype.setLimit=function(value){this.limit=value},ControlArea.prototype.incrementOffset=function(){this.offset+=this.limit},ControlArea.prototype.startLoading=function(){this.isLoading=!0,this.getRoot().addClass("loading")},ControlArea.prototype.stopLoading=function(){this.isLoading=!1,this.getRoot().removeClass("loading")},ControlArea.prototype.hasDoneInitialLoad=function(){return this.initialLoad},ControlArea.prototype.hasLoadedAllContent=function(){return this.loadedAll},ControlArea.prototype.setLoadedAllContent=function(val){this.loadedAll=val},ControlArea.prototype.setCacheNotification=function(notification){this.notifications[notification.id]=notification},ControlArea.prototype.getCacheNotification=function(id){return this.notifications[id]},ControlArea.prototype.getNotificationElement=function(id){var element=this.getRoot().find(SELECTORS_NOTIFICATION+'[data-id="'+id+'"]');return 1==element.length?element:null},ControlArea.prototype.scrollNotificationIntoView=function(notificationElement){var position=notificationElement.position(),container=this.getRoot();if(position.top-container.scrollTop()>container.innerHeight()){var height=notificationElement.outerHeight();height*=4;var scrollTo=position.top-height;container.scrollTop(scrollTo)}},ControlArea.prototype.showNotification=function(notificationElement){if("object"!=typeof notificationElement&&(notificationElement=this.getNotificationElement(notificationElement)),notificationElement&¬ificationElement.length){this.getRoot().find(SELECTORS_NOTIFICATION).removeClass("selected"),notificationElement.addClass("selected").find(SELECTORS_CAN_RECEIVE_FOCUS).focus();var notificationId=notificationElement.attr("data-id"),notification=this.getCacheNotification(notificationId);this.scrollNotificationIntoView(notificationElement),this.getContainer().trigger(NotificationAreaEvents.showNotification,[$.extend({},notification)])}},ControlArea.prototype.markNotificationAsRead=function(notificationElement){return NotificationRepo.markAsRead(notificationElement.attr("data-id")).done((function(){notificationElement.removeClass("unread")}))},ControlArea.prototype.renderNotifications=function(notifications){var promises=[],container=this.getContent();return $.each(notifications,function(index,notification){var contextUrl=notification.contexturl;delete notification.contexturl;var promise=Templates.render(TEMPLATES_NOTIFICATION,notification).then(function(html,js){return notification.contexturl=contextUrl,this.setCacheNotification(notification),{html:html,js:js}}.bind(this));promises.push(promise)}.bind(this)),$.when.apply($,promises).then((function(){$.each(arguments,(function(index,argument){container.append(argument.html),Templates.runTemplateJS(argument.js)}))}))},ControlArea.prototype.loadMoreNotifications=function(){if(this.isLoading||this.hasLoadedAllContent())return $.Deferred().resolve();this.startLoading();var request={limit:this.getLimit(),offset:this.getOffset(),useridto:this.getUserId()};return this.initialLoad||(request.limit=this.getOffset()+this.getLimit(),request.offset=0),NotificationRepo.query(request).then(function(result){var notifications=result.notifications;return this.unreadCount=result.unreadcount,this.setLoadedAllContent(!notifications.length||notifications.length<this.getLimit()),this.initialLoad=!0,!!notifications.length&&(this.incrementOffset(),this.renderNotifications(notifications))}.bind(this)).always(function(){this.stopLoading()}.bind(this))},ControlArea.prototype.registerEventListeners=function(){CustomEvents.define(this.getRoot(),[CustomEvents.events.activate,CustomEvents.events.scrollBottom,CustomEvents.events.scrollLock,CustomEvents.events.up,CustomEvents.events.down]),this.getRoot().on(CustomEvents.events.scrollBottom,function(){this.loadMoreNotifications()}.bind(this)),this.getRoot().on(CustomEvents.events.activate,SELECTORS_NOTIFICATION,function(e){var notificationElement=$(e.target).closest(SELECTORS_NOTIFICATION);this.showNotification(notificationElement)}.bind(this)),this.getRoot().on(CustomEvents.events.up,SELECTORS_NOTIFICATION,function(e,data){var notificationElement=$(e.target).closest(SELECTORS_NOTIFICATION);this.showNotification(notificationElement.prev()),data.originalEvent.preventDefault()}.bind(this)),this.getRoot().on(CustomEvents.events.down,SELECTORS_NOTIFICATION,function(e,data){var notificationElement=$(e.target).closest(SELECTORS_NOTIFICATION);this.showNotification(notificationElement.next()),data.originalEvent.preventDefault()}.bind(this)),this.getContainer().on(NotificationAreaEvents.notificationShown,function(e,notification){if(!notification.read){var element=this.getNotificationElement(notification.id);element&&this.markNotificationAsRead(element);var cachedNotification=this.getCacheNotification(notification.id);cachedNotification&&(cachedNotification.read=!0)}}.bind(this))},ControlArea})); define("message_popup/notification_area_events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={showNotification:"notification-area-events:showNotification",notificationShown:"notification-area-events:notificationShown"},_exports.default})); /** * Controls the notification popover in the nav bar. * * See template: message_popup/notification_popover * * @module message_popup/notification_popover_controller * @class notification_popover_controller * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("message_popup/notification_popover_controller",["jquery","core/ajax","core/templates","core/str","core/url","core/notification","core/custom_interaction_events","core/popover_region_controller","message_popup/notification_repository","message_popup/notification_area_events"],(function($,Ajax,Templates,Str,URL,DebugNotification,CustomEvents,PopoverController,NotificationRepo,NotificationAreaEvents){var SELECTORS_MARK_ALL_READ_BUTTON='[data-action="mark-all-read"]',SELECTORS_ALL_NOTIFICATIONS_CONTAINER='[data-region="all-notifications"]',SELECTORS_NOTIFICATION='[data-region="notification-content-item-container"]',SELECTORS_UNREAD_NOTIFICATION='[data-region="notification-content-item-container"].unread',SELECTORS_NOTIFICATION_LINK='[data-action="content-item-link"]',SELECTORS_COUNT_CONTAINER='[data-region="count-container"]',NotificationPopoverController=function(element){PopoverController.call(this,element),this.markAllReadButton=this.root.find(SELECTORS_MARK_ALL_READ_BUTTON),this.unreadCount=0,this.lastQueried=0,this.userId=this.root.attr("data-userid"),this.container=this.root.find(SELECTORS_ALL_NOTIFICATIONS_CONTAINER),this.limit=20,this.offset=0,this.loadedAll=!1,this.initialLoad=!1,this.unreadCount=this.root.find(SELECTORS_COUNT_CONTAINER).html()};return(NotificationPopoverController.prototype=Object.create(PopoverController.prototype)).constructor=NotificationPopoverController,NotificationPopoverController.prototype.updateButtonAriaLabel=function(){this.isMenuOpen()?Str.get_string("hidenotificationwindow","message").done(function(string){this.menuToggle.attr("aria-label",string)}.bind(this)):this.unreadCount?Str.get_string("shownotificationwindowwithcount","message",this.unreadCount).done(function(string){this.menuToggle.attr("aria-label",string)}.bind(this)):Str.get_string("shownotificationwindownonew","message").done(function(string){this.menuToggle.attr("aria-label",string)}.bind(this))},NotificationPopoverController.prototype.getContent=function(){return this.container},NotificationPopoverController.prototype.getOffset=function(){return this.offset},NotificationPopoverController.prototype.incrementOffset=function(){this.offset+=this.limit},NotificationPopoverController.prototype.hasDoneInitialLoad=function(){return this.initialLoad},NotificationPopoverController.prototype.hasLoadedAllContent=function(){return this.loadedAll},NotificationPopoverController.prototype.setLoadedAllContent=function(val){this.loadedAll=val},NotificationPopoverController.prototype.renderUnreadCount=function(){var element=this.root.find(SELECTORS_COUNT_CONTAINER);this.unreadCount?(element.text(this.unreadCount),element.removeClass("hidden")):element.addClass("hidden")},NotificationPopoverController.prototype.hideUnreadCount=function(){this.root.find(SELECTORS_COUNT_CONTAINER).addClass("hidden")},NotificationPopoverController.prototype.getNotificationElement=function(id){var element=this.root.find(SELECTORS_NOTIFICATION+'[data-id="'+id+'"]');return 1==element.length?element:null},NotificationPopoverController.prototype.renderNotifications=function(notifications,container){var promises=[];return $.each(notifications,function(index,notification){var offset=this.getOffset()-this.limit;notification.viewmoreurl=URL.relativeUrl("/message/output/popup/notifications.php",{notificationid:notification.id,offset:offset});var notificationurlparams={notificationid:notification.id};notification.contexturl=URL.relativeUrl("message/output/popup/mark_notification_read.php",notificationurlparams);var promise=Templates.render("message_popup/notification_content_item",notification).then((function(html,js){return{html:html,js:js}}));promises.push(promise)}.bind(this)),$.when.apply($,promises).then((function(){$.each(arguments,(function(index,argument){container.append(argument.html),Templates.runTemplateJS(argument.js)}))}))},NotificationPopoverController.prototype.loadMoreNotifications=function(){if(this.isLoading||this.hasLoadedAllContent())return $.Deferred().resolve();this.startLoading();var request={limit:this.limit,offset:this.getOffset(),useridto:this.userId},container=this.getContent();return NotificationRepo.query(request).then(function(result){var notifications=result.notifications;return this.unreadCount=result.unreadcount,this.lastQueried=Math.floor((new Date).getTime()/1e3),this.setLoadedAllContent(!notifications.length||notifications.length<this.limit),this.initialLoad=!0,this.updateButtonAriaLabel(),!!notifications.length&&(this.incrementOffset(),this.renderNotifications(notifications,container))}.bind(this)).always(function(){this.stopLoading()}.bind(this))},NotificationPopoverController.prototype.markAllAsRead=function(){this.markAllReadButton.addClass("loading");var request={useridto:this.userId,timecreatedto:this.lastQueried};return NotificationRepo.markAllAsRead(request).then(function(){this.unreadCount=0,this.root.find(SELECTORS_UNREAD_NOTIFICATION).removeClass("unread")}.bind(this)).always(function(){this.markAllReadButton.removeClass("loading")}.bind(this))},NotificationPopoverController.prototype.registerEventListeners=function(){CustomEvents.define(this.root,[CustomEvents.events.activate]),this.root.on(CustomEvents.events.activate,SELECTORS_MARK_ALL_READ_BUTTON,function(e,data){this.markAllAsRead(),e.stopPropagation(),data.originalEvent.preventDefault()}.bind(this)),this.root.on(CustomEvents.events.activate,SELECTORS_NOTIFICATION_LINK,function(e){var element=$(e.target).closest(SELECTORS_NOTIFICATION);element.hasClass("unread")&&(this.unreadCount--,element.removeClass("unread")),e.stopPropagation()}.bind(this)),this.root.on(this.events().menuOpened,function(){this.hideUnreadCount(),this.updateButtonAriaLabel(),this.hasDoneInitialLoad()||this.loadMoreNotifications()}.bind(this)),this.root.on(this.events().menuClosed,function(){this.renderUnreadCount(),this.updateButtonAriaLabel()}.bind(this)),this.root.on(this.events().startLoading,function(){this.getContent().attr("aria-busy","true")}.bind(this)),this.root.on(this.events().stopLoading,function(){this.getContent().attr("aria-busy","false")}.bind(this)),this.getContentContainer().on(CustomEvents.events.scrollBottom,function(){this.isLoading||this.hasLoadedAllContent()||this.loadMoreNotifications()}.bind(this)),CustomEvents.define(this.getContentContainer(),[CustomEvents.events.scrollLock]),$(document).on(NotificationAreaEvents.notificationShown,function(e,notification){if(!notification.read){var element=this.getNotificationElement(notification.id);element&&element.removeClass("unread"),this.unreadCount--,this.renderUnreadCount()}}.bind(this))},NotificationPopoverController})); /** * Retrieves notifications from the server. * * @module message_popup/notification_repository * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("message_popup/notification_repository",["core/ajax","core/notification"],(function(Ajax,Notification){return{query:function(args){void 0===args.limit&&(args.limit=20),void 0===args.offset&&(args.offset=0);var request={methodname:"message_popup_get_popup_notifications",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},countUnread:function(args){var request={methodname:"message_popup_get_unread_popup_notification_count",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},markAllAsRead:function(args){var request={methodname:"core_message_mark_all_notifications_as_read",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},markAsRead:function(id,timeread){var args={notificationid:id};timeread&&(args.timeread=timeread);var request={methodname:"core_message_mark_notification_read",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise}}})); define("block_accessreview/module",["exports","core/ajax","core/templates","core/notification"],(function(_exports,_ajax,Templates,_notification){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,Templates=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Manager for the accessreview block. * * @module block_accessreview/module * @author Max Larkin <max@brickfieldlabs.ie> * @copyright 2020 Brickfield Education Labs <max@brickfieldlabs.ie> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(Templates);let toggleState=!0;const renderTemplate=(element,errorCount,checkCount,displayFormat,minViews,viewDelta)=>{const weight=parseInt((errorCount-minViews)/viewDelta*2),context={resultPassed:!errorCount,classList:"",passRate:{errorCount:errorCount,checkCount:checkCount,failureRate:Math.round(errorCount/checkCount*100)}};if(!element)return Promise.resolve();const elementClassList=["block_accessreview"];context.resultPassed?elementClassList.push("block_accessreview_success"):weight?elementClassList.push("block_accessreview_danger"):elementClassList.push("block_accessreview_warning");const showIcons="showicons"==displayFormat||"showboth"==displayFormat,showBackground="showbackground"==displayFormat||"showboth"==displayFormat;return showBackground&&!showIcons?(element.classList.add(...elementClassList,"alert"),Promise.resolve()):(showIcons&&!showBackground&&(context.classList=elementClassList.join(" ")),Templates.renderForPromise("block_accessreview/status",context).then((_ref=>{let{html:html,js:js}=_ref;Templates.appendNodeContents(element,html,js),showBackground&&element.classList.add(...elementClassList,"alert")})).catch())},showAccessMap=function(courseId,displayFormat){let updatePreference=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Promise.all(fetchReviewData(courseId,updatePreference)).then((_ref2=>{let[sectionData,moduleData]=_ref2;const{minViews:minViews,viewDelta:viewDelta}=getErrorTotals(sectionData,moduleData);return sectionData.forEach((section=>{const element=document.querySelector("#section-".concat(section.section," .summary"));element&&renderTemplate(element,section.numerrors,section.numchecks,displayFormat,minViews,viewDelta)})),moduleData.forEach((module=>{const element=document.getElementById("module-".concat(module.cmid));element&&renderTemplate(element,module.numerrors,module.numchecks,displayFormat,minViews,viewDelta)})),document.querySelector(".icon-accessmap").classList.remove("fa-eye-slash"),document.querySelector(".icon-accessmap").classList.add("fa-eye"),{sectionData:sectionData,moduleData:moduleData}})).catch(_notification.exception)},toggleAccessMap=(courseId,displayFormat)=>{toggleState=!toggleState,toggleState?showAccessMap(courseId,displayFormat,!0):function(){let updatePreference=arguments.length>0&&void 0!==arguments[0]&&arguments[0];document.querySelectorAll(".block_accessreview_view").forEach((node=>node.remove()));const classList=["block_accessreview","block_accessreview_success","block_accessreview_warning","block_accessreview_danger","block_accessreview_view","alert"];document.querySelectorAll(".block_accessreview").forEach((node=>node.classList.remove(...classList))),updatePreference&&setToggleStatePreference(!1),document.querySelector(".icon-accessmap").classList.remove("fa-eye"),document.querySelector(".icon-accessmap").classList.add("fa-eye-slash")}(!0)},getErrorTotals=(sectionData,moduleData)=>{const totals={totalErrors:0,totalUsers:0,minViews:0,maxViews:0,viewDelta:0};return[].concat(sectionData,moduleData).forEach((item=>{totals.totalErrors+=item.numerrors,item.numerrors<totals.minViews&&(totals.minViews=item.numerrors),item.numerrors>totals.maxViews&&(totals.maxViews=item.numerrors),totals.totalUsers+=item.numchecks})),totals.viewDelta=totals.maxViews-totals.minViews+1,totals},getTogglePreferenceParams=toggleState=>({methodname:"core_user_update_user_preferences",args:{preferences:[{type:"block_accessreviewtogglestate",value:toggleState}]}}),setToggleStatePreference=toggleState=>(0,_ajax.call)([getTogglePreferenceParams(toggleState)]),fetchReviewData=function(courseid){let updatePreference=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const calls=[{methodname:"block_accessreview_get_section_data",args:{courseid:courseid}},{methodname:"block_accessreview_get_module_data",args:{courseid:courseid}}];return updatePreference&&calls.push(getTogglePreferenceParams(!0)),(0,_ajax.call)(calls)};_exports.init=(toggled,displayFormat,courseId)=>{toggleState=1==toggled,toggleState&&showAccessMap(courseId,displayFormat),((courseId,displayFormat)=>{document.addEventListener("click",(e=>{e.target.closest("#toggle-accessmap")&&(e.preventDefault(),toggleAccessMap(courseId,displayFormat))}))})(courseId,displayFormat)}})); /** * Completion Progress overview page behaviour. * * @module block_completion_progress/overview * @copyright 2020 Jonathon Fowler <fowlerj@usq.edu.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_completion_progress/overview",["core_user/participants"],(function(Participants){return{init:function(options){var form=document.getElementById("participantsform"),action=document.getElementById("formactionid");function checkaction(){action.disabled=null===form.querySelector("input.usercheckbox:checked")}Participants.init(options),checkaction(),form.addEventListener("change",checkaction)}}})); /** * Completion Progress block progress bar behaviour. * * @module block_completion_progress/progressbar * @copyright 2020 Jonathon Fowler <fowlerj@usq.edu.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_completion_progress/progressbar",["jquery","core/pubsub","core/utils"],(function($,PubSub,Utils){function showInfo(event){var cell=$(this),container=cell.closest(".block_completion_progress .barContainer"),visibleinfo=container.siblings(".progressEventInfo:visible"),infotoshow=container.siblings("#"+cell.data("infoRef"));visibleinfo.is(infotoshow)||(visibleinfo.hide(),infotoshow.show()),event.preventDefault()}function showAllInfo(event){var initialinfo=$(this).closest(".progressEventInfo");initialinfo.siblings(".progressEventInfo").show(),initialinfo.hide(),event.preventDefault()}function viewActivity(){var cell=$(this),infolink=cell.closest(".block_completion_progress .barContainer").siblings("#"+cell.data("infoRef")).find("a.action_link");null!==infolink.prop("onclick")?infolink.click():document.location=infolink.prop("href")}function scrollContainer(event){var barrow=$(this).closest(".block_completion_progress .barContainer").find(".barRow"),amount=event.data*barrow.prop("scrollWidth")*.15;barrow.prop("scrollLeft",barrow.prop("scrollLeft")+amount),event.preventDefault()}function checkArrows(){var barrow=$(this),barcontainer=barrow.closest(".block_completion_progress .barContainer"),leftarrow=barcontainer.find(".left-arrow-svg"),rightarrow=barcontainer.find(".right-arrow-svg"),scrolled=barrow.prop("scrollLeft"),scrollWidth=barrow.prop("scrollWidth")-barrow.prop("offsetWidth"),threshold=Math.floor(.25*barrow.find(".progressBarCell:first-child").width());"rtl"===document.dir?((scrolled=-scrolled)>threshold?rightarrow.css("display","block"):rightarrow.css("display","none"),scrollWidth>threshold&&scrolled<scrollWidth-threshold?leftarrow.css("display","block"):leftarrow.css("display","none")):(scrolled>threshold?leftarrow.css("display","block"):leftarrow.css("display","none"),scrollWidth>threshold&&scrolled<scrollWidth-threshold?rightarrow.css("display","block"):rightarrow.css("display","none"))}function initialiseBar(instanceid){var barcontainers=$('.block_completion_progress .barContainer[data-instanceid="'+instanceid+'"]');barcontainers.on("touchstart mouseover",".progressBarCell",showInfo),barcontainers.on("click",".progressBarCell[data-haslink=true]",viewActivity),barcontainers.siblings(".progressEventInfo").find(".progressShowAllInfo").click(showAllInfo),function(barcontainers){var barrows=barcontainers.find(".barRow");function checkEachBar(){barrows.each(checkArrows)}barrows.scroll(checkArrows),$(window).resize(checkEachBar),PubSub.subscribe("nav-drawer-toggle-end",checkEachBar),$(document).on("theme_boost/drawers:shown theme_boost/drawers:hidden",Utils.debounce(checkEachBar,250)),$((function(){barcontainers.find(".nowicon").each((function(){var nowicon=$(this),barrow=nowicon.closest(".block_completion_progress .barRow");barrow.prop("scrollLeft",0),barrow.prop("scrollLeft",nowicon.offset().left-barrow.offset().left-barrow.width()/2)})),barrows.each(checkArrows)})),barcontainers.on("click",".left-arrow-svg",-1,scrollContainer),barcontainers.on("click",".right-arrow-svg",1,scrollContainer)}(barcontainers)}return{init:function(instanceids){for(var i=instanceids.length-1;i>=0;i--)initialiseBar(instanceids[i])}}})); define("block_massaction/massactionblock",["exports","./checkboxmanager","core/str","core/log","core/notification","core/pending","core_courseformat/courseeditor"],(function(_exports,checkboxmanager,Str,_log,_notification,_pending,_courseeditor){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Main module for the massaction block. * * @module block_massaction/massactionblock * @copyright 2022 ISB Bayern * @author Philipp Memmel * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.usedMoodleCssClasses=_exports.init=_exports.cssIds=_exports.constants=void 0,checkboxmanager=_interopRequireWildcard(checkboxmanager),Str=_interopRequireWildcard(Str),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);_exports.usedMoodleCssClasses={ACTIVITY_ITEM:".activity-item",SECTION_NAME:"sectionname",MODULE_ID_PREFIX:"module-"};const cssIds={SELECT_ALL_LINK:"block-massaction-control-selectall",DESELECT_ALL_LINK:"block-massaction-control-deselectall",HIDE_LINK:"block-massaction-action-hide",SHOW_LINK:"block-massaction-action-show",MAKE_AVAILABLE_LINK:"block-massaction-action-makeavailable",DUPLICATE_LINK:"block-massaction-action-duplicate",DELETE_LINK:"block-massaction-action-delete",SHOW_DESCRIPTION_LINK:"block-massaction-action-showdescription",HIDE_DESCRIPTION_LINK:"block-massaction-action-hidedescription",CONTENT_CHANGED_NOTIFICATION_LINK:"block-massaction-action-contentchangednotification",MOVELEFT_LINK:"block-massaction-action-moveleft",MOVERIGHT_LINK:"block-massaction-action-moveright",MOVETO_ICON_LINK:"block-massaction-action-moveto",DUPLICATETO_ICON_LINK:"block-massaction-action-duplicateto",DUPLICATE_TO_COURSE_ICON_LINK:"block-massaction-action-duplicatetocourse",SECTION_SELECT:"block-massaction-control-section-list-select",MOVETO_SELECT:"block-massaction-control-section-list-moveto",DUPLICATETO_SELECT:"block-massaction-control-section-list-duplicateto",BOX_ID_PREFIX:"block-massaction-module-selector-",CHECKBOX_CLASS:"block-massaction-checkbox",HIDDEN_FIELD_REQUEST_INFORMATION:"block-massaction-control-request",ACTION_FORM:"block-massaction-control-form"};_exports.cssIds=cssIds;const constants={SECTION_SELECT_DESCRIPTION_VALUE:"description",SECTION_NUMBER_ALL_PLACEHOLDER:"all",CHECKBOX_DESCRIPTION_SUFFIX:" Checkbox"};_exports.constants=constants;const actions_HIDE="hide",actions_SHOW="show",actions_MAKE_AVAILABLE="makeavailable",actions_DUPLICATE="duplicate",actions_DELETE="delete",actions_SHOW_DESCRIPTION="showdescription",actions_HIDE_DESCRIPTION="hidedescription",actions_MOVE_LEFT="moveleft",actions_MOVE_RIGHT="moveright",actions_CONTENT_CHANGED_NOTIFICATION="contentchangednotification",actions_MOVE_TO="moveto",actions_DUPLICATE_TO="duplicateto",actions_DUPLICATE_TO_COURSE="duplicatetocourse";_exports.init=async()=>{var _document$getElementB,_document$getElementB2,_document$getElementB3,_document$getElementB4,_document$getElementB5,_document$getElementB6,_document$getElementB7,_document$getElementB8,_document$getElementB9,_document$getElementB10,_document$getElementB11,_document$getElementB12,_document$getElementB13,_document$getElementB14,_document$getElementB15;const pendingPromise=new _pending.default("block_massaction/init");(0,_courseeditor.getCurrentCourseEditor)().stateManager.getInitialPromise().then((()=>checkboxmanager.initCheckboxManager())).catch((error=>_log.default.debug(error))),null===(_document$getElementB=document.getElementById(cssIds.SELECT_ALL_LINK))||void 0===_document$getElementB||_document$getElementB.addEventListener("click",(()=>checkboxmanager.setSectionSelection(!0,constants.SECTION_NUMBER_ALL_PLACEHOLDER)),!1),null===(_document$getElementB2=document.getElementById(cssIds.DESELECT_ALL_LINK))||void 0===_document$getElementB2||_document$getElementB2.addEventListener("click",(()=>checkboxmanager.setSectionSelection(!1,constants.SECTION_NUMBER_ALL_PLACEHOLDER)),!1),null===(_document$getElementB3=document.getElementById(cssIds.HIDE_LINK))||void 0===_document$getElementB3||_document$getElementB3.addEventListener("click",(()=>submitAction(actions_HIDE)),!1),null===(_document$getElementB4=document.getElementById(cssIds.SHOW_LINK))||void 0===_document$getElementB4||_document$getElementB4.addEventListener("click",(()=>submitAction(actions_SHOW)),!1),null===(_document$getElementB5=document.getElementById(cssIds.MAKE_AVAILABLE_LINK))||void 0===_document$getElementB5||_document$getElementB5.addEventListener("click",(()=>submitAction(actions_MAKE_AVAILABLE)),!1),null===(_document$getElementB6=document.getElementById(cssIds.DUPLICATE_LINK))||void 0===_document$getElementB6||_document$getElementB6.addEventListener("click",(()=>submitAction(actions_DUPLICATE)),!1),null===(_document$getElementB7=document.getElementById(cssIds.DELETE_LINK))||void 0===_document$getElementB7||_document$getElementB7.addEventListener("click",(()=>submitAction(actions_DELETE)),!1),null===(_document$getElementB8=document.getElementById(cssIds.SHOW_DESCRIPTION_LINK))||void 0===_document$getElementB8||_document$getElementB8.addEventListener("click",(()=>submitAction(actions_SHOW_DESCRIPTION)),!1),null===(_document$getElementB9=document.getElementById(cssIds.HIDE_DESCRIPTION_LINK))||void 0===_document$getElementB9||_document$getElementB9.addEventListener("click",(()=>submitAction(actions_HIDE_DESCRIPTION)),!1),null===(_document$getElementB10=document.getElementById(cssIds.CONTENT_CHANGED_NOTIFICATION_LINK))||void 0===_document$getElementB10||_document$getElementB10.addEventListener("click",(()=>submitAction(actions_CONTENT_CHANGED_NOTIFICATION)),!1),null===(_document$getElementB11=document.getElementById(cssIds.MOVELEFT_LINK))||void 0===_document$getElementB11||_document$getElementB11.addEventListener("click",(()=>submitAction(actions_MOVE_LEFT)),!1),null===(_document$getElementB12=document.getElementById(cssIds.MOVERIGHT_LINK))||void 0===_document$getElementB12||_document$getElementB12.addEventListener("click",(()=>submitAction(actions_MOVE_RIGHT)),!1),null===(_document$getElementB13=document.getElementById(cssIds.MOVETO_ICON_LINK))||void 0===_document$getElementB13||_document$getElementB13.addEventListener("click",(()=>submitAction(actions_MOVE_TO)),!1),null===(_document$getElementB14=document.getElementById(cssIds.DUPLICATETO_ICON_LINK))||void 0===_document$getElementB14||_document$getElementB14.addEventListener("click",(()=>submitAction(actions_DUPLICATE_TO)),!1),null===(_document$getElementB15=document.getElementById(cssIds.DUPLICATE_TO_COURSE_ICON_LINK))||void 0===_document$getElementB15||_document$getElementB15.addEventListener("click",(()=>submitAction(actions_DUPLICATE_TO_COURSE)),!1),pendingPromise.resolve()};const submitAction=action=>{const submitData={action:action,moduleIds:[]};if(submitData.moduleIds=checkboxmanager.getSelectedModIds(),0===submitData.moduleIds.length)return displayError(Str.get_string("noitemselected","block_massaction")),!1;switch(action){case actions_HIDE:case actions_SHOW:case actions_MAKE_AVAILABLE:case actions_DUPLICATE:case actions_DUPLICATE_TO_COURSE:case actions_CONTENT_CHANGED_NOTIFICATION:case actions_MOVE_LEFT:case actions_MOVE_RIGHT:case actions_DELETE:case actions_SHOW_DESCRIPTION:case actions_HIDE_DESCRIPTION:break;case actions_MOVE_TO:if(submitData.moveToTarget=document.getElementById(cssIds.MOVETO_SELECT).value,""===submitData.moveToTarget.trim())return displayError(Str.get_string("nomovingtargetselected","block_massaction")),!1;break;case actions_DUPLICATE_TO:if(submitData.duplicateToTarget=document.getElementById(cssIds.DUPLICATETO_SELECT).value,""===submitData.duplicateToTarget.trim())return displayError(Str.get_string("nomovingtargetselected","block_massaction")),!1;break;default:return displayError("Unknown action: "+action+". Coding error."),!1}return document.getElementById(cssIds.HIDDEN_FIELD_REQUEST_INFORMATION).value=JSON.stringify(submitData),document.getElementById(cssIds.ACTION_FORM).submit(),!0},displayError=errorText=>{Promise.resolve([Str.get_string("error","core"),errorText,Str.get_string("back","core")]).then((text=>_notification.default.alert(text[0],text[1],text[2]))).catch((error=>_log.default.debug(error)))}})); define("block_massaction/checkboxmanager",["exports","core/templates","core/notification","./massactionblock","core_courseformat/courseeditor","core_course/events"],(function(_exports,_templates,_notification,_massactionblock,_courseeditor,_events){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Checkbox manager amd module: Adds checkboxes to the activities for selecting and * generates a data structure of the activities and checkboxes. * * @module block_massaction/checkboxmanager * @copyright 2022 ISB Bayern * @author Philipp Memmel * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setSectionSelection=_exports.initCheckboxManager=_exports.getSelectedModIds=void 0,_templates=_interopRequireDefault(_templates),_events=_interopRequireDefault(_events);let localStateUpdating=!1,sectionsChanged=!1,sections=[],moduleNames=[];const sectionBoxes={};_exports.initCheckboxManager=()=>{const courseEditor=(0,_courseeditor.getCurrentCourseEditor)(),eventsToListen_SECTION_UPDATED="section:updated",eventsToListen_CHANGE_FINISHED="transaction:end";courseEditor.stateManager.target.addEventListener(_events.default.stateChanged,(event=>{event.detail.action===eventsToListen_SECTION_UPDATED&&(sectionsChanged=!0),event.detail.action===eventsToListen_CHANGE_FINISHED&&rebuildLocalState()})),sectionsChanged=!0,rebuildLocalState()};const rebuildLocalState=()=>{if(localStateUpdating)return;localStateUpdating=!0;const courseEditor=(0,_courseeditor.getCurrentCourseEditor)();sections=[];for(const prop of Object.getOwnPropertyNames(sectionBoxes))delete sectionBoxes[prop];sections=[...courseEditor.stateManager.state.section.values()].sort(((a,b)=>a.number>b.number?1:-1)),moduleNames=[...courseEditor.stateManager.state.cm.values()];const sectionsUnfiltered=sections;sections=filterVisibleSections(sections),updateSelectionAndMoveToDropdowns(sections,sectionsUnfiltered),addCheckboxes(),localStateUpdating=!1};_exports.getSelectedModIds=()=>{const moduleIds=[];for(let sectionNumber in sectionBoxes)for(let i=0;i<sectionBoxes[sectionNumber].length;i++){document.getElementById(sectionBoxes[sectionNumber][i].boxId).checked&&moduleIds.push(sectionBoxes[sectionNumber][i].moduleId)}return moduleIds};const setSectionSelection=(value,sectionNumber)=>{const boxIds=[];if(void 0===sectionNumber||sectionNumber!==_massactionblock.constants.SECTION_SELECT_DESCRIPTION_VALUE){if(void 0!==sectionNumber&§ionNumber===_massactionblock.constants.SECTION_NUMBER_ALL_PLACEHOLDER)for(const sectionId in sectionBoxes)for(let j=0;j<sectionBoxes[sectionId].length;j++)boxIds.push(sectionBoxes[sectionId][j].boxId);else sectionBoxes[sectionNumber].forEach((box=>boxIds.push(box.boxId)));for(let i=0;i<boxIds.length;i++)document.getElementById(boxIds[i]).checked=value;document.getElementById(_massactionblock.cssIds.SECTION_SELECT).value=_massactionblock.constants.SECTION_SELECT_DESCRIPTION_VALUE}};_exports.setSectionSelection=setSectionSelection;const addCheckboxes=()=>{sections.forEach((section=>{sectionBoxes[section.number]=[];const moduleIds=section.cmlist;if(moduleIds&&moduleIds.length>0&&""!==moduleIds[0]){moduleNames.filter((modinfo=>moduleIds.includes(modinfo.id.toString()))).forEach((modinfo=>{addCheckboxToModule(section.number,modinfo.id.toString(),modinfo.name)}))}}))},addCheckboxToModule=(sectionNumber,moduleId,moduleName)=>{const boxId=_massactionblock.cssIds.BOX_ID_PREFIX+moduleId;let additionalCssClass,moduleElement=document.getElementById(_massactionblock.usedMoodleCssClasses.MODULE_ID_PREFIX+moduleId).querySelector(_massactionblock.usedMoodleCssClasses.ACTIVITY_ITEM);if(moduleElement||(moduleElement=document.getElementById(_massactionblock.usedMoodleCssClasses.MODULE_ID_PREFIX+moduleId),additionalCssClass="block-massaction-checkbox-legacy"),null===document.getElementById(boxId)){const checkBoxElement=document.createElement("input");if(checkBoxElement.type="checkbox",checkBoxElement.className=_massactionblock.cssIds.CHECKBOX_CLASS,additionalCssClass&&checkBoxElement.classList.add(additionalCssClass),checkBoxElement.id=boxId,null!==moduleElement){const checkboxDescription=moduleName+_massactionblock.constants.CHECKBOX_DESCRIPTION_SUFFIX;checkBoxElement.ariaLabel=checkboxDescription,checkBoxElement.name=checkboxDescription,moduleElement.insertBefore(checkBoxElement,moduleElement.firstChild)}}sectionBoxes[sectionNumber].push({moduleId:moduleId,boxId:boxId})},filterVisibleSections=sections=>sections.filter((section=>0!==section.cmlist.length)).filter((section=>section.cmlist.every((moduleid=>null!==document.getElementById(_massactionblock.usedMoodleCssClasses.MODULE_ID_PREFIX+moduleid))))),updateSelectionAndMoveToDropdowns=(sections,sectionsUnfiltered)=>{sectionsChanged?(_templates.default.renderForPromise("block_massaction/section_select",{sections:sectionsUnfiltered}).then((_ref=>{let{html:html,js:js}=_ref;return _templates.default.replaceNode("#"+_massactionblock.cssIds.SECTION_SELECT,html,js),disableInvisibleAndEmptySections(sections),document.getElementById(_massactionblock.cssIds.SECTION_SELECT).addEventListener("change",(event=>setSectionSelection(!0,event.target.value)),!1),!0})).catch((ex=>(0,_notification.exception)(ex))),_templates.default.renderForPromise("block_massaction/moveto_select",{sections:sectionsUnfiltered}).then((_ref2=>{let{html:html,js:js}=_ref2;return _templates.default.replaceNode("#"+_massactionblock.cssIds.MOVETO_SELECT,html,js),!0})).catch((ex=>(0,_notification.exception)(ex))),_templates.default.renderForPromise("block_massaction/duplicateto_select",{sections:sectionsUnfiltered}).then((_ref3=>{let{html:html,js:js}=_ref3;return _templates.default.replaceNode("#"+_massactionblock.cssIds.DUPLICATETO_SELECT,html,js),!0})).catch((ex=>(0,_notification.exception)(ex)))):disableInvisibleAndEmptySections(sections),sectionsChanged=!1},disableInvisibleAndEmptySections=sections=>{Array.prototype.forEach.call(document.getElementById(_massactionblock.cssIds.SECTION_SELECT).options,(option=>{option.value===_massactionblock.constants.SECTION_SELECT_DESCRIPTION_VALUE||sections.some((section=>parseInt(option.value)===section.number))?option.disabled=!1:option.disabled=!0}))}})); define("block_myoverview/main",["exports","block_myoverview/view","block_myoverview/view_nav"],(function(_exports,View,ViewNav){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Javascript to initialise the myoverview block. * * @copyright 2018 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,View=_interopRequireWildcard(View),ViewNav=_interopRequireWildcard(ViewNav);_exports.init=root=>{ViewNav.init(root),View.init(root)}})); define("block_myoverview/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={courseView:{region:'[data-region="courses-view"]',regionContent:'[data-region="course-view-content"]'},FILTERS:'[data-region="filter"]',FILTER_OPTION:"[data-filter]",DISPLAY_OPTION:"[data-display-option]",ACTION_HIDE_COURSE:'[data-action="hide-course"]',ACTION_SHOW_COURSE:'[data-action="show-course"]',ACTION_ADD_FAVOURITE:'[data-action="add-favourite"]',ACTION_REMOVE_FAVOURITE:'[data-action="remove-favourite"]',FAVOURITE_ICON:'[data-region="favourite-icon"]',ICON_IS_FAVOURITE:'[data-region="is-favourite"]',ICON_NOT_FAVOURITE:'[data-region="not-favourite"]',region:{selectBlock:'[data-region="myoverview"]',clearIcon:'[data-action="clearsearch"]',searchInput:'[data-action="search"]'}},_exports.default})); define("block_myoverview/repository",["exports","core/ajax","core/notification"],(function(_exports,_ajax,Notification){var obj; /** * A javascript module to retrieve enrolled coruses from the server. * * @module block_myoverview/repository * @copyright 2018 Bas Brands <base@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateUserPreferences=_exports.setFavouriteCourses=_exports.getEnrolledCoursesByTimeline=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj},Notification=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Notification);_exports.getEnrolledCoursesByTimeline=args=>{const request={methodname:"core_course_get_enrolled_courses_by_timeline_classification",args:args};return _ajax.default.call([request])[0]};_exports.setFavouriteCourses=args=>{const request={methodname:"core_course_set_favourite_courses",args:args};return _ajax.default.call([request])[0]};_exports.updateUserPreferences=args=>{const request={methodname:"core_user_update_user_preferences",args:args};_ajax.default.call([request])[0].fail(Notification.exception)}})); define("block_myoverview/view",["exports","jquery","block_myoverview/repository","core/paged_content_factory","core/pubsub","core/custom_interaction_events","core/notification","core/templates","core_course/events","block_myoverview/selectors","core/paged_content_events","core/aria","core/utils"],(function(_exports,_jquery,Repository,PagedContentFactory,PubSub,CustomEvents,Notification,Templates,CourseEvents,_selectors,PagedContentEvents,Aria,_utils){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Manage the courses view for the overview block. * * @copyright 2018 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.reset=_exports.init=_exports.clearSearch=void 0,_jquery=_interopRequireDefault(_jquery),Repository=_interopRequireWildcard(Repository),PagedContentFactory=_interopRequireWildcard(PagedContentFactory),PubSub=_interopRequireWildcard(PubSub),CustomEvents=_interopRequireWildcard(CustomEvents),Notification=_interopRequireWildcard(Notification),Templates=_interopRequireWildcard(Templates),CourseEvents=_interopRequireWildcard(CourseEvents),_selectors=_interopRequireDefault(_selectors),PagedContentEvents=_interopRequireWildcard(PagedContentEvents),Aria=_interopRequireWildcard(Aria);const TEMPLATES_COURSES_CARDS="block_myoverview/view-cards",TEMPLATES_COURSES_LIST="block_myoverview/view-list",TEMPLATES_COURSES_SUMMARY="block_myoverview/view-summary",TEMPLATES_NOCOURSES="core_course/no-courses",GROUPINGS_GROUPING_ALLINCLUDINGHIDDEN="allincludinghidden",NUMCOURSES_PERPAGE=[12,24,48,96,0];let loadedPages=[],courseOffset=0,lastPage=0,lastLimit=0,namespace=null;const getFilterValues=root=>{const courseRegion=root.find(_selectors.default.courseView.region);return{display:courseRegion.attr("data-display"),grouping:courseRegion.attr("data-grouping"),sort:courseRegion.attr("data-sort"),displaycategories:courseRegion.attr("data-displaycategories"),customfieldname:courseRegion.attr("data-customfieldname"),customfieldvalue:courseRegion.attr("data-customfieldvalue")}},DEFAULT_PAGED_CONTENT_CONFIG={ignoreControlWhileLoading:!0,controlPlacementBottom:!0,persistentLimitKey:"block_myoverview_user_paging_preference"},getFavouriteIconContainer=(root,courseId)=>root.find(_selectors.default.FAVOURITE_ICON+'[data-course-id="'+courseId+'"]'),getPagedContentContainer=(root,index)=>root.find('[data-region="paged-content-page"][data-page="'+index+'"]'),getCourseId=root=>root.attr("data-course-id"),getAddFavouriteMenuItem=(root,courseId)=>root.find('[data-action="add-favourite"][data-course-id="'+courseId+'"]'),getRemoveFavouriteMenuItem=(root,courseId)=>root.find('[data-action="remove-favourite"][data-course-id="'+courseId+'"]'),addToFavourites=(root,courseId)=>{const removeAction=getRemoveFavouriteMenuItem(root,courseId),addAction=getAddFavouriteMenuItem(root,courseId);setCourseFavouriteState(courseId,!0).then((success=>{success?(PubSub.publish(CourseEvents.favourited,courseId),removeAction.removeClass("hidden"),addAction.addClass("hidden"),((root,courseId)=>{const iconContainer=getFavouriteIconContainer(root,courseId),isFavouriteIcon=iconContainer.find(_selectors.default.ICON_IS_FAVOURITE);isFavouriteIcon.removeClass("hidden"),Aria.unhide(isFavouriteIcon);const notFavourteIcon=iconContainer.find(_selectors.default.ICON_NOT_FAVOURITE);notFavourteIcon.addClass("hidden"),Aria.hide(notFavourteIcon)})(root,courseId)):Notification.alert("Starring course failed","Could not change favourite state")})).catch(Notification.exception)},removeFromFavourites=(root,courseId)=>{const removeAction=getRemoveFavouriteMenuItem(root,courseId),addAction=getAddFavouriteMenuItem(root,courseId);setCourseFavouriteState(courseId,!1).then((success=>{success?(PubSub.publish(CourseEvents.unfavorited,courseId),removeAction.addClass("hidden"),addAction.removeClass("hidden"),((root,courseId)=>{const iconContainer=getFavouriteIconContainer(root,courseId),isFavouriteIcon=iconContainer.find(_selectors.default.ICON_IS_FAVOURITE);isFavouriteIcon.addClass("hidden"),Aria.hide(isFavouriteIcon);const notFavourteIcon=iconContainer.find(_selectors.default.ICON_NOT_FAVOURITE);notFavourteIcon.removeClass("hidden"),Aria.unhide(notFavourteIcon)})(root,courseId)):Notification.alert("Starring course failed","Could not change favourite state")})).catch(Notification.exception)},getHideCourseMenuItem=(root,courseId)=>root.find('[data-action="hide-course"][data-course-id="'+courseId+'"]'),getShowCourseMenuItem=(root,courseId)=>root.find('[data-action="show-course"][data-course-id="'+courseId+'"]'),setCourseHiddenState=(courseId,status)=>(!1===status&&(status=null),Repository.updateUserPreferences({preferences:[{type:"block_myoverview_hidden_course_"+courseId,value:status}]})),hideElement=(root,id)=>{const pagingBar=root.find('[data-region="paging-bar"]'),jumpto=parseInt(pagingBar.attr("data-active-page-number"));let reducedCourse=loadedPages[jumpto].courses.reduce(((accumulator,current)=>(+id!=+current.id&&accumulator.push(current),accumulator)),[]);if(void 0!==loadedPages[jumpto+1]){const newElement=loadedPages[jumpto+1].courses.slice(0,1);loadedPages.forEach(((courseList,index)=>{if(index>jumpto){let popElement=[];void 0!==loadedPages[index+1]&&(popElement=loadedPages[index+1].courses.slice(0,1)),loadedPages[index].courses=[...loadedPages[index].courses.slice(1),...popElement]}})),reducedCourse=[...reducedCourse,...newElement]}if(lastPage===jumpto+1&&0===loadedPages[jumpto+1].courses.length){const pagedContentContainer=root.find('[data-region="paged-content-container"]');PagedContentFactory.resetLastPageNumber((0,_jquery.default)(pagedContentContainer).attr("id"),jumpto)}loadedPages[jumpto].courses=reducedCourse,courseOffset--;const pagedContentPage=getPagedContentContainer(root,jumpto);renderCourses(root,loadedPages[jumpto]).then(((html,js)=>Templates.replaceNodeContents(pagedContentPage,html,js))).catch(Notification.exception),loadedPages.forEach(((courseList,index)=>{if(index>jumpto){getPagedContentContainer(root,index).remove()}}))},setCourseFavouriteState=(courseId,status)=>Repository.setFavouriteCourses({courses:[{id:courseId,favourite:status}]}).then((result=>0===result.warnings.length&&(loadedPages.forEach((courseList=>{courseList.courses.forEach(((course,index)=>{course.id==courseId&&(courseList.courses[index].isfavourite=status)}))})),!0))).catch(Notification.exception),noCoursesRender=root=>{const nocoursesimg=root.find(_selectors.default.courseView.region).attr("data-nocoursesimg"),newcourseurl=root.find(_selectors.default.courseView.region).attr("data-newcourseurl");return Templates.render(TEMPLATES_NOCOURSES,{nocoursesimg:nocoursesimg,newcourseurl:newcourseurl})},renderCourses=(root,coursesData)=>{const filters=getFilterValues(root);let currentTemplate="";return currentTemplate="card"===filters.display?TEMPLATES_COURSES_CARDS:"list"===filters.display?TEMPLATES_COURSES_LIST:TEMPLATES_COURSES_SUMMARY,coursesData?(!1===Array.isArray(coursesData.courses)&&(coursesData.courses=Object.values(coursesData.courses)),coursesData.courses=coursesData.courses.map((course=>(course.showcoursecategory="on"===filters.displaycategories,course))),coursesData.courses.length?Templates.render(currentTemplate,{courses:coursesData.courses}):noCoursesRender(root)):noCoursesRender(root)},registerPagedEventHandlers=(root,namespace)=>{const event=namespace+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT;PubSub.subscribe(event,(root=>limit=>root.find(_selectors.default.courseView.region).attr("data-paging",limit))(root))},itemsPerPageFunc=(pagingLimit,root)=>{let itemsPerPage=NUMCOURSES_PERPAGE.map((value=>{let active=!1;return value===pagingLimit&&(active=!0),{value:value,active:active}}));const totalCourseCount=parseInt(root.find(_selectors.default.courseView.region).attr("data-totalcoursecount"),10);return itemsPerPage.filter((pagingOption=>pagingOption.value<totalCourseCount||0===pagingOption.value))},pageBuilder=function(coursesData,currentPage,pageData,actions){let activeSearch=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,courses=coursesData.courses?coursesData.courses:coursesData,nextPageStart=0,pageCourses=[];if(void 0!==loadedPages[currentPage]){pageCourses=loadedPages[currentPage].courses;const currentPageLength=pageCourses.length;currentPageLength<pageData.limit&&(nextPageStart=pageData.limit-currentPageLength,pageCourses={...loadedPages[currentPage].courses,...courses.slice(0,nextPageStart)})}else nextPageStart=pageData.limit||!1,pageCourses=pageData.limit>0?courses.slice(0,pageData.limit):courses;loadedPages[currentPage]={courses:pageCourses};const remainingCourses=!1!==nextPageStart?courses.slice(nextPageStart,courses.length):[];remainingCourses.length&&(loadedPages[currentPage+1]={courses:remainingCourses}),loadedPages[currentPage].courses.length<pageData.limit||!remainingCourses.length?(lastPage=currentPage,null===activeSearch&&actions.allItemsLoaded(currentPage)):void 0!==loadedPages[currentPage+1]&&loadedPages[currentPage+1].courses.length<pageData.limit&&(lastPage=currentPage+1),courseOffset=coursesData.nextoffset},resetGlobals=()=>{courseOffset=0,loadedPages=[],lastPage=0,lastLimit=0},standardFunctionalityCurry=()=>(resetGlobals(),(filters,currentPage,pageData,actions,root,promises,limit)=>{const pagePromise=((filters,limit)=>Repository.getEnrolledCoursesByTimeline({offset:courseOffset,limit:limit,classification:filters.grouping,sort:filters.sort,customfieldname:filters.customfieldname,customfieldvalue:filters.customfieldvalue}))(filters,limit).then((coursesData=>(pageBuilder(coursesData,currentPage,pageData,actions),renderCourses(root,loadedPages[currentPage])))).catch(Notification.exception);promises.push(pagePromise)}),searchFunctionalityCurry=()=>(resetGlobals(),(filters,currentPage,pageData,actions,root,promises,limit,inputValue)=>{const searchingPromise=((filters,limit,searchValue)=>Repository.getEnrolledCoursesByTimeline({offset:courseOffset,limit:limit,classification:"search",sort:filters.sort,customfieldname:filters.customfieldname,customfieldvalue:filters.customfieldvalue,searchvalue:searchValue}))(filters,limit,inputValue).then((coursesData=>(pageBuilder(coursesData,currentPage,pageData,actions),renderCourses(root,loadedPages[currentPage])))).catch(Notification.exception);promises.push(searchingPromise)}),initializePagedContent=function(root,promiseFunction){let inputValue=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const pagingLimit=parseInt(root.find(_selectors.default.courseView.region).attr("data-paging"),10);let itemsPerPage=itemsPerPageFunc(pagingLimit,root);const filters=getFilterValues(root),config={...DEFAULT_PAGED_CONTENT_CONFIG};config.eventNamespace=namespace;const pagedContentPromise=PagedContentFactory.createWithLimit(itemsPerPage,((pagesData,actions)=>{let promises=[];return pagesData.forEach((pageData=>{const currentPage=pageData.pageNumber;let limit=pageData.limit>0?pageData.limit:0;if(+lastLimit!=+limit&&(loadedPages=[],courseOffset=0,lastPage=0),lastPage===currentPage)return actions.allItemsLoaded(lastPage),void promises.push(renderCourses(root,loadedPages[currentPage]));lastLimit=limit,void 0===loadedPages[currentPage+1]&&void 0===loadedPages[currentPage]&&(limit*=2),promiseFunction(filters,currentPage,pageData,actions,root,promises,limit,inputValue)})),promises}),config);pagedContentPromise.then(((html,js)=>(registerPagedEventHandlers(root,namespace),Templates.replaceNodeContents(root.find(_selectors.default.courseView.region),html,js)))).catch(Notification.exception)},registerEventListeners=(root,page)=>{CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,_selectors.default.ACTION_ADD_FAVOURITE,((e,data)=>{const favourite=(0,_jquery.default)(e.target).closest(_selectors.default.ACTION_ADD_FAVOURITE),courseId=getCourseId(favourite);addToFavourites(root,courseId),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,_selectors.default.ACTION_REMOVE_FAVOURITE,((e,data)=>{const favourite=(0,_jquery.default)(e.target).closest(_selectors.default.ACTION_REMOVE_FAVOURITE),courseId=getCourseId(favourite);removeFromFavourites(root,courseId),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,_selectors.default.FAVOURITE_ICON,((e,data)=>{data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,_selectors.default.ACTION_HIDE_COURSE,((e,data)=>{const target=(0,_jquery.default)(e.target).closest(_selectors.default.ACTION_HIDE_COURSE),courseId=getCourseId(target);((root,courseId)=>{const hideAction=getHideCourseMenuItem(root,courseId),showAction=getShowCourseMenuItem(root,courseId),filters=getFilterValues(root);setCourseHiddenState(courseId,!0),filters.grouping!==GROUPINGS_GROUPING_ALLINCLUDINGHIDDEN&&hideElement(root,courseId),hideAction.addClass("hidden"),showAction.removeClass("hidden")})(root,courseId),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,_selectors.default.ACTION_SHOW_COURSE,((e,data)=>{const target=(0,_jquery.default)(e.target).closest(_selectors.default.ACTION_SHOW_COURSE),courseId=getCourseId(target);((root,courseId)=>{const hideAction=getHideCourseMenuItem(root,courseId),showAction=getShowCourseMenuItem(root,courseId),filters=getFilterValues(root);setCourseHiddenState(courseId,null),filters.grouping!==GROUPINGS_GROUPING_ALLINCLUDINGHIDDEN&&hideElement(root,courseId),hideAction.removeClass("hidden"),showAction.addClass("hidden")})(root,courseId),data.originalEvent.preventDefault()}));const input=page.querySelector(_selectors.default.region.searchInput),clearIcon=page.querySelector(_selectors.default.region.clearIcon);clearIcon.addEventListener("click",(()=>{input.value="",input.focus(),clearSearch(clearIcon,root)})),input.addEventListener("input",(0,_utils.debounce)((()=>{""===input.value?clearSearch(clearIcon,root):(activeSearch(clearIcon),initializePagedContent(root,searchFunctionalityCurry(),input.value.trim()))}),1e3))},clearSearch=(clearIcon,root)=>{clearIcon.classList.add("d-none"),init(root)};_exports.clearSearch=clearSearch;const activeSearch=clearIcon=>{clearIcon.classList.remove("d-none")},init=root=>{if(root=(0,_jquery.default)(root),loadedPages=[],lastPage=0,courseOffset=0,!root.attr("data-init")){const page=document.querySelector(_selectors.default.region.selectBlock);registerEventListeners(root,page),namespace="block_myoverview_"+root.attr("id")+"_"+Math.random(),root.attr("data-init",!0)}initializePagedContent(root,standardFunctionalityCurry())};_exports.init=init;_exports.reset=root=>{loadedPages.length>0?loadedPages.forEach(((courseList,index)=>{let pagedContentPage=getPagedContentContainer(root,index);renderCourses(root,courseList).then(((html,js)=>Templates.replaceNodeContents(pagedContentPage,html,js))).catch(Notification.exception)})):init(root)}})); define("block_myoverview/view_nav",["exports","jquery","core/custom_interaction_events","block_myoverview/repository","block_myoverview/view","block_myoverview/selectors"],(function(_exports,_jquery,CustomEvents,Repository,View,_selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Manage the timeline view navigation for the overview block. * * @copyright 2018 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),CustomEvents=_interopRequireWildcard(CustomEvents),Repository=_interopRequireWildcard(Repository),View=_interopRequireWildcard(View),_selectors=_interopRequireDefault(_selectors);const updatePreferences=(filter,value)=>{let type=null;type="display"===filter?"block_myoverview_user_view_preference":"sort"===filter?"block_myoverview_user_sort_preference":"customfieldvalue"===filter?"block_myoverview_user_grouping_customfieldvalue_preference":"block_myoverview_user_grouping_preference",Repository.updateUserPreferences({preferences:[{type:type,value:value}]})};_exports.init=root=>{(root=>{const Selector=root.find(_selectors.default.FILTERS);CustomEvents.define(Selector,[CustomEvents.events.activate]),Selector.on(CustomEvents.events.activate,_selectors.default.FILTER_OPTION,((e,data)=>{const option=(0,_jquery.default)(e.target);if(option.hasClass("active"))return;const filter=option.attr("data-filter"),pref=option.attr("data-pref"),customfieldvalue=option.attr("data-customfieldvalue");root.find(_selectors.default.courseView.region).attr("data-"+filter,option.attr("data-value")),updatePreferences(filter,pref),customfieldvalue&&(root.find(_selectors.default.courseView.region).attr("data-customfieldvalue",customfieldvalue),updatePreferences("customfieldvalue",customfieldvalue));const page=document.querySelector(_selectors.default.region.selectBlock),input=page.querySelector(_selectors.default.region.searchInput);if(""!==input.value){const clearIcon=page.querySelector(_selectors.default.region.clearIcon);input.value="",View.clearSearch(clearIcon,root)}else View.init(root);data.originalEvent.preventDefault()})),Selector.on(CustomEvents.events.activate,_selectors.default.DISPLAY_OPTION,((e,data)=>{const option=(0,_jquery.default)(e.target);if(option.hasClass("active"))return;const filter=option.attr("data-display-option"),pref=option.attr("data-pref");root.find(_selectors.default.courseView.region).attr("data-display",option.attr("data-value")),updatePreferences(filter,pref),View.reset(root),data.originalEvent.preventDefault()}))})(root=(0,_jquery.default)(root))}})); /** * Parse the response from the navblock ajax page and render the correct DOM * structure for the tree from it. * * @module block_navigation/ajax_response_renderer * @copyright 2015 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_navigation/ajax_response_renderer",["jquery","core/templates","core/notification","core/url","core/aria"],(function($,Templates,Notification,Url,Aria){var NODETYPE_ACTIVITY=40,NODETYPE_RESOURCE=50;function buildDOM(rootElement,nodes){var ul=$("<ul></ul>");ul.attr("role","group"),Aria.hide(ul),$.each(nodes,(function(index,node){if("object"==typeof node){var li=$("<li></li>"),p=$("<p></p>"),id=node.id||node.key+"_tree_item",icon=null,isBranch=!(!node.expandable&&!node.haschildren);li.attr("role","treeitem"),p.addClass("tree_item"),p.attr("id",id),p.attr("tabindex","-1"),node.requiresajaxloading&&(li.attr("data-requires-ajax",!0),li.attr("data-node-id",node.id),li.attr("data-node-key",node.key),li.attr("data-node-type",node.type)),isBranch&&(li.addClass("collapsed contains_branch"),li.attr("aria-expanded",!1),p.addClass("branch"));var eleToAddIcon=null;if(node.link){var link=$('<a title="'+node.title+'" href="'+node.link+'"></a>');eleToAddIcon=link,link.append('<span class="item-content-wrap">'+node.name+"</span>"),node.hidden&&link.addClass("dimmed"),p.append(link)}else{var span=$("<span></span>");eleToAddIcon=span,span.append('<span class="item-content-wrap">'+node.name+"</span>"),node.hidden&&span.addClass("dimmed"),p.append(span)}!node.icon||isBranch&&node.type!==NODETYPE_ACTIVITY&&node.type!==NODETYPE_RESOURCE||(li.addClass("item_with_icon"),p.addClass("hasicon"),node.type===NODETYPE_ACTIVITY||node.type===NODETYPE_RESOURCE?((icon=$("<img/>")).attr("alt",node.icon.alt),icon.attr("title",node.icon.title),icon.attr("src",Url.imageUrl(node.icon.pix,node.icon.component)),$.each(node.icon.classes,(function(index,className){icon.addClass(className)})),eleToAddIcon.prepend(icon)):("moodle"==node.icon.component&&(node.icon.component="core"),Templates.renderPix(node.icon.pix,node.icon.component,node.icon.title).then((function(html){eleToAddIcon.prepend(html)})).catch(Notification.exception))),li.append(p),ul.append(li),node.children&&node.children.length?buildDOM(li,node.children):isBranch&&!node.requiresajaxloading&&(li.removeClass("contains_branch"),p.addClass("emptybranch"))}})),rootElement.append(ul);var id=rootElement.attr("id")+"_group";ul.attr("id",id),rootElement.attr("aria-owns",id),rootElement.attr("role","treeitem")}return{render:function(element,nodes){if(nodes.children&&nodes.children.length){buildDOM(element,nodes.children);var item=element.children("[role='treeitem']").first(),group=element.find("#"+item.attr("aria-owns"));item.attr("aria-expanded",!0),Aria.unhide(group)}else element.hasClass("contains_branch")&&(element.removeClass("contains_branch"),element.addClass("emptybranch"))}}})); /** * Load the nav tree items via ajax and render the response. * * @module block_navigation/nav_loader * @copyright 2015 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_navigation/nav_loader",["jquery","core/ajax","core/config","block_navigation/ajax_response_renderer"],(function($,ajax,config,renderer){var URL=config.wwwroot+"/lib/ajax/getnavbranch.php";function getBlockInstanceId(element){return element.closest("[data-block]").attr("data-instanceid")}return{load:function(element){element=$(element);var promise=$.Deferred(),settings={type:"POST",dataType:"json",data:{elementid:element.attr("data-node-id"),id:element.attr("data-node-key"),type:element.attr("data-node-type"),sesskey:config.sesskey,instance:getBlockInstanceId(element)}};return $.ajax(URL,settings).done((function(nodes){renderer.render(element,nodes),promise.resolve()})),promise}}})); define("block_navigation/navblock",["exports","core_block/events","core/tree"],(function(_exports,_events,_tree){var obj; /** * Load the navigation tree javascript. * * @module block_navigation/navblock * @copyright 2015 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_tree=(obj=_tree)&&obj.__esModule?obj:{default:obj};_exports.init=instanceId=>{const navTree=new _tree.default(".block_navigation .block_tree"),blockNode=document.querySelector('[data-instance-id="'.concat(instanceId,'"]'));navTree.finishExpandingGroup=item=>{_tree.default.prototype.finishExpandingGroup.call(navTree,item),(0,_events.notifyBlockContentUpdated)(blockNode)},navTree.collapseGroup=item=>{_tree.default.prototype.collapseGroup.call(navTree,item),(0,_events.notifyBlockContentUpdated)(blockNode)}}})); /** * Load the site admin nav tree via ajax and render the response. * * @module block_navigation/site_admin_loader * @copyright 2015 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_navigation/site_admin_loader",["jquery","core/ajax","core/config","block_navigation/ajax_response_renderer"],(function($,ajax,config,renderer){var URL=config.wwwroot+"/lib/ajax/getsiteadminbranch.php";return{load:function(element){element=$(element);var promise=$.Deferred(),settings={type:"POST",dataType:"json",data:{type:71,sesskey:config.sesskey}};return $.ajax(URL,settings).done((function(nodes){renderer.render(element,nodes),promise.resolve()})),promise}}})); /** * A javascript module that handles the change of the user's visibility in the * online users block. * * @module block_online_users/change_user_visibility * @copyright 2018 Mihail Geshoski <mihail@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_online_users/change_user_visibility",["jquery","core/ajax","core/str","core/notification"],(function($,Ajax,Str,Notification){var SELECTORS_CHANGE_VISIBILITY_LINK="#change-user-visibility",SELECTORS_CHANGE_VISIBILITY_ICON="#change-user-visibility .icon",oppositeAction=function(action){return"show"==action?"hide":"show"},changeVisibilityLinkAttr=function(action){getTitle(action).then((function(title){$(SELECTORS_CHANGE_VISIBILITY_LINK).attr({"data-action":action,title:title})})).catch(Notification.exception)},changeVisibilityIconAttr=function(action){var icon=$(SELECTORS_CHANGE_VISIBILITY_ICON);getTitle(action).then((function(title){$(icon).attr({title:title,"aria-label":title}),icon.is("img")?$(icon).attr({src:M.util.image_url("t/"+action),alt:title}):($(icon).addClass(getIconClass(action)),$(icon).removeClass(getIconClass(oppositeAction(action))))})).catch(Notification.exception)},getIconClass=function(action){return"show"==action?"fa-eye-slash":"fa-eye"},getTitle=function(action){return Str.get_string("online_status:"+action,"block_online_users")};return{init:function(){$(SELECTORS_CHANGE_VISIBILITY_LINK).on("click",(function(e){e.preventDefault(),function(action,userid){var request={methodname:"core_user_set_user_preferences",args:{preferences:[{name:"block_online_users_uservisibility",value:"show"==action?1:0,userid:userid}]}};Ajax.call([request])[0].then((function(data){if(data.saved){var newAction=oppositeAction(action);changeVisibilityLinkAttr(newAction),changeVisibilityIconAttr(newAction)}})).catch(Notification.exception)}($(this).attr("data-action"),$(this).attr("data-userid"))}))}}})); define("block_private_files/files_tree",["exports","core/tree"],(function(_exports,_tree){var obj; /** * Changes the display of directories and files into a tree. * * @module block_private_files/files_tree * @copyright 2021 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_tree=(obj=_tree)&&obj.__esModule?obj:{default:obj};_exports.init=blockId=>{new _tree.default("#".concat(blockId,' [role="tree"]'))}})); /** * Javascript to initialise the Recently accessed courses block. * * @module block_recentlyaccessedcourses/main * @copyright 2018 Victor Deniz <victor@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_recentlyaccessedcourses/main",["jquery","core/custom_interaction_events","core/notification","core/pubsub","core/paged_content_paging_bar","core/templates","core_course/events","core_course/repository","core/aria"],(function($,CustomEvents,Notification,PubSub,PagedContentPagingBar,Templates,CourseEvents,CoursesRepository,Aria){var SELECTORS_BLOCK_CONTAINER='[data-region="recentlyaccessedcourses"]',SELECTORS_CARD_CONTAINER='[data-region="card-deck"]',SELECTORS_COURSE_IS_FAVOURITE='[data-region="is-favourite"]',SELECTORS_CONTENT='[data-region="view-content"]',SELECTORS_EMPTY_MESSAGE='[data-region="empty-message"]',SELECTORS_LOADING_PLACEHOLDER='[data-region="loading-placeholder"]',SELECTORS_PAGING_BAR='[data-region="paging-bar"]',SELECTORS_PAGING_BAR_NEXT='[data-control="next"]',SELECTORS_PAGING_BAR_PREVIOUS='[data-control="previous"]',contentLoaded=!1,allCourses=[],visibleCoursesId=null,cardWidth=null,viewIndex=0,availableVisibleCards=1,loadContent=function(userid){return CoursesRepository.getLastAccessedCourses(userid,10).then((function(courses){return function(courses){var showcoursecategory=$(SELECTORS_BLOCK_CONTAINER).data("displaycoursecategory"),promises=courses.map((function(course){return course.showcoursecategory=showcoursecategory,Templates.render("block_recentlyaccessedcourses/course-card",course)}));return $.when.apply(null,promises).then((function(){var renderedCourses=[];return promises.forEach((function(promise){promise.then((function(html){renderedCourses.push($(html))})).catch(Notification.exception)})),renderedCourses}))}(courses)}))},recalculateVisibleCourses=function(root){var container=root.find(SELECTORS_CONTENT).find(SELECTORS_CARD_CONTAINER),availableWidth=parseFloat(root.css("width")),numberOfCourses=allCourses.length,start=0;(cardWidth||(container.html(allCourses[0]),cardWidth=allCourses[0].outerWidth(!0)),availableVisibleCards=Math.floor(availableWidth/cardWidth),viewIndex+availableVisibleCards<numberOfCourses)?start=viewIndex:start=(start=viewIndex-(viewIndex+availableVisibleCards-numberOfCourses))>=0?start:0;0===availableVisibleCards&&(availableVisibleCards=1);var coursesToShow=allCourses.slice(start,start+availableVisibleCards),newVisibleCoursesId=coursesToShow.reduce((function(carry,course){return carry+course.attr("data-course-id")}),"");if(allCourses.length>coursesToShow.length?(container.addClass("justify-content-center"),container.removeClass("justify-content-start")):(container.removeClass("justify-content-center"),container.addClass("justify-content-start")),visibleCoursesId!=newVisibleCoursesId){var pagingBar=root.find(PagedContentPagingBar.rootSelector);container.html(coursesToShow),visibleCoursesId=newVisibleCoursesId,availableVisibleCards>=allCourses.length?function(root){var pagingBar=root.find(SELECTORS_PAGING_BAR);pagingBar.css("opacity",0),pagingBar.css("visibility","hidden"),Aria.hide(pagingBar)}(root):(!function(root){var pagingBar=root.find(SELECTORS_PAGING_BAR);pagingBar.css("opacity",1),pagingBar.css("visibility","visible"),Aria.unhide(pagingBar)}(root),0===viewIndex?PagedContentPagingBar.disablePreviousControlButtons(pagingBar):PagedContentPagingBar.enablePreviousControlButtons(pagingBar),viewIndex+availableVisibleCards>=allCourses.length?PagedContentPagingBar.disableNextControlButtons(pagingBar):PagedContentPagingBar.enableNextControlButtons(pagingBar))}},registerEventListeners=function(root){var resizeTimeout=null,drawerToggling=!1;PubSub.subscribe(CourseEvents.favourited,(function(courseId){!function(root,courseId){allCourses.forEach((function(course){course.attr("data-course-id")==courseId&&course.find(SELECTORS_COURSE_IS_FAVOURITE).removeClass("hidden")}))}(0,courseId)})),PubSub.subscribe(CourseEvents.unfavorited,(function(courseId){!function(root,courseId){allCourses.forEach((function(course){course.attr("data-course-id")==courseId&&course.find(SELECTORS_COURSE_IS_FAVOURITE).addClass("hidden")}))}(0,courseId)})),PubSub.subscribe("nav-drawer-toggle-start",(function(){if(contentLoaded&&allCourses.length&&!drawerToggling){drawerToggling=!0;var recalculationCount=0,doRecalculation=function(){setTimeout((function(){recalculateVisibleCourses(root),++recalculationCount<5&&drawerToggling&&doRecalculation()}),100)};doRecalculation(root)}})),PubSub.subscribe("nav-drawer-toggle-end",(function(){drawerToggling=!1})),$(window).on("resize",(function(){contentLoaded&&allCourses.length&&(resizeTimeout||(resizeTimeout=setTimeout((function(){resizeTimeout=null,recalculateVisibleCourses(root)}),66)))})),CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_PAGING_BAR_NEXT,(function(e,data){$(e.target).closest(SELECTORS_PAGING_BAR_NEXT).hasClass("disabled")||(viewIndex+=availableVisibleCards,recalculateVisibleCourses(root)),data.originalEvent.preventDefault()})),root.on(CustomEvents.events.activate,SELECTORS_PAGING_BAR_PREVIOUS,(function(e,data){$(e.target).closest(SELECTORS_PAGING_BAR_PREVIOUS).hasClass("disabled")||(viewIndex=(viewIndex-=availableVisibleCards)<0?0:viewIndex,recalculateVisibleCourses(root)),data.originalEvent.preventDefault()}))};return{init:function(userid,root){root=$(root),registerEventListeners(root),loadContent(userid).then((function(renderedCourses){contentLoaded=!0,(allCourses=renderedCourses).length?(!function(root){root.find(SELECTORS_CONTENT).removeClass("hidden"),root.find(SELECTORS_EMPTY_MESSAGE).addClass("hidden"),root.find(SELECTORS_LOADING_PLACEHOLDER).addClass("hidden")}(root),recalculateVisibleCourses(root)):function(root){root.find(SELECTORS_EMPTY_MESSAGE).removeClass("hidden"),root.find(SELECTORS_LOADING_PLACEHOLDER).addClass("hidden"),root.find(SELECTORS_CONTENT).addClass("hidden")}(root)})).catch(Notification.exception)}}})); /** * A javascript module to handle user ajax actions. * * @module block_recentlyaccesseditems/repository * @copyright 2018 Victor Deniz <victor@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_recentlyaccesseditems/repository",["core/ajax"],(function(Ajax){return{getRecentItems:function(limit){var args={};void 0!==limit&&(args.limit=limit);var request={methodname:"block_recentlyaccesseditems_get_recent_items",args:args};return Ajax.call([request])[0]}}})); /** * Javascript to initialise the Recently accessed items block. * * @module block_recentlyaccesseditems/main * @copyright 2018 Victor Deniz <victor@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_recentlyaccesseditems/main",["jquery","block_recentlyaccesseditems/repository","core/templates","core/notification"],(function($,Repository,Templates,Notification){var SELECTORS_CARDDECK_CONTAINER='[data-region="recentlyaccesseditems-view"]',SELECTORS_CARDDECK='[data-region="recentlyaccesseditems-view-content"]',SELECTORS_SHOWMORE_LINK='[data-region="recentlyaccesseditems-view"] [data-action="more-items"]';return{init:function(root){var limit,itemsContainer=(root=$(root)).find(SELECTORS_CARDDECK_CONTAINER),itemsContent=root.find(SELECTORS_CARDDECK);(limit=9,Repository.getRecentItems(limit)).then((function(items){var pageContentPromise=function(root,items){if(items.length>0){let hasmoreitems=!1;return items.length>3&&(hasmoreitems=!0),Templates.render("block_recentlyaccesseditems/view-cards",{items:items,hasmoreitems:hasmoreitems})}var noitemsimgurl=root.attr("data-noitemsimgurl");return Templates.render("block_recentlyaccesseditems/no-items",{noitemsimgurl:noitemsimgurl})}(itemsContainer,items);pageContentPromise.then((function(html,js){return Templates.replaceNodeContents(itemsContent,html,js),items.length>3&&(()=>{const showmoreLink=document.querySelector(SELECTORS_SHOWMORE_LINK);showmoreLink.addEventListener("click",(()=>{showmoreLink.classList.add("d-none"),document.querySelector('[data-region="items-list"]').children.forEach((function(hiddenItem){hiddenItem.style="display: block"}))}))})(),null})).catch(Notification.exception)})).catch(Notification.exception)}}})); define("block_settings/settingsblock",["exports","core_block/events","core/tree"],(function(_exports,_events,_tree){var obj; /** * Load the settings block tree javscript * * @module block_settings/settingsblock * @copyright 2015 John Okely <john@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_tree=(obj=_tree)&&obj.__esModule?obj:{default:obj};_exports.init=(instanceId,siteAdminNodeId)=>{const adminTree=new _tree.default(".block_settings .block_tree"),blockNode=document.querySelector('[data-instance-id="'.concat(instanceId,'"]'));if(siteAdminNodeId){const siteAdminLink=adminTree.treeRoot.get(0).querySelector("#".concat(siteAdminNodeId," a")),newContainer=document.createElement("span");newContainer.setAttribute("tabindex","0"),siteAdminLink.childNodes.forEach((node=>newContainer.appendChild(node))),siteAdminLink.replaceWith(newContainer)}adminTree.finishExpandingGroup=function(item){_tree.default.prototype.finishExpandingGroup.call(adminTree,item),(0,_events.notifyBlockContentUpdated)(blockNode)},adminTree.collapseGroup=function(item){_tree.default.prototype.collapseGroup.call(adminTree,item),(0,_events.notifyBlockContentUpdated)(blockNode)}}})); /** * Javascript to initialise the starred courses block. * * @module block_starredcourses/main * @copyright 2018 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_starredcourses/main",["jquery","core/notification","block_starredcourses/repository","core/pubsub","core/templates","core_course/events"],(function($,Notification,Repository,PubSub,Templates,CourseEvents){var SELECTORS_BLOCK_CONTAINER='[data-region="starred-courses"]',SELECTORS_STARRED_COURSES_REGION_VIEW='[data-region="starred-courses-view"]',SELECTORS_STARRED_COURSES_REGION='[data-region="starred-courses-view-content"]',reloadContent=function(root){var content=root.find(SELECTORS_STARRED_COURSES_REGION);return Repository.getStarredCourses({limit:0,offset:0}).then((function(courses){var showcoursecategory=$(SELECTORS_BLOCK_CONTAINER).data("displaycoursecategory");return courses=courses.map((function(course){return course.showcoursecategory=showcoursecategory,course})),function(root,courses){if(courses.length>0)return Templates.render("core_course/view-cards",{courses:courses});var nocoursesimg=root.find(SELECTORS_STARRED_COURSES_REGION_VIEW).attr("data-nocoursesimg");return Templates.render("block_starredcourses/no-courses",{nocoursesimg:nocoursesimg})}(root,courses)})).then((function(html,js){return Templates.replaceNodeContents(content,html,js)})).catch(Notification.exception)};return{init:function(root){(function(root){PubSub.subscribe(CourseEvents.favourited,(function(){reloadContent(root)})),PubSub.subscribe(CourseEvents.unfavorited,(function(){reloadContent(root)}))})(root=$(root)),reloadContent(root)}}})); /** * A javascript module to retrieve user's starred courses. * * @module block_starredcourses/repository * @copyright 2018 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_starredcourses/repository",["jquery","core/ajax","core/notification"],(function($,Ajax,Notification){return{getStarredCourses:function(args){var request={methodname:"block_starredcourses_get_starred_courses",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise}}})); /** * A javascript module to retrieve calendar events from the server. * * @module block_timeline/calendar_events_repository * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/calendar_events_repository",["jquery","core/ajax","core/notification"],(function($,Ajax,Notification){return{queryByTime:function(args){args.hasOwnProperty("limit")||(args.limit=20),args.limitnum=args.limit,delete args.limit,args.hasOwnProperty("starttime")&&(args.timesortfrom=args.starttime,delete args.starttime),args.hasOwnProperty("endtime")&&(args.timesortto=args.endtime,delete args.endtime),args.limittononsuspendedevents=!0;var request={methodname:"core_calendar_get_action_events_by_timesort",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},queryByCourse:function(args){args.hasOwnProperty("limit")||(args.limit=20),args.limitnum=args.limit,delete args.limit,args.hasOwnProperty("starttime")&&(args.timesortfrom=args.starttime,delete args.starttime),args.hasOwnProperty("endtime")&&(args.timesortto=args.endtime,delete args.endtime);var request={methodname:"core_calendar_get_action_events_by_course",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise},queryByCourses:function(args){args.hasOwnProperty("limit")||(args.limit=10),args.limitnum=args.limit,delete args.limit,args.hasOwnProperty("starttime")&&(args.timesortfrom=args.starttime,delete args.starttime),args.hasOwnProperty("endtime")&&(args.timesortto=args.endtime,delete args.endtime);var request={methodname:"core_calendar_get_action_events_by_courses",args:args},promise=Ajax.call([request])[0];return promise.fail(Notification.exception),promise}}})); /** * Javascript to load and render the list of calendar events for a * given day range. * * @module block_timeline/event_list * @copyright 2016 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/event_list",["jquery","core/notification","core/templates","core/str","core/user_date","block_timeline/calendar_events_repository","core/pending"],(function($,Notification,Templates,Str,UserDate,CalendarEventsRepository,Pending){var courseview=!1,SELECTORS_EMPTY_MESSAGE='[data-region="no-events-empty-message"]',SELECTORS_EVENT_LIST_CONTENT='[data-region="event-list-content"]',SELECTORS_EVENT_LIST_WRAPPER='[data-region="event-list-wrapper"]',SELECTORS_EVENT_LIST_LOADING_PLACEHOLDER='[data-region="event-list-loading-placeholder"]',SELECTORS_TIMELINE_BLOCK='[data-region="timeline"]',SELECTORS_TIMELINE_SEARCH='[data-action="search"]',SELECTORS_MORE_ACTIVITIES_BUTTON='[data-action="more-events"]',SELECTORS_MORE_ACTIVITIES_BUTTON_CONTAINER='[data-region="more-events-button-container"]',TEMPLATES_EVENT_LIST_CONTENT="block_timeline/event-list-content",TEMPLATES_MORE_ACTIVITIES_BUTTON="block_timeline/event-list-loadmore",TEMPLATES_LOADING_ICON="core/loading";var hideContent=function(root){root.find(SELECTORS_EVENT_LIST_CONTENT).addClass("hidden"),root.find(SELECTORS_EMPTY_MESSAGE).removeClass("hidden")},showContent=function(root){root.find(SELECTORS_EVENT_LIST_CONTENT).removeClass("hidden"),root.find(SELECTORS_EMPTY_MESSAGE).addClass("hidden")},emptyContent=function(root){root.find(SELECTORS_EVENT_LIST_CONTENT).empty()},render=function(calendarEvents){var templateContext=function(calendarEvents){var eventsByDay={},templateContext={courseview:courseview,eventsbyday:[]};return calendarEvents.forEach((function(calendarEvent){var dayTimestamp=calendarEvent.timeusermidnight;eventsByDay[dayTimestamp]?eventsByDay[dayTimestamp].push(calendarEvent):eventsByDay[dayTimestamp]=[calendarEvent]})),Object.keys(eventsByDay).forEach((function(dayTimestamp){var events=eventsByDay[dayTimestamp];templateContext.eventsbyday.push({dayTimestamp:dayTimestamp,events:events})})),templateContext}(calendarEvents),templateName=TEMPLATES_EVENT_LIST_CONTENT;return Templates.render(templateName,templateContext)};const createLazyLoadingContent=(root,firstLoad,itemLimit,midnight,lastId,courseId,daysOffset,daysLimit,searchValue)=>loadEventsForLazyLoading(root,itemLimit,midnight,lastId,courseId,daysOffset,daysLimit,searchValue).then((data=>{if(data.calendarEvents.length){const lastEventId=data.calendarEvents.at(-1).id,lastTimeStamp=data.calendarEvents.at(-1).timeusermidnight;return firstLoad.resolve({hasContent:!0,lastId:lastEventId,lastTimeStamp:lastTimeStamp,loadedAll:data.loadedAll}),render(data.calendarEvents)}return firstLoad.resolve({hasContent:!1,lastId:0,lastTimeStamp:0,loadedAll:!0}),data.calendarEvents})).catch(Notification.exception),loadEventsForLazyLoading=(root,itemLimit,midnight,lastId,courseId,daysOffset,daysLimit,searchValue)=>{const eventsPromise=function(midnight,limit,daysOffset,daysLimit,lastId,courseId,searchValue){var endTime=null!=daysLimit&&midnight+86400*daysLimit,args={starttime:midnight+86400*daysOffset,limit:limit};return lastId&&(args.aftereventid=lastId),endTime&&(args.endtime=endTime),searchValue&&(args.searchvalue=searchValue),courseId?(args.courseid=courseId,CalendarEventsRepository.queryByCourse(args)):CalendarEventsRepository.queryByTime(args)}(midnight,itemLimit+1,daysOffset,daysLimit,lastId,courseId,searchValue);let calendarEvents=[],loadedAll=!0;return eventsPromise.then((result=>{if(!result.events.length)return{calendarEvents:calendarEvents,loadedAll:loadedAll};const overdueFilter=document.querySelector("[data-filtername='overdue']"),filterByOverdue=overdueFilter&&overdueFilter.getAttribute("aria-current");if(calendarEvents=result.events.filter((event=>{if("open"==event.eventtype||"opensubmission"==event.eventtype){return UserDate.getUserMidnightForTimestamp(event.timesort,midnight)>midnight}return!filterByOverdue||event.overdue})),loadedAll=calendarEvents.length<=itemLimit,loadedAll||calendarEvents.pop(),calendarEvents.length){const lastEventId=calendarEvents.at(-1).id;setOffset(root,lastEventId)}return{calendarEvents:calendarEvents,loadedAll:loadedAll}}))},getOffset=element=>parseInt(element.attr("data-lazyload-offset"),10),setOffset=(element,offset)=>{element.attr("data-lazyload-offset",offset)},getLastTimestamp=element=>parseInt(element.attr("data-timestamp"),10),setLastTimestamp=(element,timestamp)=>{element.attr("data-timestamp",timestamp)},disableMoreActivitiesButtonLoading=root=>{root.find(SELECTORS_MORE_ACTIVITIES_BUTTON_CONTAINER).remove()},initEventListener=root=>{root.find(SELECTORS_MORE_ACTIVITIES_BUTTON).on("click",(()=>{(root=>{const loadMoreButton=root.find(SELECTORS_MORE_ACTIVITIES_BUTTON);loadMoreButton.prop("disabled",!0),Templates.render(TEMPLATES_LOADING_ICON,{}).then((html=>(loadMoreButton.append(html),html))).catch((()=>!1))})(root),(root=>{const midnight=parseInt(root.attr("data-midnight"),10),courseId=root.attr("data-course-id"),daysOffset=parseInt(root.attr("data-days-offset"),10),daysLimit=root.attr("data-days-limit"),lastId=getOffset(root),eventListWrapper=root.find(SELECTORS_EVENT_LIST_WRAPPER),searchValue=root.closest(SELECTORS_TIMELINE_BLOCK).find(SELECTORS_TIMELINE_SEARCH).val();loadEventsForLazyLoading(root,10,midnight,lastId,courseId,daysOffset,daysLimit,searchValue).then((data=>{if(data.calendarEvents.length){const renderPromise=render(data.calendarEvents),lastTimestamp=getLastTimestamp(root);renderPromise.then(((html,js)=>((html=$(html)).find('[data-timestamp="'.concat(lastTimestamp,'"]')).remove(),Templates.appendNodeContents(eventListWrapper,html.html(),js),data.loadedAll||Templates.render(TEMPLATES_MORE_ACTIVITIES_BUTTON,{}).then((html=>(eventListWrapper.append(html),setLastTimestamp(root,data.calendarEvents.at(-1).timeusermidnight),initEventListener(root),html))).catch((()=>!1)),html))).catch(Notification.exception)}return data})).then((()=>disableMoreActivitiesButtonLoading(root))).catch(Notification.exception)})(root)}))};return{init:function(root){let additionalConfig=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const pendingPromise=new Pending("block/timeline:event-init");root=$(root),courseview=!!additionalConfig.courseview;var firstLoad=$.Deferred(),eventListContent=root.find(SELECTORS_EVENT_LIST_CONTENT),loadingPlaceholder=root.find(SELECTORS_EVENT_LIST_LOADING_PLACEHOLDER),courseId=root.attr("data-course-id"),daysOffset=parseInt(root.attr("data-days-offset"),10),daysLimit=root.attr("data-days-limit"),midnight=parseInt(root.attr("data-midnight"),10);const searchValue=root.closest(SELECTORS_TIMELINE_BLOCK).find(SELECTORS_TIMELINE_SEARCH).val();return emptyContent(root),showContent(root),loadingPlaceholder.removeClass("hidden"),null!=daysLimit&&(daysLimit=parseInt(daysLimit,10)),createLazyLoadingContent(root,firstLoad,5,midnight,0,courseId,daysOffset,daysLimit,searchValue).then((function(html,js){return firstLoad.then((function(data){return data.hasContent?((html=$(html)).addClass("hidden"),Templates.replaceNodeContents(eventListContent,html,js),html.removeClass("hidden"),loadingPlaceholder.addClass("hidden"),data.loadedAll||Templates.render(TEMPLATES_MORE_ACTIVITIES_BUTTON,{courseview:courseview}).then((function(html){return eventListContent.append(html),setLastTimestamp(root,data.lastTimeStamp),initEventListener(root),html})).catch((function(){return!1})),data):(loadingPlaceholder.addClass("hidden"),hideContent(root))})).catch((function(){return!1})),html})).then((()=>pendingPromise.resolve())).catch(Notification.exception)},rootSelector:'[data-region="event-list-container"]'}})); /** * Javascript to initialise the timeline block. * * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/main",["jquery","block_timeline/view_nav","block_timeline/view"],(function($,ViewNav,View){var SELECTORS_TIMELINE_VIEW='[data-region="timeline-view"]';return{init:function(root){var viewRoot=(root=$(root)).find(SELECTORS_TIMELINE_VIEW);ViewNav.init(root,viewRoot),View.init(viewRoot)}}})); /** * Manage the timeline view for the timeline block. * * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/view",["jquery","block_timeline/view_dates","block_timeline/view_courses"],(function($,ViewDates,ViewCourses){var SELECTORS_TIMELINE_DATES_VIEW='[data-region="view-dates"]',SELECTORS_TIMELINE_COURSES_VIEW='[data-region="view-courses"]';return{init:function(root){var datesViewRoot=(root=$(root)).find(SELECTORS_TIMELINE_DATES_VIEW),coursesViewRoot=root.find(SELECTORS_TIMELINE_COURSES_VIEW);ViewDates.init(datesViewRoot),ViewCourses.init(coursesViewRoot)},reset:function(root){var datesViewRoot=root.find(SELECTORS_TIMELINE_DATES_VIEW),coursesViewRoot=root.find(SELECTORS_TIMELINE_COURSES_VIEW);ViewDates.reset(datesViewRoot),ViewCourses.reset(coursesViewRoot)},shown:function(root){var datesViewRoot=root.find(SELECTORS_TIMELINE_DATES_VIEW),coursesViewRoot=root.find(SELECTORS_TIMELINE_COURSES_VIEW);datesViewRoot.hasClass("active")?ViewDates.shown(datesViewRoot):ViewCourses.shown(coursesViewRoot)}}})); /** * Manage the timeline courses view for the timeline block. * * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/view_courses",["jquery","core/notification","core/custom_interaction_events","core/templates","block_timeline/event_list","core_course/repository","block_timeline/calendar_events_repository","core/pending"],(function($,Notification,CustomEvents,Templates,EventList,CourseRepository,EventsRepository,Pending){var SELECTORS_MORE_COURSES_BUTTON='[data-action="more-courses"]',SELECTORS_MORE_COURSES_BUTTON_CONTAINER='[data-region="more-courses-button-container"]',SELECTORS_NO_COURSES_EMPTY_MESSAGE='[data-region="no-courses-empty-message"]',SELECTORS_NO_COURSES_WITH_EVENTS_MESSAGE='[data-region="no-events-empty-message"]',SELECTORS_COURSES_LIST='[data-region="courses-list"]',SELECTORS_COURSE_ITEMS_LOADING_PLACEHOLDER='[data-region="course-items-loading-placeholder"]',SELECTORS_LOADING_ICON=".loading-icon",SELECTORS_TIMELINE_BLOCK='[data-region="timeline"]',SELECTORS_TIMELINE_SEARCH='[data-action="search"]',TEMPLATES_COURSE_ITEMS="block_timeline/course-items",TEMPLATES_LOADING_ICON="core/loading";const additionalConfig={courseview:!0};var hideLoadingPlaceholder=function(root){root.find(SELECTORS_COURSE_ITEMS_LOADING_PLACEHOLDER).addClass("hidden")};var hideMoreCoursesButton=function(root){root.find(SELECTORS_MORE_COURSES_BUTTON_CONTAINER).addClass("hidden")},showMoreCoursesButton=function(root){root.find(SELECTORS_MORE_COURSES_BUTTON_CONTAINER).removeClass("hidden")},disableMoreCoursesButtonLoading=function(root){var button=root.find(SELECTORS_MORE_COURSES_BUTTON);button.prop("disabled",!1),button.find(SELECTORS_LOADING_ICON).remove()};const showNoCoursesWithEventsMessage=function(root){const container=root.find(SELECTORS_COURSES_LIST);Templates.replaceNodeContents(container,"",""),root.find(SELECTORS_NO_COURSES_WITH_EVENTS_MESSAGE).removeClass("hidden")};var getOffset=function(root){return parseInt(root.attr("data-offset"),10)},setOffset=function(root,offset){root.attr("data-offset",offset)},getLimit=function(root){return parseInt(root.attr("data-limit"),10)},getDaysOffset=function(root){return parseInt(root.attr("data-days-offset"),10)},getDaysLimit=function(root){var daysLimit=root.attr("data-days-limit");return null!=daysLimit?parseInt(daysLimit,10):void 0},getMidnight=function(root){return parseInt(root.attr("data-midnight"),10)},getStartTime=function(root){return getMidnight(root)+86400*getDaysOffset(root)},getEndTime=function(root){let endTime=null;if(root.attr("data-filter-overdue"))endTime=Math.floor(Date.now()/1e3);else{const midnight=getMidnight(root),daysLimit=getDaysLimit(root);null!=daysLimit&&(endTime=midnight+86400*daysLimit)}return endTime},hasReloadedEventsSince=function(root,time){return function(root){return root.data("last-event-load-time")}(root)>time},loadEventsForCourses=function(courses,startTime,endTime,searchValue){return function(courseIds,startTime,limit,endTime,searchValue){var args={courseids:courseIds,starttime:startTime,limit:limit};return endTime&&(args.endtime=endTime),searchValue&&(args.searchvalue=searchValue),EventsRepository.queryByCourses(args)}(courses.map((function(course){return course.id})),startTime,6,endTime,searchValue)},updateDisplayFromCourses=function(courses,root,midnight,daysOffset,daysLimit,append){return Templates.render(TEMPLATES_COURSE_ITEMS,{courses:courses,midnight:midnight,hasdaysoffset:!0,hasdayslimit:null!=daysLimit,daysoffset:daysOffset,dayslimit:daysLimit,nodayslimit:null==daysLimit,courseview:!0,hascourses:!0}).then((function(html){return hideLoadingPlaceholder(root),html&&function(root,html){let append=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var container=root.find(SELECTORS_COURSES_LIST);append?Templates.appendNodeContents(container,html,""):Templates.replaceNodeContents(container,html,"")}(root,html,append),html})).then((function(html){return courses.length<2?hideMoreCoursesButton(root):showMoreCoursesButton(root),html})).catch((function(){hideLoadingPlaceholder(root)}))},loadMoreCourses=function(root){let append=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const pendingPromise=new Pending("block/timeline:load-more-courses");var offset=getOffset(root),limit=getLimit(root);const startTime=getStartTime(root),endTime=getEndTime(root),searchValue=root.closest(SELECTORS_TIMELINE_BLOCK).find(SELECTORS_TIMELINE_SEARCH).val();return CourseRepository.getEnrolledCoursesWithEventsByTimelineClassification("all",limit,offset,"fullname asc",searchValue,startTime,endTime).then((function(result){var startEventLoadingTime=Date.now(),courses=result.courses,nextOffset=result.nextoffset,daysOffset=getDaysOffset(root),daysLimit=getDaysLimit(root),midnight=getMidnight(root);const moreCoursesAvailable=result.morecoursesavailable;setOffset(root,nextOffset);var eventsPromise=loadEventsForCourses(courses,startTime,endTime,searchValue),renderPromise=updateDisplayFromCourses(courses,root,midnight,daysOffset,daysLimit,append);return $.when(eventsPromise,renderPromise).then((function(eventsByCourse){return hasReloadedEventsSince(root,startEventLoadingTime)||(courses.length>0?(courses.forEach((function(course){const containerSelector='[data-region="course-events-container"][data-course-id="'+course.id+'"]',eventListRoot=root.find(containerSelector).find(EventList.rootSelector);EventList.init(eventListRoot,additionalConfig)})),moreCoursesAvailable?showMoreCoursesButton(root):hideMoreCoursesButton(root)):(hideMoreCoursesButton(root),0==offset&&showNoCoursesWithEventsMessage(root))),eventsByCourse}))})).then((()=>pendingPromise.resolve())).catch(Notification.exception)},registerEventListeners=function(root){CustomEvents.define(root,[CustomEvents.events.activate]),root.on(CustomEvents.events.activate,SELECTORS_MORE_COURSES_BUTTON,(function(e,data){!function(root){var button=root.find(SELECTORS_MORE_COURSES_BUTTON);button.prop("disabled",!0),Templates.render(TEMPLATES_LOADING_ICON,{}).then((function(html){return button.append(html),html})).catch((function(){return!1}))}(root),loadMoreCourses(root,!0).then((function(){disableMoreCoursesButtonLoading(root)})).catch((function(){disableMoreCoursesButtonLoading(root)})),data&&(data.originalEvent.preventDefault(),data.originalEvent.stopPropagation()),e.stopPropagation()}))},shown=function(root){root.attr("data-seen")||root.find(SELECTORS_NO_COURSES_EMPTY_MESSAGE).length||(loadMoreCourses(root),root.attr("data-seen",!0))};return{init:function(root){(root=$(root)).find(SELECTORS_NO_COURSES_EMPTY_MESSAGE).length||(!function(root,time){root.data("last-event-load-time",time)}(root,Date.now()),root.hasClass("active")&&(loadMoreCourses(root),root.attr("data-seen",!0)),registerEventListeners(root))},reset:function(root){setOffset(root,0),function(root){root.find(SELECTORS_COURSE_ITEMS_LOADING_PLACEHOLDER).removeClass("hidden")}(root),function(root){root.find(SELECTORS_NO_COURSES_WITH_EVENTS_MESSAGE).addClass("hidden")}(root),root.removeAttr("data-seen"),root.hasClass("active")&&shown(root)},shown:shown}})); /** * Manage the timeline dates view for the timeline block. * * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/view_dates",["jquery","block_timeline/event_list","core/pubsub","core/paged_content_events"],(function($,EventList,PubSub,PagedContentEvents){var SELECTORS_EVENT_LIST_CONTAINER='[data-region="event-list-container"]',SELECTORS_NO_COURSES_EMPTY_MESSAGE='[data-region="no-courses-empty-message"]',load=function(root){if(!root.find(SELECTORS_NO_COURSES_EMPTY_MESSAGE).length){var eventListContainer=root.find(SELECTORS_EVENT_LIST_CONTAINER),namespace=$(eventListContainer).attr("id")+"user_block_timeline"+Math.random();!function(root,namespace){var event=namespace+PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT;PubSub.subscribe(event,(function(limit){$(root).data("limit",limit)}))}(root,namespace);var config={persistentLimitKey:"block_timeline_user_limit_preference",eventNamespace:namespace};EventList.init(eventListContainer,config)}};return{init:function(root){(root=$(root)).hasClass("active")&&!root.find(SELECTORS_NO_COURSES_EMPTY_MESSAGE).length&&(load(root),root.attr("data-seen",!0))},reset:function(root){root.removeAttr("data-seen"),root.hasClass("active")&&(load(root),root.attr("data-seen",!0))},shown:function(root){root.attr("data-seen")||(load(root),root.attr("data-seen",!0))}}})); /** * Manage the timeline view navigation for the timeline block. * * @copyright 2018 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("block_timeline/view_nav",["jquery","core/custom_interaction_events","block_timeline/view","core/ajax","core/notification","core/utils"],(function($,CustomEvents,View,Ajax,Notification,Utils){var SELECTORS_TIMELINE_DAY_FILTER='[data-region="day-filter"]',SELECTORS_TIMELINE_DAY_FILTER_OPTION="[data-from]",SELECTORS_TIMELINE_VIEW_SELECTOR='[data-region="view-selector"]',SELECTORS_DATA_DAYS_OFFSET="[data-days-offset]",SELECTORS_TIMELINE_SEARCH_INPUT='[data-action="search"]',SELECTORS_TIMELINE_SEARCH_CLEAR_ICON='[data-action="clearsearch"]',SELECTORS_NO_COURSES_EMPTY_MESSAGE='[data-region="no-courses-empty-message"]',updateUserPreferences=function(type,value){var request={methodname:"core_user_update_user_preferences",args:{preferences:[{type:type,value:value}]}};Ajax.call([request])[0].fail(Notification.exception)};const activeSearchState=(clearSearchIcon,timelineViewRoot)=>{clearSearchIcon.removeClass("d-none"),View.reset(timelineViewRoot)},clearSearchState=(clearSearchIcon,timelineViewRoot)=>{clearSearchIcon.addClass("d-none"),View.reset(timelineViewRoot)};return{init:function(root,timelineViewRoot){(function(root,timelineViewRoot){var viewSelector=root.find(SELECTORS_TIMELINE_VIEW_SELECTOR);viewSelector.on("shown shown.bs.tab",(function(e){View.shown(timelineViewRoot),$(e.target).removeClass("active")})),CustomEvents.define(viewSelector,[CustomEvents.events.activate]),viewSelector.on(CustomEvents.events.activate,"[data-toggle='tab']",(function(e){var filtername=$(e.currentTarget).data("filtername");updateUserPreferences("block_timeline_user_sort_preference",filtername)}))})(root=$(root),timelineViewRoot),root.find(SELECTORS_NO_COURSES_EMPTY_MESSAGE).length||(function(root,timelineViewRoot){var timelineDaySelectorContainer=root.find(SELECTORS_TIMELINE_DAY_FILTER);CustomEvents.define(timelineDaySelectorContainer,[CustomEvents.events.activate]),timelineDaySelectorContainer.on(CustomEvents.events.activate,SELECTORS_TIMELINE_DAY_FILTER_OPTION,(function(e,data){var filtername=$(e.currentTarget).data("filtername");updateUserPreferences("block_timeline_user_filter_preference",filtername);var option=$(e.target).closest(SELECTORS_TIMELINE_DAY_FILTER_OPTION);if("true"!=option.attr("aria-current")){var daysOffset=option.attr("data-from"),daysLimit=option.attr("data-to"),elementsWithDaysOffset=root.find(SELECTORS_DATA_DAYS_OFFSET);elementsWithDaysOffset.attr("data-days-offset",daysOffset),null!=daysLimit?elementsWithDaysOffset.attr("data-days-limit",daysLimit):elementsWithDaysOffset.removeAttr("data-days-limit"),"overdue"===option.attr("data-filtername")?elementsWithDaysOffset.attr("data-filter-overdue",!0):elementsWithDaysOffset.removeAttr("data-filter-overdue"),View.reset(timelineViewRoot),data.originalEvent.preventDefault()}}))}(root,timelineViewRoot),((root,timelineViewRoot)=>{const searchInput=root.find(SELECTORS_TIMELINE_SEARCH_INPUT),clearSearchIcon=root.find(SELECTORS_TIMELINE_SEARCH_CLEAR_ICON);searchInput.on("input",Utils.debounce((()=>{""!==searchInput.val()?activeSearchState(clearSearchIcon,timelineViewRoot):clearSearchState(clearSearchIcon,timelineViewRoot)}),1e3)),clearSearchIcon.on("click",(()=>{searchInput.val(""),clearSearchState(clearSearchIcon,timelineViewRoot),searchInput.focus()}))})(root,timelineViewRoot))}}})); define("media_videojs/loader",["exports","core/ajax","core/config","core_filters/events","core/localstorage","core/notification","jquery"],(function(_exports,_ajax,_config,_events,_localstorage,_notification,_jquery){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setUp=void 0,_ajax=_interopRequireDefault(_ajax),_config=_interopRequireDefault(_config),_localstorage=_interopRequireDefault(_localstorage),_notification=_interopRequireDefault(_notification),_jquery=_interopRequireDefault(_jquery);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 firstLoad,language,langStringCache;_exports.setUp=lang=>{language=lang,firstLoad=!0,notifyVideoJS({detail:{nodes:document.body}}),document.addEventListener(_events.eventTypes.filterContentUpdated,notifyVideoJS)};const notifyVideoJS=e=>{const nodes=(0,_jquery.default)(e.detail.nodes),langStrings=getLanguageJson();nodes.find(".mediaplugin_videojs").addBack(".mediaplugin_videojs").find("audio, video").each(((index,element)=>{const id=(0,_jquery.default)(element).attr("id"),config=(0,_jquery.default)(element).data("setup-lazy"),modulePromises=["function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["media_videojs/video-lazy"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("media_videojs/video-lazy")):Promise.resolve(_systemImportTransformerGlobalIdentifier["media_videojs/video-lazy"])];config.techOrder&&-1!==config.techOrder.indexOf("youtube")&&modulePromises.push("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["media_videojs/Youtube-lazy"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("media_videojs/Youtube-lazy")):Promise.resolve(_systemImportTransformerGlobalIdentifier["media_videojs/Youtube-lazy"])),config.techOrder&&-1!==config.techOrder.indexOf("OgvJS")&&(config.ogvjs={worker:!0,wasm:!0,base:_config.default.wwwroot+"/media/player/videojs/ogvloader.php/"+_config.default.jsrev+"/"},modulePromises.push("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["media_videojs/videojs-ogvjs-lazy"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("media_videojs/videojs-ogvjs-lazy")):Promise.resolve(_systemImportTransformerGlobalIdentifier["media_videojs/videojs-ogvjs-lazy"]))),Promise.all([langStrings,...modulePromises]).then((_ref=>{let[langJson,videojs]=_ref;firstLoad&&(videojs.addLanguage(language,langJson),firstLoad=!1),videojs(id,config)})).catch(_notification.default.exception)}))},getLanguageJson=()=>{if(langStringCache)return Promise.resolve(langStringCache);const cacheKey="media_videojs/".concat(language),rawCacheContent=_localstorage.default.get(cacheKey);if(rawCacheContent){const cacheContent=JSON.parse(rawCacheContent);return langStringCache=cacheContent,Promise.resolve(langStringCache)}const request={methodname:"media_videojs_get_language",args:{lang:language}};return _ajax.default.call([request])[0].then((langStringData=>(_localstorage.default.set(cacheKey,langStringData),langStringData))).then((result=>JSON.parse(result))).then((langStrings=>(langStringCache=langStrings,langStrings)))}})); var e,t;e=globalThis,t=function(){return(()=>{var e={318:e=>{e.exports=function(e){return e&&e.__esModule?e:{default:e}},e.exports.default=e.exports,e.exports.__esModule=!0},848:e=>{window,e.exports=function(e){var t={};function r(i){if(t[i])return t[i].exports;var s=t[i]={i:i,l:!1,exports:{}};return e[i].call(s.exports,s,s.exports,r),s.l=!0,s.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)r.d(i,s,function(t){return e[t]}.bind(null,s));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t){function r(e,t){if(e<1||e!==Math.round(e))throw"Invalid channel count for BufferQueue";this.channels=e,this.bufferSize=t,this.flush()}r.prototype.flush=function(){this._buffers=[],this._pendingBuffer=this.createBuffer(this.bufferSize),this._pendingPos=0},r.prototype.sampleCount=function(){var e=0;return this._buffers.forEach((function(t){e+=t[0].length})),e},r.prototype.createBuffer=function(e){for(var t=[],i=0;i<this.channels;i++)t[i]=new Float32Array(e);return t},r.prototype.validate=function(e){if(e.length!==this.channels)return!1;for(var t,i=0;i<e.length;i++){var s=e[i];if(!(s instanceof Float32Array))return!1;if(0==i)t=s.length;else if(s.length!==t)return!1}return!0},r.prototype.appendBuffer=function(e){if(!this.validate(e))throw"Invalid audio buffer passed to BufferQueue.appendBuffer";for(var t=e[0].length,i=this.channels,s=this._pendingPos,d=this._pendingBuffer,h=this.bufferSize,u=0;u<t;u++){for(var c=0;c<i;c++)d[c][s]=e[c][u];++s==h&&(this._buffers.push(d),s=this._pendingPos=0,d=this._pendingBuffer=this.createBuffer(h))}this._pendingPos=s},r.prototype.prependBuffer=function(e){if(!this.validate(e))throw"Invalid audio buffer passed to BufferQueue.prependBuffer";var t=this._buffers.slice(0);t.push(this.trimBuffer(this._pendingBuffer,0,this._pendingPos)),this.flush(),this.appendBuffer(e);for(var i=0;i<t.length;i++)this.appendBuffer(t[i])},r.prototype.nextBuffer=function(){if(this._buffers.length)return this._buffers.shift();var e=this.trimBuffer(this._pendingBuffer,0,this._pendingPos);return this._pendingBuffer=this.createBuffer(this.bufferSize),this._pendingPos=0,e},r.prototype.trimBuffer=function(e,t,i){var s=e[0].length,d=t+Math.min(i,s);if(0==t&&d>=s)return e;for(var h=[],u=0;u<this.channels;u++)h[u]=e[u].subarray(t,d);return h},e.exports=r},function(e,t,i){!function(){i(0);var t=i(2),s=i(4);function n(e){this._options=e||{},this._backend=null,this._resampleFractional=0,this._resampleLastSampleData=void 0,this._tempoChanger=null}n.prototype.rate=0,n.prototype.targetRate=0,n.prototype.channels=0,n.prototype.bufferSize=0,Object.defineProperty(n.prototype,"bufferDuration",{get:function(){return this.targetRate?this.bufferSize/this.targetRate:0}}),Object.defineProperty(n.prototype,"bufferThreshold",{get:function(){return this._backend?this._backend.bufferThreshold/this.targetRate:0},set:function(e){if(!this._backend)throw"Invalid state: AudioFeeder cannot set bufferThreshold before init";this._backend.bufferThreshold=Math.round(e*this.targetRate)}}),Object.defineProperty(n.prototype,"playbackPosition",{get:function(){return this._backend?this.getPlaybackState().playbackPosition:0}}),Object.defineProperty(n.prototype,"outputPlaybackPosition",{get:function(){return this._backend?this.getPlaybackState().outputPlaybackPosition:0}}),Object.defineProperty(n.prototype,"durationBuffered",{get:function(){return this._backend?this.getPlaybackState().samplesQueued/this.targetRate:0}}),Object.defineProperty(n.prototype,"muted",{get:function(){if(this._backend)return this._backend.muted;throw"Invalid state: cannot get mute before init"},set:function(e){if(!this._backend)throw"Invalid state: cannot set mute before init";this._backend.muted=e}}),n.prototype.mute=function(){this.muted=!0},n.prototype.unmute=function(){this.muted=!1},Object.defineProperty(n.prototype,"volume",{get:function(){if(this._backend)return this._backend.volume;throw"Invalid state: cannot get volume before init"},set:function(e){if(!this._backend)throw"Invalid state: cannot set volume before init";this._backend.volume=e}}),Object.defineProperty(n.prototype,"tempo",{get:function(){if(this._tempoChanger)return this._tempoChanger.getTempo();throw"Invalid state: cannot get tempo before init"},set:function(e){if(!this._tempoChanger)throw"Invalid state: cannot set tempo before init";this._tempoChanger.setTempo(e)}}),n.prototype.init=function(e,i){if(this.channels=e,this.rate=i,this._options.backendFactory)this._backend=this._options.backendFactory(e,i,this._options);else{if(!t.isSupported())throw"No supported backend";this._backend=new t(e,i,this._options)}this.targetRate=this._backend.rate,this.bufferSize=this._backend.bufferSize,this._tempoChanger=s({sampleRate:this.targetRate,numChannels:e,tempo:1}),this._backend.onstarved=function(){this.onstarved&&this.onstarved()}.bind(this),this._backend.onbufferlow=function(){this.onbufferlow&&this.onbufferlow()}.bind(this)},n.prototype._resample=function(e){var t=this.rate,i=this.channels,s=this._backend.rate,d=this._backend.channels;if(t==s&&i==d)return e;var h,u=[],c=e[0].length,l=this._resampleFractional,f=c*s/t+l,_=Math.floor(f),p=f-_;h=t<s?function(e,i,d,h){for(var a=function(t){return t<0?d&&d.length+t>0?d[d.length+t]:e[0]:e[t]},u=0;u<i.length;u++){var c,f=(u+1-l)*t/s-1,_=Math.floor(f),p=Math.ceil(f);c=_==p?a(_):a(_)*(p-f)+a(p)*(f-_),i[u]=h*c}}:function(e,t,i,s){for(var d=0;d<t.length;d++)t[d]=s*e[d*e.length/t.length|0]};var m=1;d>i&&(m=Math.SQRT1_2);for(var g=0;g<d;g++){var v=g;g>=i&&(v=0);var y=e[v],b=new Float32Array(_);h(y,b,this._resampleLastSampleData?this._resampleLastSampleData[v]:void 0,m),u.push(b)}return this._resampleFractional=p,this._resampleLastSampleData=e,u},n.prototype.bufferData=function(e){if(!this._backend)throw"Invalid state: AudioFeeder cannot bufferData before init";var t=this._resample(e);t=this._tempoChanger.process(t),this._backend.appendBuffer(t)},n.prototype.getPlaybackState=function(){if(this._backend){var e=this._backend.getPlaybackState();return e.outputPlaybackPosition=e.playbackPosition,e.playbackPosition=this._tempoChanger.mapOutputToInputTime(e.outputPlaybackPosition),e}throw"Invalid state: AudioFeeder cannot getPlaybackState before init"},n.prototype.waitUntilReady=function(e){if(!this._backend)throw"Invalid state: AudioFeeder cannot waitUntilReady before init";this._backend.waitUntilReady(e)},n.prototype.start=function(){if(!this._backend)throw"Invalid state: AudioFeeder cannot start before init";this._backend.start()},n.prototype.stop=function(){if(!this._backend)throw"Invalid state: AudioFeeder cannot stop before init";this._backend.stop()},n.prototype.flush=function(){if(this._resampleFractional=0,this._resampleLastSampleData=void 0,!this._backend)throw"Invalid state: AudioFeeder cannot flush before init";this._tempoChanger.flush(this.durationBuffered),this._backend.flush()},n.prototype.close=function(){this._backend&&(this._backend.close(),this._backend=null)},n.prototype.onstarved=null,n.prototype.onbufferlow=null,n.isSupported=function(){return!!Float32Array&&t.isSupported()},n.initSharedAudioContext=function(){return t.isSupported()?t.initSharedAudioContext():null},e.exports=n}()},function(e,t,i){!function(){var t=window.AudioContext||window.webkitAudioContext,s=i(0),d=i(3);function o(e,t,i){var d=i.audioContext||o.initSharedAudioContext();if(this._context=d,this.output=i.output||d.destination,this.rate=d.sampleRate,this.channels=2,i.bufferSize&&(this.bufferSize=0|i.bufferSize),this.bufferThreshold=2*this.bufferSize,this._bufferQueue=new s(this.channels,this.bufferSize),this._playbackTimeAtBufferTail=d.currentTime,this._queuedTime=0,this._delayedTime=0,this._dropped=0,this._liveBuffer=this._bufferQueue.createBuffer(this.bufferSize),d.createScriptProcessor)this._node=d.createScriptProcessor(this.bufferSize,0,this.channels);else{if(!d.createJavaScriptNode)throw new Error("Bad version of web audio API?");this._node=d.createJavaScriptNode(this.bufferSize,0,this.channels)}}o.prototype.bufferSize=4096,o.prototype.bufferThreshold=8192,o.prototype._volume=1,Object.defineProperty(o.prototype,"volume",{get:function(){return this._volume},set:function(e){this._volume=+e}}),o.prototype._muted=!1,Object.defineProperty(o.prototype,"muted",{get:function(){return this._muted},set:function(e){this._muted=!!e}}),o.prototype._audioProcess=function(e){var t,i,s,h,u;u="number"==typeof e.playbackTime?e.playbackTime:this._context.currentTime+this.bufferSize/this.rate;var c=this._playbackTimeAtBufferTail;if(c<u&&(this._delayedTime+=u-c),this._bufferQueue.sampleCount()<this.bufferSize&&this.onstarved&&this.onstarved(),this._bufferQueue.sampleCount()<this.bufferSize){for(t=0;t<this.channels;t++)for(s=e.outputBuffer.getChannelData(t),h=0;h<this.bufferSize;h++)s[h]=0;this._dropped++}else{var l=this.muted?0:this.volume,f=this._bufferQueue.nextBuffer();if(f[0].length<this.bufferSize)throw"Audio buffer not expected length.";for(t=0;t<this.channels;t++)for(i=f[t],this._liveBuffer[t].set(f[t]),s=e.outputBuffer.getChannelData(t),h=0;h<i.length;h++)s[h]=i[h]*l;this._queuedTime+=this.bufferSize/this.rate,this._playbackTimeAtBufferTail=u+this.bufferSize/this.rate,this._bufferQueue.sampleCount()<Math.max(this.bufferSize,this.bufferThreshold)&&this.onbufferlow&&d(this.onbufferlow.bind(this))}},o.prototype._samplesQueued=function(){return this._bufferQueue.sampleCount()+Math.floor(this._timeAwaitingPlayback()*this.rate)},o.prototype._timeAwaitingPlayback=function(){return Math.max(0,this._playbackTimeAtBufferTail-this._context.currentTime)},o.prototype.getPlaybackState=function(){return{playbackPosition:this._queuedTime-this._timeAwaitingPlayback(),samplesQueued:this._samplesQueued(),dropped:this._dropped,delayed:this._delayedTime}},o.prototype.waitUntilReady=function(e){e()},o.prototype.appendBuffer=function(e){this._bufferQueue.appendBuffer(e)},o.prototype.start=function(){this._node.onaudioprocess=this._audioProcess.bind(this),this._node.connect(this.output),this._playbackTimeAtBufferTail=this._context.currentTime},o.prototype.stop=function(){if(this._node){var e=this._timeAwaitingPlayback();if(e>0){var t=Math.round(e*this.rate),i=this._liveBuffer?this._liveBuffer[0].length:0;t>i?(this._bufferQueue.prependBuffer(this._liveBuffer),this._bufferQueue.prependBuffer(this._bufferQueue.createBuffer(t-i))):this._bufferQueue.prependBuffer(this._bufferQueue.trimBuffer(this._liveBuffer,i-t,t)),this._playbackTimeAtBufferTail-=e}this._node.onaudioprocess=null,this._node.disconnect()}},o.prototype.flush=function(){this._bufferQueue.flush()},o.prototype.close=function(){this.stop(),this._context=null},o.prototype.onstarved=null,o.prototype.onbufferlow=null,o.isSupported=function(){return!!t},o.sharedAudioContext=null,o.initSharedAudioContext=function(){if(!o.sharedAudioContext&&o.isSupported()){var e,i=new t;if(i.createScriptProcessor)e=i.createScriptProcessor(1024,0,2);else{if(!i.createJavaScriptNode)throw new Error("Bad version of web audio API?");e=i.createJavaScriptNode(1024,0,2)}e.connect(i.destination),e.disconnect(),o.sharedAudioContext=i}return o.sharedAudioContext},e.exports=o}()},function(e,t){e.exports=function(){if(void 0!==window.setImmediate)return window.setImmediate;if(window&&window.postMessage){var e=[];return window.addEventListener("message",(function(t){if(t.source===window){var i=t.data;if("object"==typeof i&&i.nextTickBrowserPingMessage){var s=e.pop();s&&s()}}})),function(t){e.push(t),window.postMessage({nextTickBrowserPingMessage:!0},document.location.toString())}}return function(e){setTimeout(e,0)}}()},function(e,t,i){var s;window,s=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var s=t[i]={i:i,l:!1,exports:{}};return e[i].call(s.exports,s,s.exports,r),s.l=!0,s.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)r.d(i,s,function(t){return e[t]}.bind(null,s));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t){var i={float_array:function(e){return new Float32Array(e)},blit:function(e,t,i,s,d){i.set(e.subarray(t,t+d),s)}};e.exports=i},function(e,t,i){var s,d;s=i(0),d=i(2),e.exports=function(e){var t=(e=e||{}).sampleRate||44100,i=e.wsizeLog||11,h=e.tempo||1,u=(e.numChannels,Math.pow(2,50/1200)-1),c=1<<i,l=d(i),f=1<<i-2;f-=f%100;for(var _=s.float_array(c+f+5),p=s.float_array(c+f+5),m=f,g=f,v=s.float_array(c),y=0;y<c;y++)v[y]=.5*(1-Math.cos(2*Math.PI*y/c));var b=1+(c>>1),T=s.float_array(b),k=s.float_array(b),P=s.float_array(b),w=s.float_array(b),E=s.float_array(b),x=s.float_array(b),A=1+(b>>1),R=[0,0],O=[],F=[],S=[],C=[];for(y=0;y<2;y++)O.push(s.float_array(A)),F.push(s.float_array(A)),S.push(s.float_array(A)),C.push(s.float_array(b));var B=s.float_array(A),D=s.float_array(A),M=0,V=0,I=[{in_time:0,out_time:0,tempo:h}],L=0,j=0,W=1,X=0,N=0,H=0,z=0,Y={mapOutputToInputTime:function(e){for(var t=I.length-1;e<I[t].out_time&&t>0;)t--;var i=I[t];return i.in_time+i.tempo*(e-i.out_time)},flush:function(e){X=0,R=[0,0],j=0,z=0,H=0;for(var t=0;t<2;t++)for(var i=0;i<b;i++)C[t][i]=0;for(t=0;t<_.length;t++)_[t]=0;for(t=0;t<p.length;t++)p[t]=0;if(e){V=Math.max(0,V-e),M=Y.mapOutputToInputTime(V);for(var s=I.length-1;V<=I[s].out_time&&s>=0;)I.pop(),s--;I.push({in_time:M,out_time:V,tempo:h})}},getTempo:function(){return h},setTempo:function(e){m=g=f,e>=1?g=Math.round(m/e):m=Math.round(g*e),N=(1/e-1*g/m)*m,W=function(e,t){for(var i=e.length/t|0,s=0,d=0;d<i;d++)s+=e[d*t];return.9/s}(v,g),h=e;var t=I[I.length-1];t.out_time==V?t.tempo=e:I.push({in_time:M,out_time:V,tempo:e})}};Y.flush(0),Y.setTempo(h);var J=function(e,t,i){var s=Math.floor(i),d=s%2==1?-1:1;return Math.atan2(d*(t[s]-t[s+1]),d*(e[s]-e[s+1]))},U=function(e,t,i,s,d){var h=2*Math.PI/c*.5*(s+t)*m;return(function(e){return e-2*Math.PI*Math.round(e/(2*Math.PI))}(e-i-h)+h)*d},q=function(e,t,i,s,d,h){for(var l=e%2,f=1-l,_=C[f],p=R[f],m=O[f],g=F[f],v=S[f],y=C[l],b=1;b<y.length;b++)y[b]=t[b]*t[b]+i[b]*i[b];var T=O[l],k=R[l]=function(e,t){for(var i=0,s=0;s<e.length;s++)e[s]>i&&(i=e[s]);var d=1e-8*i,h=1,c=1;for(t[0]=1,s=2;s<e.length;s++){var l=s*u;if(e[s]>d&&e[s]>e[s-1]&&e[s]>=e[s+1]){var f=s+(e[s-1]-e[s+1])/(2*(e[s-1]-2*e[s]+e[s+1]));f-t[h-1]>l?(t[h++]=f,c=s):e[s]>e[c]&&(t[h-1]=f,c=s)}}return h}(y,T),P=F[l],w=S[l];if(0!=e&&0!=k){var E=0;for(H=0;H<k;H++){for(z=T[H];T[H]>m[E]&&E!=p;)++E;var x=E;E>0&&z-m[E-1]<m[E]-z&&(x=E-1);var A=z*u;if(Math.abs(m[x]-z)<A&&_[Math.round(m[x])]>.1*y[Math.round(z)]){var M=J(t,i,z),V=g[x]+v[x]+U(M,z,g[x],m[x],h)-M;P[H]=M,w[H]=V,B[H]=Math.cos(V),D[H]=Math.sin(V)}else P[H]=J(t,i,z),w[H]=0,B[H]=1,D[H]=0}T[k]=2*c;var I=T[x=0],L=T[x+1],j=B[x],W=D[x];for(b=1;b<t.length-1;b++){b>=I&&b-I>L-b&&(I=T[++x],L=T[x+1],j=B[x],W=D[x]);var X=t[b]*j-i[b]*W,N=t[b]*W+i[b]*j;t[b]=X,i[b]=N}}else for(var H=0;H<k;H++){var z=T[H];g[H]=v[H]=J(t,i,z)}},G=function(){var e=0|(X+=2*N);X-=e;for(var t=0;t<c;t++)l.m_re[t]=v[t]*_[t],l.m_im[t]=v[t]*_[m+t];s.blit(_,2*m,_,0,c-m),l.inplace(!1),l.unpack(T,k,P,w),q(L,T,k,0,0,1*g/m),q(L+1,P,w,0,0,1*(g+e)/m),s.blit(P,0,E,0,b),s.blit(w,0,x,0,b),l.repack(T,k,P,w),l.inplace(!0);var i=p.length;for(s.blit(p,j,p,0,i-j),t=i-j;t<i;t++)p[t]=0;var d=0,h=W;for(t=0;t<g;t++)Math.abs(2*l.m_re[t])>d&&(d=Math.abs(2*l.m_re[t]));for(t=0;t<c-g;t++)Math.abs(l.m_re[t+g+e]+l.m_im[t])>d&&(d=Math.abs(l.m_re[t+g+e]+l.m_im[t]));for(t=c-g;t<c;t++)Math.abs(2*l.m_im[t])>d&&(d=Math.abs(2*l.m_im[t]));var u=1/Math.floor(1*c/(2*g));for(h*d>u&&(h=u/d),t=0;t<c;t++)p[t]+=h*l.m_re[t],p[t+g+e]+=h*l.m_im[t];return L+=2,j=2*g+e};return Y.process=function(e){var i=e[0].length,d=e[0];if(e.length>1){d=s.float_array(e[0].length);for(var u=1/e.length,l=0;l<e.length;l++)for(var f=0;f<i;f++)d[f]+=u*e[l][f]}if(1==h){if(z+H>0){var v=z+H+i,y=[];for(l=0;l<e.length;l++){var b=s.float_array(v);s.blit(p,0,b,0,z),s.blit(_,0,b,z,H),s.blit(e[l],0,b,z+H,i),y.push(b)}Y.flush(0),i=v,e=y}return M+=i/t,V+=i/t,e}var T=H+i-(c-m),k=2*Math.floor(Math.max(0,T)/(2*m)),P=z+g*k+Math.floor(X+N*k);z>P&&(P=z);var w=s.float_array(P);s.blit(p,0,w,0,z);for(var E=0,x=z,A=0,R=0;;){var O=c+m-H;if(E+O>i){s.blit(d,E,_,H,i-E),H+=i-E,E=i;break}O<=0?H-=2*m:(s.blit(d,E,_,H,O),E+=O,H=c-m),R=G(),M+=2*m/t,V+=R/t,(A=x+R-P)<0&&(A=0),s.blit(p,0,w,x,R-A),x+=R}s.blit(p,R-A,p,0,A),z=A;var F=[];for(l=0;l<e.length;l++)F.push(w);return F},Y}},function(e,t,i){var s=i(0);e.exports=function(e){for(var t=1<<e,i={m_logN:e,m_N:t,m_invN:1/t,m_re:s.float_array(t),m_im:s.float_array(t),m_revTgt:new Array(t)},d=0;d<t;d++){for(var h=d,u=0,c=0;c<e;c++)u<<=1,u|=1&h,h>>=1;i.m_revTgt[d]=u}i.twiddleRe=s.float_array(i.m_logN),i.twiddleIm=s.float_array(i.m_logN);for(var l=1,f=0;f<i.m_logN;f++){var _=2*l*Math.PI*i.m_invN;i.twiddleRe[f]=Math.cos(_),i.twiddleIm[f]=Math.sin(_),l<<=1}i.inplace=function(e){var t=i.m_re,s=i.m_im,d=i.m_N,h=i.m_logN,u=d>>1,c=d>>1,l=d;if(e)for(var f=1/d,_=0;_<d;_++)t[_]*=f,s[_]*=f;for(var p=0;p<h;p++){var m=i.twiddleRe[p],g=i.twiddleIm[p];e||(g*=-1);for(var v=0;v<d;){for(var y=v,b=v+c,T=1,k=0,P=0;P<u;P++){var w=t[y],E=s[y],x=t[b],A=s[b];t[y]=w+x,s[y]=E+A,x=w-x,A=E-A,t[b]=x*T-A*k,s[b]=x*k+A*T,y++,b++;var R=T;T=T*m-k*g,k=R*g+k*m}v+=l}u>>=1,c>>=1,l>>=1}for(var O,F,S=i.m_revTgt,C=0;C<d;C++)S[C]>C&&(F=t[O=S[C]],t[O]=t[C],t[C]=F,F=s[O],s[O]=s[C],s[C]=F)};var p=t>>1;return i.unpack=function(e,s,d,h){e[0]=i.m_re[0],d[0]=i.m_im[0],s[0]=h[0]=0,e[p]=i.m_re[p],d[p]=i.m_im[p],s[p]=h[p]=0;for(var u=1;u<p;u++)e[u]=(i.m_re[u]+i.m_re[t-u])/2,s[u]=(i.m_im[u]-i.m_im[t-u])/2,d[u]=(i.m_im[u]+i.m_im[t-u])/2,h[u]=(-i.m_re[u]+i.m_re[t-u])/2},i.repack=function(e,s,d,h){i.m_re[0]=e[0],i.m_im[0]=d[0],i.m_re[p]=e[p],i.m_im[p]=d[p];for(var u=1;u<p;u++)i.m_re[u]=e[u]-h[u],i.m_im[u]=s[u]+d[u],i.m_re[t-u]=e[u]+h[u],i.m_im[t-u]=-s[u]+d[u]},i}}])},e.exports=s()}])},893:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{constructor(e){this.lower=e.start,this.upper=e.end,this.onprocess=e.process,this.position=0,this.n=0}iterate(){return this.n++,this.position=Math.floor((this.lower+this.upper)/2),this.onprocess(this.lower,this.upper,this.position)}start(){return this.iterate(),this}left(){return this.upper=this.position,this.iterate()}right(){return this.lower=this.position,this.iterate()}}},523:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=new class{hasTypedArrays(){return!!window.Uint32Array}hasWebAssembly(){return!!window.WebAssembly}hasWebAudio(){return!(!window.AudioContext&&!window.webkitAudioContext)}hasFlash(){return!1}hasAudio(){return this.hasWebAudio()}isBlacklisted(e){return!1}isSlow(){return!1}isTooSlow(){return!1}supported(e){return"OGVDecoder"===e?this.hasWebAssembly():"OGVPlayer"===e&&this.supported("OGVDecoder")&&this.hasAudio()}};t.default=i},408:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(580));class OGVDecoderAudioProxy extends((0,d.default)({loadedMetadata:!1,audioFormat:null,audioBuffer:null,cpuTime:0})){init(e){this.proxy("init",[],e)}processHeader(e,t){this.proxy("processHeader",[e],t,[e])}processAudio(e,t){this.proxy("processAudio",[e],t,[e])}close(){this.terminate()}}var h=OGVDecoderAudioProxy;t.default=h},319:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(580));class OGVDecoderVideoProxy extends((0,d.default)({loadedMetadata:!1,videoFormat:null,frameBuffer:null,cpuTime:0})){init(e){this.proxy("init",[],e)}processHeader(e,t){this.proxy("processHeader",[e],t,[e])}processFrame(e,t){this.proxy("processFrame",[e],t,[e])}close(){this.terminate()}sync(){this.proxy("sync",[],(()=>{}))}recycleFrame(e){this.proxy("recycleFrame",[e],(()=>{}),[e.y.bytes.buffer,e.u.bytes.buffer,e.v.bytes.buffer])}}var h=OGVDecoderVideoProxy;t.default=h},445:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(539)),h="1.8.4-20210702161914-bd3a07f",u={OGVDemuxerOggW:"ogv-demuxer-ogg-wasm.js",OGVDemuxerWebMW:"ogv-demuxer-webm-wasm.js",OGVDecoderAudioOpusW:"ogv-decoder-audio-opus-wasm.js",OGVDecoderAudioVorbisW:"ogv-decoder-audio-vorbis-wasm.js",OGVDecoderVideoTheoraW:"ogv-decoder-video-theora-wasm.js",OGVDecoderVideoVP8W:"ogv-decoder-video-vp8-wasm.js",OGVDecoderVideoVP8MTW:"ogv-decoder-video-vp8-mt-wasm.js",OGVDecoderVideoVP9W:"ogv-decoder-video-vp9-wasm.js",OGVDecoderVideoVP9SIMDW:"ogv-decoder-video-vp9-simd-wasm.js",OGVDecoderVideoVP9MTW:"ogv-decoder-video-vp9-mt-wasm.js",OGVDecoderVideoVP9SIMDMTW:"ogv-decoder-video-vp9-simd-mt-wasm.js",OGVDecoderVideoAV1W:"ogv-decoder-video-av1-wasm.js",OGVDecoderVideoAV1SIMDW:"ogv-decoder-video-av1-simd-wasm.js",OGVDecoderVideoAV1MTW:"ogv-decoder-video-av1-mt-wasm.js",OGVDecoderVideoAV1SIMDMTW:"ogv-decoder-video-av1-simd-mt-wasm.js"};t.default=class{constructor(){this.base=this.defaultBase()}defaultBase(){}wasmSupported(){return d.default.wasmSupported()}scriptForClass(e){return u[e]}urlForClass(e){var t=this.scriptForClass(e);if(t)return this.urlForScript(t);throw new Error("asked for URL for unknown class "+e)}urlForScript(e){if(e){var t=this.base;return void 0===t?t="":t+="/",t+e+"?version="+encodeURIComponent(h)}throw new Error("asked for URL for unknown script "+e)}loadClass(e,t,i){i=i||{};var s=this.getGlobal(),d=this.urlForClass(e),classWrapper=t=>((t=t||{}).locateFile=e=>"data:"===e.slice(0,5)?e:this.urlForScript(e),t.mainScriptUrlOrBlob=this.scriptForClass(e)+"?version="+encodeURIComponent(h),s[e](t));"function"==typeof s[e]?t(classWrapper):this.loadScript(d,(()=>{t(classWrapper)}))}}},964:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(408)),h=s(i(319)),u=s(i(445)),c={audio:{proxy:d.default,worker:"ogv-worker-audio.js"},video:{proxy:h.default,worker:"ogv-worker-video.js"}},l={OGVDecoderAudioOpusW:"audio",OGVDecoderAudioVorbisW:"audio",OGVDecoderVideoTheoraW:"video",OGVDecoderVideoVP8W:"video",OGVDecoderVideoVP9W:"video",OGVDecoderVideoVP9SIMDW:"video",OGVDecoderVideoAV1W:"video",OGVDecoderVideoAV1SIMDW:"video"};class OGVLoaderWeb extends u.default{constructor(){super(),this.scriptStatus={},this.scriptCallbacks={}}getGlobal(){return window}defaultBase(){for(var e,t,i=document.querySelectorAll("script"),s=/^(?:|(.*)\/)ogv(?:-support|-es2017)?\.js(?:\?|#|$)/,d=0;d<i.length;d++)if((e=i[d].getAttribute("src"))&&(t=e.match(s)))return t[1]}loadClass(e,t,i){(i=i||{}).worker?this.workerProxy(e,t):super.loadClass(e,t,i)}loadScript(e,t){if("done"==this.scriptStatus[e])t();else if("loading"==this.scriptStatus[e])this.scriptCallbacks[e].push(t);else{this.scriptStatus[e]="loading",this.scriptCallbacks[e]=[t];var i=document.createElement("script"),done=t=>{var i=this.scriptCallbacks[e];delete this.scriptCallbacks[e],this.scriptStatus[e]="done",i.forEach((e=>{e()}))};i.addEventListener("load",done),i.addEventListener("error",done),i.src=e,document.querySelector("head").appendChild(i)}}workerProxy(e,t){var i=c[l[e]];if(!i)throw new Error("Requested worker for class with no proxy: "+e);var s,d=i.proxy,h=i.worker,u=this.urlForScript(this.scriptForClass(e)),_=this.urlForScript(h),p=function(t){return new d(s,e,t)};if(_.match(/^https?:|\/\//i)){var m,g,v,y,b,T=!1,k=!1;function completionCheck(){if(1==T&&1==k){var e=v+" "+y+"\nOGVLoader.base = "+JSON.stringify(f.base);try{b=new Blob([e],{type:"application/javascript"})}catch(t){window.BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,(b=new BlobBuilder).append(e),b=b.getBlob()}s=new Worker(URL.createObjectURL(b)),t((function(e){return Promise.resolve(new p(e))}))}}(m=new XMLHttpRequest).open("GET",u,!0),m.onreadystatechange=function(){4==m.readyState&&200==m.status&&(v=m.responseText,T=!0,completionCheck())},m.send(),(g=new XMLHttpRequest).open("GET",_,!0),g.onreadystatechange=function(){4==g.readyState&&200==g.status&&(y=g.responseText,k=!0,completionCheck())},g.send()}else s=new Worker(_),t((function(e){return Promise.resolve(new p(e))}))}}var f=new OGVLoaderWeb,_=f;t.default=_},759:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(309)),h={MEDIA_ERR_ABORTED:1,MEDIA_ERR_NETWORK:2,MEDIA_ERR_DECODE:3,MEDIA_ERR_SRC_NOT_SUPPORTED:4};class OGVMediaError{constructor(e,t){this.code=e,this.message=t}}(0,d.default)(OGVMediaError,h),(0,d.default)(OGVMediaError.prototype,h);var u=OGVMediaError;t.default=u},278:(e,t)=>{function split(e,t,i){var s=e.split(t,i).map((e=>function(e){return e.replace(/^\s+/,"").replace(/\s+$/,"")}(e)));if("number"==typeof i)for(;s.length<i;)s.push(null);return s}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{constructor(e){e=String(e),this.major=null,this.minor=null,this.codecs=null;var t=split(e,";");if(t.length){var i=t.shift();if(i){var s=split(i,"/",2);this.major=s[0],this.minor=s[1]}for(var d in t){var h=t[d].match(/^codecs\s*=\s*"(.*?)"$/);if(h){this.codecs=split(h[1],",");break}}}}}},869:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d,h=s(i(731)),u=s(i(936)),c=s(i(848)),l=s(i(964)),f=s(i(893)),_=s(i(309)),p=s(i(759)),m=s(i(278)),g=s(i(168)),v=s(i(625)),y=(()=>{if("function"==typeof setImmediate)return setImmediate;var e=new MessageChannel,t=[];return e.port1.onmessage=e=>{t.shift()()},function(i){t.push(i),e.port2.postMessage({})}})(),b={NETWORK_EMPTY:0,NETWORK_IDLE:1,NETWORK_LOADING:2,NETWORK_NO_SOURCE:3,HAVE_NOTHING:0,HAVE_METADATA:1,HAVE_CURRENT_DATA:2,HAVE_FUTURE_DATA:3,HAVE_ENOUGH_DATA:4},T="INITIAL",k="SEEKING_END",P="LOADED",w="PRELOAD",E="READY",x="PLAYING",A="SEEKING",R="ERROR",O="NOT_SEEKING",F="BISECT_TO_TARGET",S="BISECT_TO_KEYPOINT",C="LINEAR_TO_TARGET",D="fast";function OGVJSElement(){var e=document.createElement("ogvjs");return Object.setPrototypeOf?Object.setPrototypeOf(e,Object.getPrototypeOf(this)):e.__proto__=this.__proto__,e}d="undefined"==typeof performance||void 0===typeof performance.now?Date.now:performance.now.bind(performance),OGVJSElement.prototype=Object.create(HTMLElement.prototype,{});class OGVPlayer extends OGVJSElement{constructor(e){if(super(),(e=e||{}).base=e.base||l.default.base,this._options=e,this._instanceId="ogvjs"+ ++OGVPlayer.instanceCount,void 0!==e.worker?this._enableWorker=!!e.worker:this._enableWorker=!!window.Worker,!l.default.wasmSupported())throw new Error("WebAssembly not supported");this._enableThreading=!!e.threading,this._enableSIMD=!!e.simd,this._state=T,this._seekState=O,this._detectedType=null,this._canvas=document.createElement("canvas"),this._frameSink=null,e.video&&this._canvas.captureStream?(this._mediaStream=new MediaStream,this._video="object"==typeof e.video?e.video:document.createElement("video"),this._video.playsInline=!0,this._video.srcObject=this._mediaStream):this._video=null,this._videoTrack=null,this._audioTrack=null,this._canvasStream=null,this.className=this._instanceId,(0,_.default)(this,b),this._view=this._video||this._canvas,this._view.style.position="absolute",this._view.style.top="0",this._view.style.left="0",this._view.style.width="100%",this._view.style.height="100%",this._view.style.objectFit="contain",this.appendChild(this._view),this._startTime=d(),this._codec=null,this._audioInfo=null,this._videoInfo=null,this._actionQueue=[],this._audioFeeder=null,this._muted=!1,this._initialPlaybackPosition=0,this._initialPlaybackOffset=0,this._prebufferingAudio=!1,this._initialSeekTime=0,this._currentSrc="",this._streamEnded=!1,this._mediaError=null,this._dataEnded=!1,this._byteLength=0,this._duration=null,this._lastSeenTimestamp=null,this._nextProcessingTimer,this._nextFrameTimer=null,this._loading=!1,this._started=!1,this._paused=!0,this._ended=!1,this._startedPlaybackInDocument=!1,this._stream=void 0,this._framesProcessed=0,this._targetPerFrameTime=1e3/60,this._actualPerFrameTime=0,this._totalFrameTime=0,this._totalFrameCount=0,this._playTime=0,this._bufferTime=0,this._drawingTime=0,this._proxyTime=0,this._totalJitter=0,this._droppedAudio=0,this._delayedAudio=0,this._lateFrames=0,this._poster="",this._thumbnail=null,this._frameEndTimestamp=0,this._audioEndTimestamp=0,this._decodedFrames=[],this._pendingFrames=[],this._lastFrameDecodeTime=0,this._lastFrameVideoCpuTime=0,this._lastFrameAudioCpuTime=0,this._lastFrameDemuxerCpuTime=0,this._lastFrameDrawingTime=0,this._lastFrameBufferTime=0,this._lastFrameProxyTime=0,this._lastVideoCpuTime=0,this._lastAudioCpuTime=0,this._lastDemuxerCpuTime=0,this._lastBufferTime=0,this._lastProxyTime=0,this._lastDrawingTime=0,this._lastFrameTimestamp=0,this._currentVideoCpuTime=0,this._lastTimeUpdate=0,this._timeUpdateInterval=250,this._seekTargetTime=0,this._bisectTargetTime=0,this._seekMode=null,this._lastSeekPosition=null,this._seekBisector=null,this._didSeek=null,this._depth=0,this._needProcessing=!1,this._pendingFrame=0,this._pendingAudio=0,this._framePipelineDepth=8,this._frameParallelism=this._enableThreading?Math.min(16,navigator.hardwareConcurrency)||1:0,this._audioPipelineDepth=12,this._videoInfo=null,this._audioInfo=null,this._width=0,this._height=0,this._volume=1,this._playbackRate=1,Object.defineProperties(this,{src:{get:function(){return this.getAttribute("src")||""},set:function(e){this.setAttribute("src",e),this._loading=!1,this._prepForLoad("interactive")}},buffered:{get:function(){var e;return e=this._stream&&this._byteLength&&this._duration?this._stream.getBufferedRanges().map((e=>e.map((e=>e/this._stream.length*this._duration)))):[[0,0]],new g.default(e)}},seekable:{get:function(){return this.duration<1/0&&this._stream&&this._stream.seekable&&this._codec&&this._codec.seekable?new g.default([[0,this._duration]]):new g.default([])}},currentTime:{get:function(){return this._state==A?this._seekTargetTime:this._codec?this._state!=x||this._paused?this._initialPlaybackOffset:this._getPlaybackTime():this._initialSeekTime},set:function(e){this._seek(e,"exact")}},duration:{get:function(){return this._codec&&this._codec.loadedMetadata?null!==this._duration?this._duration:1/0:NaN}},paused:{get:function(){return this._paused}},ended:{get:function(){return this._ended}},seeking:{get:function(){return this._state==A}},muted:{get:function(){return this._muted},set:function(e){this._muted=e,this._audioFeeder?this._audioFeeder.muted=this._muted:this._started&&!this._muted&&this._codec&&this._codec.hasAudio&&(this._log("unmuting: switching from timer to audio clock"),this._initAudioFeeder(),this._startPlayback(this._audioEndTimestamp)),this._fireEventAsync("volumechange")}},poster:{get:function(){return this._poster},set:function(e){if(this._poster=e,!this._started){this._thumbnail&&this.removeChild(this._thumbnail);var t=new Image;t.src=this._poster,t.className="ogvjs-poster",t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.visibility="hidden",t.addEventListener("load",(()=>{this._thumbnail===t&&(OGVPlayer.styleManager.appendRule("."+this._instanceId,{width:t.naturalWidth+"px",height:t.naturalHeight+"px"}),OGVPlayer.updatePositionOnResize(),t.style.visibility="visible")})),this._thumbnail=t,this.appendChild(t)}}},videoWidth:{get:function(){return this._videoInfo?this._videoInfo.displayWidth:0}},videoHeight:{get:function(){return this._videoInfo?this._videoInfo.displayHeight:0}},ogvjsVideoFrameRate:{get:function(){return this._videoInfo?0==this._videoInfo.fps?this._totalFrameCount/(this._totalFrameTime/1e3):this._videoInfo.fps:0}},ogvjsAudioChannels:{get:function(){return this._audioInfo?this._audioInfo.channels:0}},ogvjsAudioSampleRate:{get:function(){return this._audioInfo?this._audioInfo.rate:0}},width:{get:function(){return this._width},set:function(e){this._width=parseInt(e,10),this.style.width=this._width+"px",OGVPlayer.updatePositionOnResize()}},height:{get:function(){return this._height},set:function(e){this._height=parseInt(e,10),this.style.height=this._height+"px",OGVPlayer.updatePositionOnResize()}},autoplay:{get:function(){return!1},set:function(e){}},controls:{get:function(){return!1},set:function(e){}},loop:{get:function(){return!1},set:function(e){}},crossOrigin:{get:function(){return null},set:function(e){}},currentSrc:{get:function(){return this._currentSrc}},defaultMuted:{get:function(){return!1}},defaultPlaybackRate:{get:function(){return 1}},error:{get:function(){return this._state===R?this._mediaError?this._mediaError:new p.default("unknown error occurred in media procesing"):null}},preload:{get:function(){return this.getAttribute("preload")||""},set:function(e){this.setAttribute("preload",e)}},readyState:{get:function(){return this._stream&&this._codec&&this._codec.loadedMetadata?OGVPlayer.HAVE_ENOUGH_DATA:OGVPlayer.HAVE_NOTHING}},networkState:{get:function(){return this._stream?this._stream.waiting?OGVPlayer.NETWORK_LOADING:OGVPlayer.NETWORK_IDLE:this.readyState==OGVPlayer.HAVE_NOTHING?OGVPlayer.NETWORK_EMPTY:OGVPlayer.NETWORK_NO_SOURCE}},playbackRate:{get:function(){return this._playbackRate},set:function(e){var t=Number(e)||1;this._audioFeeder?this._audioFeeder.tempo=t:this._paused||(this._initialPlaybackOffset=this._getPlaybackTime(),this._initialPlaybackPosition=t*d()/1e3),this._playbackRate=t,this._fireEventAsync("ratechange")}},played:{get:function(){return new g.default([[0,this.currentTime]])}},volume:{get:function(){return this._volume},set:function(e){this._volume=+e,this._audioFeeder&&(this._audioFeeder.volume=this._volume),this._fireEventAsync("volumechange")}}}),this.onframecallback=null,this.onloadstate=null,this.onprogress=null,this.onsuspend=null,this.onabort=null,this.onemptied=null,this.onstalled=null,this.onloadedmetadata=null,this.onloadeddata=null,this.oncanplay=null,this.oncanplaythrough=null,this.onplaying=null,this.onwaiting=null,this.onseeking=null,this.onseeked=null,this.onended=null,this.ondurationchange=null,this.ontimeupdate=null,this.onplay=null,this.onpause=null,this.onratechange=null,this.onresize=null,this.onvolumechange=null,this.onaudiofeedercreated=null}_time(e){var t=d();e();var i=d()-t;return this._lastFrameDecodeTime+=i,i}_log(e){var t=this._options;if(t.debug){var i=d()-this._startTime;t.debugFilter&&!e.match(t.debugFilter)||console.log("["+Math.round(10*i)/10+"ms] "+e)}}_fireEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._log("fireEvent "+e);var i,s="function"==typeof Event;for(var d in s?i=new CustomEvent(e):(i=document.createEvent("Event")).initEvent(e,!1,!1),t)t.hasOwnProperty(d)&&(i[d]=t[d]);var h=this.dispatchEvent(i);!s&&"resize"===e&&this.onresize&&h&&this.onresize.call(this,i)}_fireEventAsync(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._log("fireEventAsync "+e),y((()=>{this._fireEvent(e,t)}))}static initSharedAudioContext(){c.default.initSharedAudioContext()}_initAudioFeeder(){var e=this._options,t={bufferSize:8192};if(e.audioContext&&(t.audioContext=e.audioContext),e.audioDestination&&(t.output=e.audioDestination),e.audioBackendFactory&&(t.backendFactory=e.audioBackendFactory),this._video&&!t.output){t.audioContext||(t.audioContext=c.default.initSharedAudioContext());var i=t.audioContext.createMediaStreamDestination();this._audioTrack=i.stream.getAudioTracks()[0],this._mediaStream.addTrack(this._audioTrack),navigator.userAgent.match(/WebKit/)&&(this._video.src=this._mediaStream),this._video.play(),t.output=i}var s=this._audioFeeder=new c.default(t);s.init(this._audioInfo.channels,this._audioInfo.rate),this.onaudiofeedercreated&&this.onaudiofeedercreated(this._audioFeeder),s.bufferThreshold=1,s.volume=this.volume,s.muted=this.muted,s.tempo=this.playbackRate,s.onbufferlow=()=>{this._log("onbufferlow"),this._stream&&(this._stream.buffering||this._stream.seeking)||this._pendingAudio||this._pingProcessing()},s.onstarved=()=>{this._dataEnded?this._log("onstarved: appear to have reached end of audio"):(this._log("onstarved: halting audio due to starvation"),this._stopPlayback(),this._prebufferingAudio=!0),this._isProcessing()||this._pingProcessing(0)}}_startPlayback(e){if(this._audioFeeder){this._audioFeeder.start();var t=this._audioFeeder.getPlaybackState();this._initialPlaybackPosition=t.playbackPosition}else this._initialPlaybackPosition=this._playbackRate*d()/1e3;void 0!==e&&(this._initialPlaybackOffset=e),this._prebufferingAudio=!1,this._log("continuing at "+this._initialPlaybackPosition+", "+this._initialPlaybackOffset)}_stopPlayback(){this._initialPlaybackOffset=this._getPlaybackTime(),this._log("pausing at "+this._initialPlaybackOffset),this._audioFeeder&&this._audioFeeder.stop()}_getPlaybackTime(e){return this._prebufferingAudio||this._paused?this._initialPlaybackOffset:(this._audioFeeder?(e=e||this._audioFeeder.getPlaybackState()).playbackPosition:this._playbackRate*d()/1e3)-this._initialPlaybackPosition+this._initialPlaybackOffset}_stopVideo(){this._log("STOPPING"),this._state=T,this._seekState=O,this._started=!1,this._ended=!1,this._frameEndTimestamp=0,this._audioEndTimestamp=0,this._lastFrameDecodeTime=0,this._prebufferingAudio=!1,this._actionQueue.splice(0,this._actionQueue.length),this._stream&&(this._stream.abort(),this._stream=null,this._streamEnded=!1),this._codec&&(this._codec.close(),this._codec=null,this._pendingFrame=0,this._pendingAudio=0,this._dataEnded=!1),this._videoInfo=null,this._audioInfo=null,this._audioFeeder&&(this._audioFeeder.close(),this._audioFeeder=null),this._nextProcessingTimer&&(clearTimeout(this._nextProcessingTimer),this._nextProcessingTimer=null),this._nextFrameTimer&&(clearTimeout(this._nextFrameTimer),this._nextFrameTimer=null),this._frameSink&&(this._frameSink.clear(),this._frameSink=null),this._decodedFrames&&(this._decodedFrames=[]),this._pendingFrames&&(this._pendingFrames=[]),this._initialSeekTime=0,this._initialPlaybackPosition=0,this._initialPlaybackOffset=0,this._duration=null}_doFrameComplete(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._startedPlaybackInDocument&&!document.body.contains(this)&&y((()=>{this.stop()}));var t=d(),i=t-this._lastFrameTimestamp,s=this._actualPerFrameTime-this._targetPerFrameTime;this._totalJitter+=Math.abs(s),this._playTime+=i;var h={cpuTime:this._lastFrameDecodeTime,drawingTime:this._drawingTime-this._lastFrameDrawingTime,bufferTime:this._bufferTime-this._lastFrameBufferTime,proxyTime:this._proxyTime-this._lastFrameProxyTime,demuxerTime:0,videoTime:0,audioTime:0,clockTime:this._actualPerFrameTime,late:e.dropped,dropped:e.dropped};function n(e){return Math.round(10*e)/10}this._codec&&(h.demuxerTime=this._codec.demuxerCpuTime-this._lastFrameDemuxerCpuTime,h.videoTime+=this._currentVideoCpuTime-this._lastFrameVideoCpuTime,h.audioTime+=this._codec.audioCpuTime-this._lastFrameAudioCpuTime),h.cpuTime+=h.demuxerTime,this._lastFrameDecodeTime=0,this._lastFrameTimestamp=t,this._codec?(this._lastFrameVideoCpuTime=this._currentVideoCpuTime,this._lastFrameAudioCpuTime=this._codec.audioCpuTime,this._lastFrameDemuxerCpuTime=this._codec.demuxerCpuTime):(this._lastFrameVideoCpuTime=0,this._lastFrameAudioCpuTime=0,this._lastFrameDemuxerCpuTime=0),this._lastFrameDrawingTime=this._drawingTime,this._lastFrameBufferTime=this._bufferTime,this._lastFrameProxyTime=this._proxyTime,this._log("drew frame "+e.frameEndTimestamp+": clock time "+n(i)+" (jitter "+n(s)+") cpu: "+n(h.cpuTime)+" (mux: "+n(h.demuxerTime)+" buf: "+n(h.bufferTime)+" draw: "+n(h.drawingTime)+" proxy: "+n(h.proxyTime)+") vid: "+n(h.videoTime)+" aud: "+n(h.audioTime)),this._fireEventAsync("framecallback",h),(!this._lastTimeUpdate||t-this._lastTimeUpdate>=this._timeUpdateInterval)&&(this._lastTimeUpdate=t,this._fireEventAsync("timeupdate")),this._codec&&e.yCbCrBuffer&&this._codec.recycleFrame(e.yCbCrBuffer)}_seekStream(e){this._stream.seeking&&this._stream.abort(),this._stream.buffering&&this._stream.abort(),this._streamEnded=!1,this._dataEnded=!1,this._ended=!1,this._stream.seek(e).then((()=>{this._readBytesAndWait()})).catch((e=>{this._onStreamError(e)}))}_onStreamError(e){"AbortError"===e.name?this._log("i/o promise canceled; ignoring"):(this._log("i/o error: "+e),this._mediaError=new p.default(p.default.MEDIA_ERR_NETWORK,String(e)),this._state=R,this._stopPlayback())}_seek(e,t){if(this._log("requested seek to "+e+", mode "+t),this.readyState==this.HAVE_NOTHING)return this._log("not yet loaded; saving seek position for later"),void(this._initialSeekTime=e);if(this._stream&&!this._stream.seekable)throw new Error("Cannot seek a non-seekable stream");if(this._codec&&!this._codec.seekable)throw new Error("Cannot seek in a non-seekable file");var prepForSeek=i=>{this._stream&&this._stream.buffering&&this._stream.abort(),this._stream&&this._stream.seeking&&this._stream.abort(),this._actionQueue.splice(0,this._actionQueue.length),this._stopPlayback(),this._prebufferingAudio=!1,this._audioFeeder&&this._audioFeeder.flush(),this._state=A,this._seekTargetTime=e,this._seekMode=t,this._codec?this._codec.flush(i):i()};prepForSeek((()=>{this._isProcessing()||this._pingProcessing(0)})),this._actionQueue.push((()=>{prepForSeek((()=>{this._doSeek(e)}))}))}_doSeek(e){this._streamEnded=!1,this._dataEnded=!1,this._ended=!1,this._state=A,this._seekTargetTime=e,this._lastSeekPosition=-1,this._decodedFrames=[],this._pendingFrames=[],this._pendingFrame=0,this._pendingAudio=0,this._didSeek=!1,this._codec.seekToKeypoint(e,(t=>{if(t)return this._seekState=C,this._fireEventAsync("seeking"),this._didSeek?void 0:void this._pingProcessing();this._codec.getKeypointOffset(e,(e=>{e>0?(this._seekState=C,this._seekStream(e)):(this._seekState=F,this._startBisection(this._seekTargetTime)),this._fireEventAsync("seeking")}))}))}_startBisection(e){var t=Math.max(0,this._stream.length-65536);this._bisectTargetTime=e,this._seekBisector=new f.default({start:0,end:t,process:(e,t,i)=>i!=this._lastSeekPosition&&(this._lastSeekPosition=i,this._codec.flush((()=>{this._seekStream(i)})),!0)}),this._seekBisector.start()}_continueSeekedPlayback(){this._seekState=O,this._state=E,this._frameEndTimestamp=this._codec.frameTimestamp,this._audioEndTimestamp=this._codec.audioTimestamp,this._codec.hasAudio?this._seekTargetTime=this._codec.audioTimestamp:this._seekTargetTime=this._codec.frameTimestamp,this._initialPlaybackOffset=this._seekTargetTime;var finishedSeeking=()=>{this._lastTimeUpdate=this._seekTargetTime,this._fireEventAsync("timeupdate"),this._fireEventAsync("seeked"),this._isProcessing()||this._pingProcessing()};if(this._codec.hasVideo&&this._decodedFrames.length){var e=this._decodedFrames.shift();this._drawFrame(e.yCbCrBuffer),finishedSeeking()}else{if(this._codec.hasVideo&&this._codec.frameReady)return this._codec.decodeFrame((e=>{e&&this._drawFrame(this._codec.frameBuffer),finishedSeeking()})),void this._codec.sync();finishedSeeking()}}_drawFrame(e){this._thumbnail&&(this.removeChild(this._thumbnail),this._thumbnail=null),this._frameSink.drawFrame(e),this._video&&(this._canvasStream||(this._canvasStream=this._canvas.captureStream(0),this._videoTrack=this._canvasStream.getVideoTracks()[0],this._mediaStream.addTrack(this._videoTrack),navigator.userAgent.match(/WebKit/)&&(this._video.src=this._mediaStream,this._video.play())),this._videoTrack&&this._videoTrack.requestFrame?this._videoTrack.requestFrame():this._canvasStream&&this._canvasStream.requestFrame&&this._canvasStream.requestFrame())}_doProcessLinearSeeking(){var e;if(e=this._codec.hasVideo?this._targetPerFrameTime/1e3:1/256,this._codec.hasVideo){if(this._pendingFrame)return;if(!this._codec.frameReady)return void this._codec.process((e=>{e?this._pingProcessing():this._streamEnded?(this._log("stream ended during linear seeking on video"),this._dataEnded=!0,this._continueSeekedPlayback()):this._readBytesAndWait()}));if(this._seekMode===D&&this._codec.keyframeTimestamp==this._codec.frameTimestamp)return void this._continueSeekedPlayback();if(this._codec.frameTimestamp<=this._seekTargetTime){var t=this._codec.frameTimestamp;return this._pendingFrame++,this._pendingFrames.push({frameEndTimestamp:t}),this._decodedFrames.splice(0,this._decodedFrames.length),this._codec.decodeFrame((e=>{this._pendingFrame--,this._pendingFrames.shift(),this._decodedFrames.push({yCbCrBuffer:this._codec.frameBuffer,videoCpuTime:this._codec.videoCpuTime,frameEndTimestamp:t}),this._pingProcessing()})),void this._codec.sync()}if(!this._codec.hasAudio)return void this._continueSeekedPlayback()}if(this._codec.hasAudio){if(this._pendingAudio)return;return this._codec.audioReady?this._codec.audioTimestamp+e<this._seekTargetTime?void this._codec.decodeAudio((()=>{this._pingProcessing()})):void this._continueSeekedPlayback():void this._codec.process((e=>{e?this._pingProcessing():this._streamEnded?(this._log("stream ended during linear seeking on audio"),this._dataEnded=!0,this._continueSeekedPlayback()):this._readBytesAndWait()}))}}_doProcessBisectionSeek(){var e,t;if(this._codec.hasVideo)t=this._codec.frameTimestamp,e=this._targetPerFrameTime/1e3;else{if(!this._codec.hasAudio)throw new Error("Invalid seek state; no audio or video track available");t=this._codec.audioTimestamp,e=1/256}t<0?this._codec.process((e=>{if(e)this._pingProcessing();else if(this._streamEnded){if(this._log("stream ended during bisection seek"),!this._seekBisector.right())throw this._log("failed going back"),new Error("not sure what to do")}else this._readBytesAndWait()})):t-e/2>this._bisectTargetTime?this._seekBisector.left()||(this._log("close enough (left)"),this._seekTargetTime=t,this._continueSeekedPlayback()):t+e/2<this._bisectTargetTime?this._seekBisector.right()||(this._log("close enough (right)"),this._seekState=C,this._pingProcessing()):this._seekState==F&&this._codec.hasVideo&&this._codec.keyframeTimestamp<this._codec.frameTimestamp?(this._log("finding the keypoint now"),this._seekState=S,this._startBisection(this._codec.keyframeTimestamp)):(this._log("straight seeking now"),this._seekState=C,this._pingProcessing())}_setupVideo(){this._videoInfo.fps>0?this._targetPerFrameTime=1e3/this._videoInfo.fps:this._targetPerFrameTime=16.667,this._canvas.width=this._videoInfo.displayWidth,this._canvas.height=this._videoInfo.displayHeight,OGVPlayer.styleManager.appendRule("."+this._instanceId,{width:this._videoInfo.displayWidth+"px",height:this._videoInfo.displayHeight+"px"}),OGVPlayer.updatePositionOnResize();var e={};void 0!==this._options.webGL&&(e.webGL=this._options.webGL),this._options.forceWebGL&&(e.webGL="required"),this._frameSink=h.default.attach(this._canvas,e)}_doProcessing(){if(this._didSeek&&(this._didSeek=!1),this._nextProcessingTimer=null,this._isProcessing(),this._depth>0)throw new Error("REENTRANCY FAIL: doProcessing recursing unexpectedly");var e=0;do{if(this._needProcessing=!1,this._depth++,this._doProcessingLoop(),this._depth--,this._needProcessing&&this._isProcessing())throw new Error("REENTRANCY FAIL: waiting on input or codec but asked to keep processing");++e>500&&(this._log("stuck in processing loop; breaking with timer"),this._needProcessing=0,this._pingProcessing(0))}while(this._needProcessing)}_doProcessingLoop(){if(this._actionQueue.length)this._actionQueue.shift()();else if(this._state==T)this._doProcessInitial();else if(this._state==k)this._doProcessSeekingEnd();else if(this._state==P)this._doProcessLoaded();else if(this._state==w)this._doProcessPreload();else if(this._state==E)this._doProcessReady();else if(this._state==A)this._doProcessSeeking();else if(this._state==x)this._doProcessPlay();else{if(this._state!=R)throw new Error("Unexpected OGVPlayer state "+this._state);this._doProcessError()}}_doProcessInitial(){if(this._codec.loadedMetadata){if(!this._codec.hasVideo&&!this._codec.hasAudio)throw new Error("No audio or video found, something is wrong");this._codec.hasAudio&&(this._audioInfo=this._codec.audioFormat),this._codec.hasVideo&&(this._videoInfo=this._codec.videoFormat,this._setupVideo()),isNaN(this._codec.duration)||(this._duration=this._codec.duration),null===this._duration&&this._stream.seekable&&"video/ogg"==this._detectedType?(this._state=k,this._lastSeenTimestamp=-1,this._codec.flush((()=>{this._seekStream(Math.max(0,this._stream.length-131072))}))):(this._state=P,this._pingProcessing())}else this._codec.process((e=>{if(e)this._pingProcessing();else{if(this._streamEnded)throw new Error("end of file before headers found");this._log("reading more cause we are out of data"),this._readBytesAndWait()}}))}_doProcessSeekingEnd(){this._codec.frameReady?(this._log("saw frame with "+this._codec.frameTimestamp),this._lastSeenTimestamp=Math.max(this._lastSeenTimestamp,this._codec.frameTimestamp),this._codec.discardFrame((()=>{this._pingProcessing()}))):this._codec.audioReady?(this._log("saw audio with "+this._codec.audioTimestamp),this._lastSeenTimestamp=Math.max(this._lastSeenTimestamp,this._codec.audioTimestamp),this._codec.discardAudio((()=>{this._pingProcessing()}))):this._codec.process((e=>{e?this._pingProcessing():this._stream.eof?(this._log("seek-duration: we are at the end: "+this._lastSeenTimestamp),this._lastSeenTimestamp>0&&(this._duration=this._lastSeenTimestamp),this._state=P,this._codec.flush((()=>{this._streamEnded=!1,this._dataEnded=!1,this._seekStream(0)}))):this._readBytesAndWait()}))}_doProcessLoaded(){this._state=w,this._fireEventAsync("loadedmetadata"),this._fireEventAsync("durationchange"),this._codec.hasVideo&&this._fireEventAsync("resize"),this._pingProcessing(0)}_doProcessPreload(){!this._codec.frameReady&&this._codec.hasVideo||!this._codec.audioReady&&this._codec.hasAudio?this._codec.process((e=>{e?this._pingProcessing():this._streamEnded?this._ended=!0:this._readBytesAndWait()})):(this._state=E,this._fireEventAsync("loadeddata"),this._pingProcessing())}_doProcessReady(){if(this._log("initial seek to "+this._initialSeekTime),this._initialSeekTime>0){var e=this._initialSeekTime;this._initialSeekTime=0,this._log("initial seek to "+e),this._doSeek(e)}else if(this._paused)this._log("paused while in ready");else{var finishStartPlaying=()=>{this._log("finishStartPlaying"),this._state=x,this._lastFrameTimestamp=d(),this._codec.hasAudio&&this._audioFeeder?this._prebufferingAudio=!0:this._startPlayback(),this._pingProcessing(0),this._fireEventAsync("play"),this._fireEventAsync("playing")};!this._codec.hasAudio||this._audioFeeder||this._muted?finishStartPlaying():(this._initAudioFeeder(),this._audioFeeder.waitUntilReady(finishStartPlaying))}}_doProcessSeeking(){if(this._seekState==O)throw new Error("seeking in invalid state (not seeking?)");if(this._seekState==F)this._doProcessBisectionSeek();else if(this._seekState==S)this._doProcessBisectionSeek();else{if(this._seekState!=C)throw new Error("Invalid seek state "+this._seekState);this._doProcessLinearSeeking()}}_doProcessPlay(){var e=this._codec;if(this._paused)this._log("paused during playback; stopping loop");else if((!e.hasAudio||e.audioReady||this._pendingAudio||this._dataEnded)&&(!e.hasVideo||e.frameReady||this._pendingFrame||this._decodedFrames.length||this._dataEnded)){var t,i,s,d=null,h=0,u=!1,c=0;if(e.hasAudio&&this._audioFeeder?(d=this._audioFeeder.getPlaybackState(),h=this._getPlaybackTime(d),u=this._dataEnded&&0==this._audioFeeder.durationBuffered,this._prebufferingAudio&&(this._audioFeeder.durationBuffered>=2*this._audioFeeder.bufferThreshold&&(!e.hasVideo||this._decodedFrames.length>=this._framePipelineDepth)||this._dataEnded)&&(this._log("prebuffering audio done; buffered to "+this._audioFeeder.durationBuffered),this._startPlayback(h),this._prebufferingAudio=!1),d.dropped!=this._droppedAudio&&this._log("dropped "+(d.dropped-this._droppedAudio)),d.delayed!=this._delayedAudio&&this._log("delayed "+(d.delayed-this._delayedAudio)),this._droppedAudio=d.dropped,this._delayedAudio=d.delayed,(t=this._audioFeeder.durationBuffered<=2*this._audioFeeder.bufferThreshold)&&(this._codec.audioReady?this._pendingAudio>=this._audioPipelineDepth&&(this._log("audio decode disabled: "+this._pendingAudio+" packets in flight"),t=!1):t=!1)):(h=this._getPlaybackTime(),t=this._codec.audioReady&&this._audioEndTimestamp<h),this._codec.hasVideo){i=this._decodedFrames.length>0,s=this._pendingFrame+this._decodedFrames.length<this._framePipelineDepth+this._frameParallelism&&this._codec.frameReady,i&&(c=1e3*(this._decodedFrames[0].frameEndTimestamp-h),this._actualPerFrameTime=this._targetPerFrameTime-c);var l=this._targetPerFrameTime;if(this._prebufferingAudio)s&&this._log("decoding a frame during prebuffering"),i=!1;else if(i&&this._dataEnded&&u)this._log("audio timeline ended? ready to draw frame");else if(i&&-c>=l){for(var f=-1,_=0;_<this._decodedFrames.length-1;_++)this._decodedFrames[_].frameEndTimestamp<h&&(f=_-1);if(f>=0)for(;f-- >=0;){this._lateFrames++;var p=this._decodedFrames.shift();this._log("skipping already-decoded late frame at "+p.frameEndTimestamp),c=1e3*(p.frameEndTimestamp-h),this._frameEndTimestamp=p.frameEndTimestamp,this._actualPerFrameTime=this._targetPerFrameTime-c,this._framesProcessed++,p.dropped=!0,this._doFrameComplete(p)}var m=this._codec.nextKeyframeTimestamp,g=m-this._targetPerFrameTime/1e3*(this._framePipelineDepth+this._pendingFrame);if(m>=0&&m!=this._codec.frameTimestamp&&h>=g){this._log("skipping late frame at "+this._decodedFrames[0].frameEndTimestamp+" vs "+h+", expect to see keyframe at "+m);for(var v=0;v<this._decodedFrames.length;v++){var y=this._decodedFrames[v];this._lateFrames++,this._framesProcessed++,this._frameEndTimestamp=y.frameEndTimestamp,c=1e3*(y.frameEndTimestamp-h),this._actualPerFrameTime=this._targetPerFrameTime-c,y.dropped=!0,this._doFrameComplete(y)}this._decodedFrames=[];for(var b=0;b<this._pendingFrames.length;b++){var T=this._pendingFrames[b];this._lateFrames++,this._framesProcessed++,this._frameEndTimestamp=T.frameEndTimestamp,c=1e3*(T.frameEndTimestamp-h),this._actualPerFrameTime=this._targetPerFrameTime-c,T.dropped=!0,this._doFrameComplete(T)}for(this._pendingFrames=[],this._pendingFrame=0;this._codec.frameReady&&this._codec.frameTimestamp<m;){var k={frameEndTimestamp:this._codec.frameTimestamp,dropped:!0};c=1e3*(k.frameEndTimestamp-h),this._actualPerFrameTime=this._targetPerFrameTime-c,this._lateFrames++,this._codec.discardFrame((()=>{})),this._framesProcessed++,this._doFrameComplete(k)}return void(this._isProcessing()||this._pingProcessing())}}else i&&c<=4||(i=!1)}if(s){this._log("play loop: ready to decode frame; thread depth: "+this._pendingFrame+", have buffered: "+this._decodedFrames.length),0==this._videoInfo.fps&&this._codec.frameTimestamp-this._frameEndTimestamp>0&&(this._targetPerFrameTime=1e3*(this._codec.frameTimestamp-this._frameEndTimestamp)),this._totalFrameTime+=this._targetPerFrameTime,this._totalFrameCount++;var P=this._frameEndTimestamp=this._codec.frameTimestamp;this._pendingFrame++,this._pendingFrames.push({frameEndTimestamp:P});var w=this._pendingFrames,E=!1,x=this._time((()=>{this._codec.decodeFrame((e=>{w===this._pendingFrames?(this._log("play loop callback: decoded frame"),this._pendingFrame--,this._pendingFrames.shift(),e?this._decodedFrames.push({yCbCrBuffer:this._codec.frameBuffer,videoCpuTime:this._codec.videoCpuTime,frameEndTimestamp:P}):this._log("Bad video packet or something"),this._codec.process((()=>{this._isProcessing()||this._pingProcessing(E?void 0:0)}))):this._log("play loop callback after flush, discarding")}))}));this._pendingFrame&&(E=!0,this._proxyTime+=x,this._pingProcessing(),this._dataEnded&&this._codec.sync())}else if(t){this._log("play loop: ready for audio; depth: "+this._pendingAudio),this._pendingAudio++;var A=this._codec.audioTimestamp,R=this._time((()=>{this._codec.decodeAudio((e=>{if(this._pendingAudio--,this._log("play loop callback: decoded audio"),this._audioEndTimestamp=A,e){var t=this._codec.audioBuffer;if(t&&(this._bufferTime+=this._time((()=>{this._audioFeeder&&this._audioFeeder.bufferData(t)})),!this._codec.hasVideo)){this._framesProcessed++;var i={frameEndTimestamp:this._audioEndTimestamp};this._doFrameComplete(i)}}this._isProcessing()||this._pingProcessing()}))}));this._pendingAudio&&(this._proxyTime+=R,this._codec.audioReady?this._pingProcessing():this._doProcessPlayDemux())}else if(i){this._log("play loop: ready to draw frame"),this._nextFrameTimer&&(clearTimeout(this._nextFrameTimer),this._nextFrameTimer=null),this._thumbnail&&(this.removeChild(this._thumbnail),this._thumbnail=null);var O=this._decodedFrames.shift();this._currentVideoCpuTime=O.videoCpuTime,this._drawingTime+=this._time((()=>{this._drawFrame(O.yCbCrBuffer)})),this._framesProcessed++,this._doFrameComplete(O),this._pingProcessing()}else if(!this._decodedFrames.length||this._nextFrameTimer||this._prebufferingAudio)if(this._dataEnded&&!(this._pendingAudio||this._pendingFrame||this._decodedFrames.length)){this._log("play loop: playback reached end of data "+[this._pendingAudio,this._pendingFrame,this._decodedFrames.length]);var F=0;this._codec.hasAudio&&this._audioFeeder&&(F=1e3*this._audioFeeder.durationBuffered),F>0?(this._log("play loop: ending pending "+F+" ms"),this._pingProcessing(Math.max(0,F))):(this._log("play loop: ENDING NOW: playback time "+this._getPlaybackTime()+"; frameEndTimestamp: "+this._frameEndTimestamp),this._stopPlayback(),this._prebufferingAudio=!1,this._initialPlaybackOffset=Math.max(this._audioEndTimestamp,this._frameEndTimestamp),this._ended=!0,this._paused=!0,this._fireEventAsync("pause"),this._fireEventAsync("ended"))}else this._prebufferingAudio&&(e.hasVideo&&!e.frameReady||e.hasAudio&&!e.audioReady)?(this._log("play loop: prebuffering demuxing"),this._doProcessPlayDemux()):this._log("play loop: waiting on async/timers");else{var S=c;this._log("play loop: setting a timer for drawing "+S),this._nextFrameTimer=setTimeout((()=>{this._nextFrameTimer=null,this._pingProcessing()}),S)}}else this._log("play loop: demuxing"),this._doProcessPlayDemux()}_doProcessPlayDemux(){var e=this._codec.frameReady,t=this._codec.audioReady;this._codec.process((i=>{this._codec.frameReady&&!e||this._codec.audioReady&&!t?(this._log("demuxer has packets"),this._pingProcessing()):i?(this._log("demuxer processing to find more packets"),this._pingProcessing()):(this._log("demuxer ran out of data"),this._streamEnded?(this._log("demuxer reached end of data stream"),this._dataEnded=!0,this._pingProcessing()):(this._log("demuxer loading more data"),this._readBytesAndWait()))}))}_doProcessError(){}_isProcessing(){return this._stream&&(this._stream.buffering||this._stream.seeking)||this._codec&&this._codec.processing}_readBytesAndWait(){this._stream.buffering||this._stream.seeking?this._log("readBytesAndWait during i/o"):this._stream.read(32768).then((e=>{this._log("got input "+[e.byteLength]),e.byteLength&&this._actionQueue.push((()=>{this._codec.receiveInput(e,(()=>{this._pingProcessing()}))})),this._stream.eof&&(this._log("stream is at end!"),this._streamEnded=!0),this._isProcessing()||this._pingProcessing()})).catch((e=>{this._onStreamError(e)}))}_pingProcessing(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;this._stream&&this._stream.waiting?this._log("waiting on input"):(this._nextProcessingTimer&&(this._log("canceling old processing timer"),clearTimeout(this._nextProcessingTimer),this._nextProcessingTimer=null),e>-1/256?this._nextProcessingTimer=setTimeout((()=>{this._pingProcessing()}),e):this._depth?this._needProcessing=!0:this._doProcessing())}_startProcessingVideo(e){if(!this._started&&!this._codec){this._framesProcessed=0,this._bufferTime=0,this._drawingTime=0,this._proxyTime=0,this._started=!0,this._ended=!1;var t={base:this._options.base,worker:this._enableWorker,threading:this._enableThreading,simd:this._enableSIMD};this._detectedType&&(t.type=this._detectedType),this._codec=new v.default(t),this._lastVideoCpuTime=0,this._lastAudioCpuTime=0,this._lastDemuxerCpuTime=0,this._lastBufferTime=0,this._lastDrawingTime=0,this._lastProxyTime=0,this._lastFrameVideoCpuTime=0,this._lastFrameAudioCpuTime=0,this._lastFrameDemuxerCpuTime=0,this._lastFrameBufferTime=0,this._lastFrameProxyTime=0,this._lastFrameDrawingTime=0,this._currentVideoCpuTime=0,this._codec.onseek=e=>{this._didSeek=!0,this._stream&&this._seekStream(e)},this._codec.init((()=>{this._codec.receiveInput(e,(()=>{this._readBytesAndWait()}))}))}}_loadCodec(e){this._stream.read(1024).then((t=>{var i=new Uint8Array(t);i.length>4&&i[0]=="O".charCodeAt(0)&&i[1]=="g".charCodeAt(0)&&i[2]=="g".charCodeAt(0)&&i[3]=="S".charCodeAt(0)?this._detectedType="video/ogg":i.length>4&&26==i[0]&&69==i[1]&&223==i[2]&&163==i[3]?this._detectedType="video/webm":this._detectedType="video/ogg",e(t)}))}_prepForLoad(e){this._stopVideo();var doLoad=()=>{this._options.stream?this._stream=this._options.stream:this._stream=new u.default({url:this.src,cacheSize:16777216,progressive:!1}),this._stream.load().then((()=>{this._loading=!1,this._currentSrc=this.src,this._byteLength=this._stream.seekable?this._stream.length:0;var e=this._stream.headers["x-content-duration"];"string"==typeof e&&(this._duration=parseFloat(e)),this._loadCodec((e=>{this._startProcessingVideo(e)}))})).catch((e=>{this._onStreamError(e)}))};this._currentSrc="",this._loading=!0,this._actionQueue.push((()=>{e&&"none"===this.preload?this._loading=!1:doLoad()})),this._pingProcessing(0)}load(){this._prepForLoad()}canPlayType(e){var t=new m.default(e);function checkTypes(e){if(t.codecs){var i=0,s=0;return t.codecs.forEach((t=>{e.indexOf(t)>=0?i++:s++})),0===i||s>0?"":"probably"}return"maybe"}return"ogg"!==t.minor||"audio"!==t.major&&"video"!==t.major&&"application"!==t.major?"webm"!==t.minor||"audio"!==t.major&&"video"!==t.major?"":checkTypes(["vorbis","opus","vp8","vp9"]):checkTypes(["vorbis","opus","theora"])}play(){this._muted||this._options.audioContext||OGVPlayer.initSharedAudioContext(),this._paused&&(this._startedPlaybackInDocument=document.body.contains(this),this._paused=!1,this._state==A||(this._started&&this._codec&&this._codec.loadedMetadata?(this._ended&&this._stream&&this._byteLength?(this._log(".play() starting over after end"),this._seek(0)):this._log(".play() while already started"),this._state=E,this._isProcessing()||this._pingProcessing()):this._loading?this._log(".play() while loading"):(this._log(".play() before started"),this._stream||this.load()))),this._video&&this._video.paused&&this._video.play()}getPlaybackStats(){return{targetPerFrameTime:this._targetPerFrameTime,framesProcessed:this._framesProcessed,videoBytes:this._codec?this._codec.videoBytes:0,audioBytes:this._codec?this._codec.audioBytes:0,playTime:this._playTime,demuxingTime:this._codec?this._codec.demuxerCpuTime-this._lastDemuxerCpuTime:0,videoDecodingTime:this._codec?this._codec.videoCpuTime-this._lastVideoCpuTime:0,audioDecodingTime:this._codec?this._codec.audioCpuTime-this._lastAudioCpuTime:0,bufferTime:this._bufferTime-this._lastBufferTime,drawingTime:this._drawingTime-this._lastDrawingTime,proxyTime:this._proxyTime-this._lastProxyTime,droppedAudio:this._droppedAudio,delayedAudio:this._delayedAudio,jitter:this._totalJitter/this._framesProcessed,lateFrames:this._lateFrames}}resetPlaybackStats(){this._framesProcessed=0,this._playTime=0,this._codec&&(this._lastDemuxerCpuTime=this._codec.demuxerCpuTime,this._lastVideoCpuTime=this._codec.videoCpuTime,this._lastAudioCpuTime=this._codec.audioCpuTime,this._codec.videoBytes=0,this._codec.audioBytes=0),this._lastBufferTime=this._bufferTime,this._lastDrawingTime=this._drawingTime,this._lastProxyTime=this._proxyTime,this._totalJitter=0,this._totalFrameTime=0,this._totalFrameCount=0}getVideoFrameSink(){return this._frameSink}getCanvas(){return this._canvas}getVideo(){return this._video}pause(){this._paused||(this._nextProcessingTimer&&(clearTimeout(this._nextProcessingTimer),this._nextProcessingTimer=null),this._stopPlayback(),this._prebufferingAudio=!1,this._paused=!0,this._fireEvent("pause"))}stop(){this._stopVideo(),this._paused=!0}fastSeek(e){this._seek(+e,D)}}if((0,_.default)(OGVPlayer,b),OGVPlayer.instanceCount=0,OGVPlayer.styleManager=new function(){var e=document.createElement("style");e.type="text/css",e.textContent="ogvjs { display: inline-block; position: relative; -webkit-user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0); ",document.head.appendChild(e);var t=e.sheet;this.appendRule=function(e,i){var s=[];for(var d in i)i.hasOwnProperty(d)&&s.push(d+":"+i[d]);var h=e+"{"+s.join(";")+"}";t.insertRule(h,t.cssRules.length-1)}},OGVPlayer.supportsObjectFit="string"==typeof document.createElement("canvas").style.objectFit,OGVPlayer.supportsObjectFit&&navigator.userAgent.match(/iPhone|iPad|iPod Touch/)&&(OGVPlayer.supportsObjectFit=!1),OGVPlayer.supportsObjectFit&&navigator.userAgent.match(/Edge/)&&(OGVPlayer.supportsObjectFit=!1),OGVPlayer.supportsObjectFit)OGVPlayer.updatePositionOnResize=function(){};else{OGVPlayer.updatePositionOnResize=function(){function fixup(e,t,i){var s=e.offsetParent||e.parentNode,d=t/i;if(d>s.offsetWidth/s.offsetHeight){var h=s.offsetWidth/d,u=(s.offsetHeight-h)/2;e.style.width="100%",e.style.height=h+"px",e.style.marginLeft=0,e.style.marginRight=0,e.style.marginTop=u+"px",e.style.marginBottom=u+"px"}else{var c=s.offsetHeight*d,l=(s.offsetWidth-c)/2;e.style.width=c+"px",e.style.height="100%",e.style.marginLeft=l+"px",e.style.marginRight=l+"px",e.style.marginTop=0,e.style.marginBottom=0}}function queryOver(e,t){var i=document.querySelectorAll(e);Array.prototype.slice.call(i).forEach(t)}queryOver("ogvjs > canvas",(function(e){fixup(e,e.width,e.height)})),queryOver("ogvjs > img",(function(e){fixup(e,e.naturalWidth,e.naturalHeight)}))};var M=function(){y(OGVPlayer.updatePositionOnResize)};window.addEventListener("resize",OGVPlayer.updatePositionOnResize),window.addEventListener("orientationchange",OGVPlayer.updatePositionOnResize),document.addEventListener("fullscreenchange",M),document.addEventListener("mozfullscreenchange",M),document.addEventListener("webkitfullscreenchange",M),document.addEventListener("MSFullscreenChange",M)}var V=OGVPlayer;t.default=V},580:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=function(e){return class{constructor(t,i,s){for(var d in s=s||{},this.worker=t,this.transferables=function(){var e=new ArrayBuffer(1024),i=new Uint8Array(e);try{return t.postMessage({action:"transferTest",bytes:i},[e]),!e.byteLength}catch(e){return!1}}(),e)e.hasOwnProperty(d)&&(this[d]=e[d]);this.processingQueue=0,Object.defineProperty(this,"processing",{get:function(){return this.processingQueue>0}}),this.messageCount=0,this.pendingCallbacks={},this.worker.addEventListener("message",(e=>{this.handleMessage(e)})),this.proxy("construct",[i,s],(()=>{}))}proxy(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];if(!this.worker)throw'Tried to call "'+e+'" method on closed proxy object';var d="callback-"+ ++this.messageCount+"-"+e;i&&(this.pendingCallbacks[d]=i);var h={action:e,callbackId:d,args:t||[]};this.processingQueue++,this.transferables?this.worker.postMessage(h,s):this.worker.postMessage(h)}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.processingQueue=0,this.pendingCallbacks={})}handleMessage(e){if(this.processingQueue--,"callback"===e.data.action){var t=e.data,i=t.callbackId,s=t.args,d=this.pendingCallbacks[i];if(t.props)for(var h in t.props)t.props.hasOwnProperty(h)&&(this[h]=t.props[h]);d&&(delete this.pendingCallbacks[i],d.apply(this,s))}}}}},168:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{constructor(e){this._ranges=e,this.length=e.length}start(e){if(e<0||e>this.length||e!==(0|e))throw new RangeError("Invalid index");return this._ranges[e][0]}end(e){if(e<0||e>this.length||e!==(0|e))throw new RangeError("Invalid index");return this._ranges[e][1]}}},625:(e,t,i)=>{var s=i(318);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var d=s(i(964));t.default=class{constructor(e){return this.options=e||{},this.demuxer=null,this.videoDecoder=null,this.audioDecoder=null,this.flushIter=0,this.loadedMetadata=!1,this.processing=!1,Object.defineProperties(this,{duration:{get:function(){return this.loadedMetadata?this.demuxer.duration:NaN}},hasAudio:{get:function(){return this.loadedMetadata&&!!this.audioDecoder}},audioReady:{get:function(){return this.hasAudio&&this.demuxer.audioReady}},audioTimestamp:{get:function(){return this.demuxer.audioTimestamp}},audioFormat:{get:function(){return this.hasAudio?this.audioDecoder.audioFormat:null}},audioBuffer:{get:function(){return this.hasAudio?this.audioDecoder.audioBuffer:null}},hasVideo:{get:function(){return this.loadedMetadata&&!!this.videoDecoder}},frameReady:{get:function(){return this.hasVideo&&this.demuxer.frameReady}},frameTimestamp:{get:function(){return this.demuxer.frameTimestamp}},keyframeTimestamp:{get:function(){return this.demuxer.keyframeTimestamp}},nextKeyframeTimestamp:{get:function(){return this.demuxer.nextKeyframeTimestamp}},videoFormat:{get:function(){return this.hasVideo?this.videoDecoder.videoFormat:null}},frameBuffer:{get:function(){return this.hasVideo?this.videoDecoder.frameBuffer:null}},seekable:{get:function(){return this.demuxer.seekable}},demuxerCpuTime:{get:function(){return this.demuxer?this.demuxer.cpuTime:0}},audioCpuTime:{get:function(){return this.audioDecoder?this.audioDecoder.cpuTime:0}},videoCpuTime:{get:function(){return this.videoDecoder?this.videoDecoder.cpuTime:0}}}),this.loadedDemuxerMetadata=!1,this.loadedAudioMetadata=!1,this.loadedVideoMetadata=!1,this.loadedAllMetadata=!1,this.onseek=null,this.videoBytes=0,this.audioBytes=0,this}flushSafe(e){var t=this.flushIter;return i=>{this.flushIter<=t&&e(i)}}init(e){var t;this.processing=!0,t="video/webm"===this.options.type||"audio/webm"===this.options.type?"OGVDemuxerWebMW":"OGVDemuxerOggW",d.default.loadClass(t,(t=>{t().then((t=>{this.demuxer=t,t.onseek=e=>{this.onseek&&this.onseek(e)},t.init((()=>{this.processing=!1,e()}))}))}))}close(){this.demuxer&&(this.demuxer.close(),this.demuxer=null),this.videoDecoder&&(this.videoDecoder.close(),this.videoDecoder=null),this.audioDecoder&&(this.audioDecoder.close(),this.audioDecoder=null)}receiveInput(e,t){this.demuxer.receiveInput(e,t)}process(e){if(this.processing)throw new Error("reentrancy fail on OGVWrapperCodec.process");this.processing=!0;var finish=t=>{this.processing=!1,e(t)},doProcessData=()=>{this.demuxer.process(finish)};this.demuxer.loadedMetadata&&!this.loadedDemuxerMetadata?this.loadAudioCodec((()=>{this.loadVideoCodec((()=>{this.loadedDemuxerMetadata=!0,this.loadedAudioMetadata=!this.audioDecoder,this.loadedVideoMetadata=!this.videoDecoder,this.loadedAllMetadata=this.loadedAudioMetadata&&this.loadedVideoMetadata,finish(!0)}))})):this.loadedDemuxerMetadata&&!this.loadedAudioMetadata?this.audioDecoder.loadedMetadata?(this.loadedAudioMetadata=!0,this.loadedAllMetadata=this.loadedAudioMetadata&&this.loadedVideoMetadata,finish(!0)):this.demuxer.audioReady?this.demuxer.dequeueAudioPacket(((e,t)=>{this.audioBytes+=e.byteLength,this.audioDecoder.processHeader(e,(e=>{finish(!0)}))})):doProcessData():this.loadedAudioMetadata&&!this.loadedVideoMetadata?this.videoDecoder.loadedMetadata?(this.loadedVideoMetadata=!0,this.loadedAllMetadata=this.loadedAudioMetadata&&this.loadedVideoMetadata,finish(!0)):this.demuxer.frameReady?(this.processing=!0,this.demuxer.dequeueVideoPacket((e=>{this.videoBytes+=e.byteLength,this.videoDecoder.processHeader(e,(()=>{finish(!0)}))}))):doProcessData():this.loadedVideoMetadata&&!this.loadedMetadata&&this.loadedAllMetadata?(this.loadedMetadata=!0,finish(!0)):!this.loadedMetadata||this.hasAudio&&!this.demuxer.audioReady||this.hasVideo&&!this.demuxer.frameReady?doProcessData():finish(!0)}decodeFrame(e){var t=this.flushSafe(e),i=this.frameTimestamp,s=this.keyframeTimestamp;this.demuxer.dequeueVideoPacket((e=>{this.videoBytes+=e.byteLength,this.videoDecoder.processFrame(e,(e=>{var d=this.videoDecoder.frameBuffer;d&&(d.timestamp=i,d.keyframeTimestamp=s),t(e)}))}))}decodeAudio(e){var t=this.flushSafe(e);this.demuxer.dequeueAudioPacket(((e,i)=>{this.audioBytes+=e.byteLength,this.audioDecoder.processAudio(e,(e=>{if(i){var s=this.audioDecoder.audioBuffer,d=[];for(var h of s){var u=Math.round(i*this.audioFormat.rate/1e9);u>0?d.push(h.subarray(0,h.length-Math.min(u,h.length))):d.push(h.subarray(Math.min(Math.abs(u),h.length),h.length))}this.audioDecoder.audioBuffer=d}return t(e)}))}))}discardFrame(e){this.demuxer.dequeueVideoPacket((t=>{this.videoBytes+=t.byteLength,e()}))}discardAudio(e){this.demuxer.dequeueAudioPacket(((t,i)=>{this.audioBytes+=t.byteLength,e()}))}flush(e){this.flushIter++,this.demuxer.flush(e)}sync(){this.videoDecoder&&this.videoDecoder.sync()}recycleFrame(e){this.videoDecoder&&this.videoDecoder.recycleFrame(e)}getKeypointOffset(e,t){this.demuxer.getKeypointOffset(e,t)}seekToKeypoint(e,t){this.demuxer.seekToKeypoint(e,this.flushSafe(t))}loadAudioCodec(e){if(this.demuxer.audioCodec){var t={vorbis:"OGVDecoderAudioVorbisW",opus:"OGVDecoderAudioOpusW"}[this.demuxer.audioCodec];this.processing=!0,d.default.loadClass(t,(t=>{var i={};this.demuxer.audioFormat&&(i.audioFormat=this.demuxer.audioFormat),t(i).then((t=>{this.audioDecoder=t,t.init((()=>{this.loadedAudioMetadata=t.loadedMetadata,this.processing=!1,e()}))}))}),{worker:this.options.worker})}else e()}loadVideoCodec(e){if(this.demuxer.videoCodec){var t=!!this.options.simd,i=!!this.options.threading,s={theora:"OGVDecoderVideoTheoraW",vp8:i?"OGVDecoderVideoVP8MTW":"OGVDecoderVideoVP8W",vp9:i?t?"OGVDecoderVideoVP9SIMDMTW":"OGVDecoderVideoVP9MTW":t?"OGVDecoderVideoVP9SIMDW":"OGVDecoderVideoVP9W",av1:i?t?"OGVDecoderVideoAV1SIMDMTW":"OGVDecoderVideoAV1MTW":t?"OGVDecoderVideoAV1SIMDW":"OGVDecoderVideoAV1W"}[this.demuxer.videoCodec];this.processing=!0,d.default.loadClass(s,(t=>{var s={};this.demuxer.videoFormat&&(s.videoFormat=this.demuxer.videoFormat),i&&delete window.ENVIRONMENT_IS_PTHREAD,t(s).then((t=>{this.videoDecoder=t,t.init((()=>{this.loadedVideoMetadata=t.loadedMetadata,this.processing=!1,e()}))}))}),{worker:this.options.worker&&!this.options.threading})}else e()}}},539:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=new class{constructor(){this.tested=!1,this.testResult=void 0}wasmSupported(){if(!this.tested){try{"object"==typeof WebAssembly?this.testResult=function(){var e=new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,127,1,127,3,2,1,0,5,3,1,0,1,7,8,1,4,116,101,115,116,0,0,10,16,1,14,0,32,0,65,1,54,2,0,32,0,40,2,0,11]),t=new WebAssembly.Module(e);return 0!==new WebAssembly.Instance(t,{}).exports.test(4)}():this.testResult=!1}catch(e){console.log("Exception while testing WebAssembly",e),this.testResult=!1}this.tested=!0}return this.testResult}};t.default=i},309:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])}},431:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}(),d=function get(e,t,i){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(void 0===s){var d=Object.getPrototypeOf(e);return null===d?void 0:get(d,t,i)}if("value"in s)return s.value;var h=s.get;return void 0!==h?h.call(i):void 0};function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var h=i(828),u="arraybuffer",c=function(e){function ArrayBufferBackend(){return _classCallCheck(this,ArrayBufferBackend),_possibleConstructorReturn(this,(ArrayBufferBackend.__proto__||Object.getPrototypeOf(ArrayBufferBackend)).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(ArrayBufferBackend,e),s(ArrayBufferBackend,[{key:"initXHR",value:function(){d(ArrayBufferBackend.prototype.__proto__||Object.getPrototypeOf(ArrayBufferBackend.prototype),"initXHR",this).call(this),this.xhr.responseType=u}},{key:"onXHRProgress",value:function(){}},{key:"onXHRLoad",value:function(){var e=this.xhr.response;this.bytesRead+=e.byteLength,this.emit("buffer",e),d(ArrayBufferBackend.prototype.__proto__||Object.getPrototypeOf(ArrayBufferBackend.prototype),"onXHRLoad",this).call(this)}}]),ArrayBufferBackend}(h);c.supported=function(){try{var e=new XMLHttpRequest;return e.responseType=u,e.responseType===u}catch(e){return!1}},e.exports=c},306:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}();function getXHRRangeMatches(e){var t=e.getResponseHeader("Content-Range");return t&&t.match(/^bytes (\d+)-(\d+)\/(\d+)/)}var d=function(e){function Backend(e){var t=e.url,i=e.offset,s=e.length,d=e.cachever,h=void 0===d?0:d;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,Backend);var u=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(Backend.__proto__||Object.getPrototypeOf(Backend)).call(this));return u.url=t,u.offset=i,u.length=s,u.cachever=h,u.loaded=!1,u.seekable=!1,u.headers={},u.eof=!1,u.bytesRead=0,u.xhr=new XMLHttpRequest,u}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(Backend,e),s(Backend,[{key:"load",value:function(){var e=this;return new Promise((function(t,i){var s=null;e._onAbort=function(e){s(),i(e)};var d=function(){if(2==e.xhr.readyState){if(206==e.xhr.status){var d=function(e){var t=getXHRRangeMatches(e);return t?parseInt(t[1],10):0}(e.xhr);if(e.offset!=d)return console.log("Expected start at "+e.offset+" but got "+d+"; working around Safari range caching bug: https://bugs.webkit.org/show_bug.cgi?id=82672"),e.cachever++,e.emit("cachever"),e.abort(),s(),void e.load().then(t).catch(i);e.seekable=!0}e.xhr.status>=200&&e.xhr.status<300?(e.length=function(e){if(206==e.status)return function(e){var t=getXHRRangeMatches(e);return t?parseInt(t[3],10):-1}(e);var t=e.getResponseHeader("Content-Length");return null===t||""===t?-1:parseInt(t,10)}(e.xhr),e.headers=function(e){var t={};return e.getAllResponseHeaders().split(/\r?\n/).forEach((function(e){var i=e.split(/:\s*/,2);i.length>1&&(t[i[0].toLowerCase()]=i[1])})),t}(e.xhr),e.onXHRStart()):(s(),i(new Error("HTTP error "+e.xhr.status)))}},h=function(){s(),i(new Error("network error"))},u=function(){s(),t()};s=function(){e.xhr.removeEventListener("readystatechange",d),e.xhr.removeEventListener("error",h),e.off("open",u),e._onAbort=null},e.initXHR(),e.xhr.addEventListener("readystatechange",d),e.xhr.addEventListener("error",h),e.on("open",u),e.xhr.send()}))}},{key:"bufferToOffset",value:function(e){return Promise.reject(new Error("abstract"))}},{key:"abort",value:function(){if(this.xhr.abort(),this._onAbort){var e=this._onAbort;this._onAbort=null;var t=new Error("Aborted");t.name="AbortError",e(t)}}},{key:"initXHR",value:function(){var e=this.url;this.cachever&&(e+="?buggy_cachever="+this.cachever),this.xhr.open("GET",e);var t=null;(this.offset||this.length)&&(t="bytes="+this.offset+"-"),this.length&&(t+=this.offset+this.length-1),null!==t&&this.xhr.setRequestHeader("Range",t)}},{key:"onXHRStart",value:function(){throw new Error("abstract")}}]),Backend}(i(566));e.exports=d},810:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}(),d=function get(e,t,i){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(void 0===s){var d=Object.getPrototypeOf(e);return null===d?void 0:get(d,t,i)}if("value"in s)return s.value;var h=s.get;return void 0!==h?h.call(i):void 0};function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var h=function(e){function BinaryStringBackend(){return _classCallCheck(this,BinaryStringBackend),_possibleConstructorReturn(this,(BinaryStringBackend.__proto__||Object.getPrototypeOf(BinaryStringBackend)).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(BinaryStringBackend,e),s(BinaryStringBackend,[{key:"initXHR",value:function(){d(BinaryStringBackend.prototype.__proto__||Object.getPrototypeOf(BinaryStringBackend.prototype),"initXHR",this).call(this),this.xhr.responseType="text",this.xhr.overrideMimeType("text/plain; charset=x-user-defined")}},{key:"onXHRProgress",value:function(){var e=this.xhr.responseText.slice(this.bytesRead);e.length>0&&(this.bytesRead+=e.length,this.emit("buffer",e))}},{key:"onXHRLoad",value:function(){this.onXHRProgress(),d(BinaryStringBackend.prototype.__proto__||Object.getPrototypeOf(BinaryStringBackend.prototype),"onXHRLoad",this).call(this)}}]),BinaryStringBackend}(i(828));h.supported=function(){try{return!!(new XMLHttpRequest).overrideMimeType}catch(e){return!1}},e.exports=h},828:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}(),d=function get(e,t,i){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(void 0===s){var d=Object.getPrototypeOf(e);return null===d?void 0:get(d,t,i)}if("value"in s)return s.value;var h=s.get;return void 0!==h?h.call(i):void 0};function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var h=function(e){function DownloadBackend(){return _classCallCheck(this,DownloadBackend),_possibleConstructorReturn(this,(DownloadBackend.__proto__||Object.getPrototypeOf(DownloadBackend)).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(DownloadBackend,e),s(DownloadBackend,[{key:"bufferToOffset",value:function(e){var t=this;return new Promise((function(i,s){if(t.eof||t.offset>=e)i();else{var d=null;t._onAbort=function(e){d(),s(e)};var h=function(){t.offset>=e&&!t.eof&&(d(),i())},u=function(){d(),i()},c=function(){d(),s(new Error("error streaming"))};d=function(){t.buffering=!1,t.off("buffer",h),t.off("done",u),t.off("error",c),t._onAbort=null},t.buffering=!0,t.on("buffer",h),t.on("done",u),t.on("error",c)}}))}},{key:"initXHR",value:function(){d(DownloadBackend.prototype.__proto__||Object.getPrototypeOf(DownloadBackend.prototype),"initXHR",this).call(this)}},{key:"onXHRStart",value:function(){var e=this;this.xhr.addEventListener("progress",(function(){return e.onXHRProgress()})),this.xhr.addEventListener("error",(function(){return e.onXHRError()})),this.xhr.addEventListener("load",(function(){return e.onXHRLoad()})),this.emit("open")}},{key:"onXHRProgress",value:function(){throw new Error("abstract")}},{key:"onXHRError",value:function(){this.emit("error")}},{key:"onXHRLoad",value:function(){this.eof=!0,this.emit("done")}}]),DownloadBackend}(i(306));e.exports=h},761:(e,t,i)=>{var s=i(855),d=i(810),h=i(431),u=null;e.exports=function(e){if(!1===e.progressive)return new h(e);if(u||(u=s.supported()?s:d.supported()?d:null),!u)throw new Error("No supported backend class");return new u(e)}},855:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}(),d=function get(e,t,i){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(void 0===s){var d=Object.getPrototypeOf(e);return null===d?void 0:get(d,t,i)}if("value"in s)return s.value;var h=s.get;return void 0!==h?h.call(i):void 0};function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var h=i(828),u="moz-chunked-arraybuffer",c=function(e){function MozChunkedBackend(){return _classCallCheck(this,MozChunkedBackend),_possibleConstructorReturn(this,(MozChunkedBackend.__proto__||Object.getPrototypeOf(MozChunkedBackend)).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(MozChunkedBackend,e),s(MozChunkedBackend,[{key:"initXHR",value:function(){d(MozChunkedBackend.prototype.__proto__||Object.getPrototypeOf(MozChunkedBackend.prototype),"initXHR",this).call(this),this.xhr.responseType=u}},{key:"onXHRProgress",value:function(){var e=this.xhr.response;this.bytesRead+=e.byteLength,this.emit("buffer",e)}}]),MozChunkedBackend}(h);c.supported=function(){try{var e=new XMLHttpRequest;return e.responseType=u,e.responseType===u}catch(e){return!1}},e.exports=c},503:e=>{var t=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}();function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function CacheItem(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.buffer,i=void 0===t?void 0:t,s=e.string,d=void 0===s?void 0:s,h=e.start,u=void 0===h?0:h,c=e.end,l=void 0===c?u+(i?i.byteLength:d?d.length:0):c,f=e.prev,_=void 0===f?null:f,p=e.next,m=void 0===p?null:p,g=e.eof,v=void 0!==g&&g,y=e.empty,b=void 0===y?!(i||d):y,T=e.timestamp,k=void 0===T?Date.now():T;_classCallCheck(this,CacheItem),this.start=u,this.end=l,this.prev=_,this.next=m,this.eof=v,this.empty=b,this.timestamp=k,this.buffer=i,this.string=d,Object.defineProperty(this,"length",{get:function(){return this.end-this.start}})}return t(CacheItem,[{key:"contains",value:function(e){return e>=this.start&&(e<this.end||this.eof)}},{key:"readBytes",value:function(e,t,i){var s=t-this.start,d=i-t;if(this.buffer){var h=new Uint8Array(this.buffer,s,d);e.set(h)}else{if(!this.string)throw new Error("invalid state");for(var u=this.string,c=0;c<d;c++)e[c]=u.charCodeAt(s+c)}this.timestamp=Date.now()}},{key:"split",value:function(e){if(!this.empty||!this.contains(e))throw new Error("invalid split");var t=new CacheItem({start:this.start,end:e}),i=new CacheItem({start:e,end:this.eof?e:this.end,eof:this.eof});return t.next=i,i.prev=t,[t,i]}},{key:"first",value:function(e){for(var t=this;t;t=t.next)if(e(t))return t;return null}},{key:"last",value:function(e){for(var last=null,t=this;t&&e(t);t=t.next)last=t;return last}}]),CacheItem}();e.exports=i},91:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}();function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var d=i(503),h=function(){function CachePool(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.cacheSize,i=void 0===t?0:t;_classCallCheck(this,CachePool);var s=new d({eof:!0});this.head=s,this.tail=s,this.readOffset=0,this.readCursor=s,this.writeOffset=0,this.writeCursor=s,this.cacheSize=i}return s(CachePool,[{key:"bytesReadable",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0,t=this.readOffset,i=this.readCursor,s=i.last((function(i){return!i.empty&&i.start<=t+e}));return s?Math.min(e,s.end-t):0}},{key:"bytesWritable",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0,t=this.writeOffset,i=this.writeCursor;if(i.eof)return e;var s=i.last((function(i){return i.empty&&i.start<=t+e}));return s?Math.min(e,s.end-t):0}},{key:"seekRead",value:function(e){var t=this.head.first((function(t){return t.contains(e)}));if(!t)throw new Error("read seek out of range");this.readOffset=e,this.readCursor=t}},{key:"seekWrite",value:function(e){var t=this.head.first((function(t){return t.contains(e)}));if(!t)throw new Error("write seek out of range");this.writeOffset=e,this.writeCursor=t}},{key:"readBytes",value:function(e){for(var t=e.byteLength,i=this.bytesReadable(t),s=this.readOffset,d=s+i,h=s,u=this.readCursor;u&&!u.empty&&!(u.start>=d);u=u.next){var c=Math.min(d,u.end),l=e.subarray(h-s,c-s);u.readBytes(l,h,c),h=c}return this.readOffset=h,this.readCursor=this.readCursor.first((function(e){return e.contains(h)})),i}},{key:"write",value:function(e){var t=this.bufferItem(e),i=this.writeCursor;if(!i.empty)throw new Error("write cursor not empty");if(!i.contains(t.end)&&i.end!==t.end)throw new Error("write cursor too small");i.start<t.start&&(this.split(i,t.start),i=this.writeCursor),(t.end<i.end||i.eof)&&(this.split(i,t.end),i=this.writeCursor),this.splice(i,i,t,t),this.writeOffset=t.end,this.writeCursor=t.next,this.gc()}},{key:"bufferItem",value:function(e){if(e instanceof ArrayBuffer)return new d({start:this.writeOffset,end:this.writeOffset+e.byteLength,buffer:e});if("string"==typeof e)return new d({start:this.writeOffset,end:this.writeOffset+e.length,string:e});throw new Error("invalid input to write")}},{key:"split",value:function(e,t){var i=e.split(t);this.splice(e,e,i[0],i[1])}},{key:"ranges",value:function(){for(var ranges=[],e=this.head;e;e=e.next)if(!e.empty){var t=e;e=e.last((function(e){return!e.empty})),ranges.push([t.start,e.end])}return ranges}},{key:"gc",value:function(){for(var e=0,t=[],i=this.head;i;i=i.next)i.empty||(e+=i.length,(i.end<this.readOffset||i.start>this.readOffset+this.chunkSize)&&t.push(i));if(e>this.cacheSize){t.sort((function(e,t){return e.timestamp-t.timestamp}));for(var s=0;s<t.length;s++){var d=t[s];if(e<=this.cacheSize)break;this.remove(d),e-=d.length}}}},{key:"remove",value:function(e){var t=new d({start:e.start,end:e.end});this.splice(e,e,t,t),(e=t).prev&&e.prev.empty&&(e=this.consolidate(e.prev)),e.next&&e.next.empty&&!e.next.eof&&(e=this.consolidate(e)),0===e.start&&(this.head=e)}},{key:"consolidate",value:function(e){var t=e.last((function(e){return e.empty&&!e.eof})),i=new d({start:e.start,end:t.end});return this.splice(e,t,i,i),i}},{key:"splice",value:function(e,t,i,s){var d=this;if(e.start!==i.start)throw new Error("invalid splice head");if(!(t.end===s.end||t.eof&&s.eof))throw new Error("invalid splice tail");var h=e.prev,u=t.next;e.prev=null,t.next=null,h&&(h.next=i,i.prev=h),u&&(u.prev=s,s.next=u),e===this.head&&(this.head=i),t===this.tail&&(this.tail=s),this.readCursor=this.head.first((function(e){return e.contains(d.readOffset)})),this.writeCursor=this.head.first((function(e){return e.contains(d.writeOffset)}))}},{key:"eof",get:function(){return this.readCursor.eof}}]),CachePool}();e.exports=h},814:(e,t,i)=>{e.exports=i(91)},566:e=>{var t=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}(),i=function(){function TinyEvents(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,TinyEvents),this._e={}}return t(TinyEvents,[{key:"on",value:function(e,t){(this._e[e]||(this._e[e]=[])).push(t)}},{key:"off",value:function(e,t){var i=this._e[e]||[],s=i.indexOf(t);t>=0&&i.splice(s,1)}},{key:"emit",value:function(e,t){(this._e[e]||[]).slice().forEach((function(e){return e(t)}))}}]),TinyEvents}();e.exports=i},936:(e,t,i)=>{var s=function(){function defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,i){return t&&defineProperties(e.prototype,t),i&&defineProperties(e,i),e}}();i(566);var d=i(814),h=i(761),u=function(){function StreamFile(e){var t=e.url,i=void 0===t?"":t,s=e.chunkSize,h=void 0===s?1048576:s,u=e.cacheSize,c=void 0===u?0:u,l=e.progressive,f=void 0===l||l;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,StreamFile),this.length=-1,this.loaded=!1,this.loading=!1,this.seekable=!1,this.buffering=!1,this.seeking=!1,this.progressive=f,Object.defineProperties(this,{offset:{get:function(){return this._cache.readOffset}},eof:{get:function(){return this.length===this._cache.readOffset}}}),this.url=i,this.headers={},this._cache=new d({cacheSize:c}),this._backend=null,this._cachever=0,this._chunkSize=h}return s(StreamFile,[{key:"load",value:function(){var e=this;return new Promise((function(t,i){if(e.loading)throw new Error("cannot load when loading");if(e.loaded)throw new Error("cannot load when loaded");e.loading=!0,e._openBackend().then((function(i){e.seekable=i.seekable,e.headers=i.headers,e.length=i.length,e.loaded=!0,e.loading=!1,t()})).catch((function(t){"AbortError"!==t.name&&(e.loading=!1),i(t)}))}))}},{key:"_openBackend",value:function(){var e=this;return new Promise((function(t,i){if(e._backend)t(e._backend);else if(e.eof)i(new Error("cannot open at end of file"));else{var s=e._cache,d=e._chunkSize,u=s.bytesReadable(d),c=s.readOffset+u;if(s.seekWrite(c),e.length>=0&&c>=e.length)return void t(null);var l=e._clampToLength(s.writeOffset+s.bytesWritable(d))-s.writeOffset;if(0===l)t(null);else{var f=e._backend=new h({url:e.url,offset:e._cache.writeOffset,length:l,cachever:e._cachever,progressive:e.progressive}),_=null,p=function(){f!==e._backend?(_(),i(new Error("invalid state"))):(f.on("buffer",(function(t){f===e._backend&&e._cache.write(t)})),f.on("done",(function(){f===e._backend&&(-1===e.length&&(e.length=e._backend.offset+e._backend.bytesRead),e._backend=null)})),t(f))},m=function(t){f!==e._backend?i(new Error("invalid state")):(e._backend=null,i(t))};_=function(){f.off("open",p),f.off("error",m)},f.on("open",p),f.on("error",m),f.on("cachever",(function(){e._cachever++})),f.load()}}}))}},{key:"_readAhead",value:function(){var e=this;return new Promise((function(t,i){e._backend||e.eof?t():e._openBackend().then((function(){t()})).catch((function(e){i(e)}))}))}},{key:"seek",value:function(e){var t=this;return new Promise((function(i,s){if(!t.loaded||t.buffering||t.seeking)throw new Error("invalid state");if(e!==(0|e)||e<0)throw new Error("invalid input");if(t.length>=0&&e>t.length)throw new Error("seek past end of file");if(!t.seekable)throw new Error("seek on non-seekable stream");t._backend&&t.abort(),t._cache.seekRead(e),t._cache.seekWrite(e),t._readAhead().then(i).catch(s)}))}},{key:"read",value:function(e){var t=this;return this.buffer(e).then((function(e){return t.readSync(e)}))}},{key:"readSync",value:function(e){var t=this.bytesAvailable(e),i=new Uint8Array(t);if(this.readBytes(i)!==t)throw new Error("failed to read expected data");return i.buffer}},{key:"readBytes",value:function(e){if(!this.loaded||this.buffering||this.seeking)throw new Error("invalid state");if(!(e instanceof Uint8Array))throw new Error("invalid input");var t=this._cache.readBytes(e);return this._readAhead(),t}},{key:"buffer",value:function(e){var t=this;return new Promise((function(i,s){if(!t.loaded||t.buffering||t.seeking)throw new Error("invalid state");if(e!==(0|e)||e<0)throw new Error("invalid input");var d=t._clampToLength(t.offset+e),h=d-t.offset,u=t.bytesAvailable(h);u>=h?i(u):(t.buffering=!0,t._openBackend().then((function(i){return i?i.bufferToOffset(d).then((function(){return t.buffering=!1,t.buffer(e)})):Promise.resolve(u)})).then((function(e){t.buffering=!1,i(e)})).catch((function(e){"AbortError"!==e.name&&(t.buffering=!1),s(e)})))}))}},{key:"bytesAvailable",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return this._cache.bytesReadable(e)}},{key:"abort",value:function(){this.loading&&(this.loading=!1),this.buffering&&(this.buffering=!1),this.seeking&&(this.seeking=!1),this._backend&&(this._backend.abort(),this._backend=null)}},{key:"getBufferedRanges",value:function(){return this._cache.ranges()}},{key:"_clampToLength",value:function(e){return this.length<0?e:Math.min(this.length,e)}}]),StreamFile}();e.exports=u},826:e=>{e.exports={vertex:"precision lowp float;\n\nattribute vec2 aPosition;\nattribute vec2 aLumaPosition;\nattribute vec2 aChromaPosition;\nvarying vec2 vLumaPosition;\nvarying vec2 vChromaPosition;\nvoid main() {\n gl_Position = vec4(aPosition, 0, 1);\n vLumaPosition = aLumaPosition;\n vChromaPosition = aChromaPosition;\n}\n",fragment:"// inspired by https://github.com/mbebenita/Broadway/blob/master/Player/canvas.js\n\nprecision lowp float;\n\nuniform sampler2D uTextureY;\nuniform sampler2D uTextureCb;\nuniform sampler2D uTextureCr;\nvarying vec2 vLumaPosition;\nvarying vec2 vChromaPosition;\nvoid main() {\n // Y, Cb, and Cr planes are uploaded as LUMINANCE textures.\n float fY = texture2D(uTextureY, vLumaPosition).x;\n float fCb = texture2D(uTextureCb, vChromaPosition).x;\n float fCr = texture2D(uTextureCr, vChromaPosition).x;\n\n // Premultipy the Y...\n float fYmul = fY * 1.1643828125;\n\n // And convert that to RGB!\n gl_FragColor = vec4(\n fYmul + 1.59602734375 * fCr - 0.87078515625,\n fYmul - 0.39176171875 * fCb - 0.81296875 * fCr + 0.52959375,\n fYmul + 2.017234375 * fCb - 1.081390625,\n 1\n );\n}\n",vertexStripe:"precision lowp float;\n\nattribute vec2 aPosition;\nattribute vec2 aTexturePosition;\nvarying vec2 vTexturePosition;\n\nvoid main() {\n gl_Position = vec4(aPosition, 0, 1);\n vTexturePosition = aTexturePosition;\n}\n",fragmentStripe:"// extra 'stripe' texture fiddling to work around IE 11's poor performance on gl.LUMINANCE and gl.ALPHA textures\n\nprecision lowp float;\n\nuniform sampler2D uStripe;\nuniform sampler2D uTexture;\nvarying vec2 vTexturePosition;\nvoid main() {\n // Y, Cb, and Cr planes are mapped into a pseudo-RGBA texture\n // so we can upload them without expanding the bytes on IE 11\n // which doesn't allow LUMINANCE or ALPHA textures\n // The stripe textures mark which channel to keep for each pixel.\n // Each texture extraction will contain the relevant value in one\n // channel only.\n\n float fLuminance = dot(\n texture2D(uStripe, vTexturePosition),\n texture2D(uTexture, vTexturePosition)\n );\n\n gl_FragColor = vec4(fLuminance, fLuminance, fLuminance, 1);\n}\n"}},487:e=>{!function(){function FrameSink(e,t){throw new Error("abstract")}FrameSink.prototype.drawFrame=function(e){throw new Error("abstract")},FrameSink.prototype.clear=function(){throw new Error("abstract")},e.exports=FrameSink}()},926:(e,t,i)=>{!function(){var t=i(487),s=i(627);function SoftwareFrameSink(e){var t=this,i=e.getContext("2d"),d=null,h=null,u=null;return t.drawFrame=function(t){var c=t.format;e.width===c.displayWidth&&e.height===c.displayHeight||(e.width=c.displayWidth,e.height=c.displayHeight),null!==d&&d.width==c.width&&d.height==c.height||function(e,t){for(var s=(d=i.createImageData(e,t)).data,h=e*t*4,u=0;u<h;u+=4)s[u+3]=255}(c.width,c.height),s.convertYCbCr(t,d.data);var l,f=c.cropWidth!=c.displayWidth||c.cropHeight!=c.displayHeight;f?(h||function(e,t){(h=document.createElement("canvas")).width=e,h.height=t,u=h.getContext("2d")}(c.cropWidth,c.cropHeight),l=u):l=i,l.putImageData(d,-c.cropLeft,-c.cropTop,c.cropLeft,c.cropTop,c.cropWidth,c.cropHeight),f&&i.drawImage(h,0,0,c.displayWidth,c.displayHeight)},t.clear=function(){i.clearRect(0,0,e.width,e.height)},t}SoftwareFrameSink.prototype=Object.create(t.prototype),e.exports=SoftwareFrameSink}()},895:(e,t,i)=>{!function(){var t=i(487),s=i(826);function WebGLFrameSink(e){var t,i,d=this,h=WebGLFrameSink.contextForCanvas(e);if(null===h)throw new Error("WebGL unavailable");function compileShader(e,t){var i=h.createShader(e);if(h.shaderSource(i,t),h.compileShader(i),!h.getShaderParameter(i,h.COMPILE_STATUS)){var s=h.getShaderInfoLog(i);throw h.deleteShader(i),new Error("GL shader compilation for "+e+" failed: "+s)}return i}var u,c,l,f,_,p,m,g,v,y,b=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),T={},k={},P={};function createOrReuseTexture(e){return T[e]||(T[e]=h.createTexture()),T[e]}function uploadTexture(e,t,i,s){var d=createOrReuseTexture(e);if(h.activeTexture(h.TEXTURE0),WebGLFrameSink.stripe){var u=!T[e+"_temp"],c=createOrReuseTexture(e+"_temp");h.bindTexture(h.TEXTURE_2D,c),u?(h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,t/4,i,0,h.RGBA,h.UNSIGNED_BYTE,s)):h.texSubImage2D(h.TEXTURE_2D,0,0,0,t/4,i,h.RGBA,h.UNSIGNED_BYTE,s);var l=T[e+"_stripe"],f=!l;f&&(l=createOrReuseTexture(e+"_stripe")),h.bindTexture(h.TEXTURE_2D,l),f&&(h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,t,1,0,h.RGBA,h.UNSIGNED_BYTE,function(e){if(P[e])return P[e];for(var t=e,i=new Uint32Array(t),s=0;s<t;s+=4)i[s]=255,i[s+1]=65280,i[s+2]=16711680,i[s+3]=4278190080;return P[e]=new Uint8Array(i.buffer)}(t)))}else h.bindTexture(h.TEXTURE_2D,d),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.LINEAR),h.texImage2D(h.TEXTURE_2D,0,h.LUMINANCE,t,i,0,h.LUMINANCE,h.UNSIGNED_BYTE,s)}function unpackTexture(e,t,s){var d=T[e];h.useProgram(i);var m=k[e];m||(h.activeTexture(h.TEXTURE0),h.bindTexture(h.TEXTURE_2D,d),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.LINEAR),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,t,s,0,h.RGBA,h.UNSIGNED_BYTE,null),m=k[e]=h.createFramebuffer()),h.bindFramebuffer(h.FRAMEBUFFER,m),h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,d,0);var g=T[e+"_temp"];h.activeTexture(h.TEXTURE1),h.bindTexture(h.TEXTURE_2D,g),h.uniform1i(p,1);var v=T[e+"_stripe"];h.activeTexture(h.TEXTURE2),h.bindTexture(h.TEXTURE_2D,v),h.uniform1i(_,2),h.bindBuffer(h.ARRAY_BUFFER,u),h.enableVertexAttribArray(c),h.vertexAttribPointer(c,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,l),h.enableVertexAttribArray(f),h.vertexAttribPointer(f,2,h.FLOAT,!1,0,0),h.viewport(0,0,t,s),h.drawArrays(h.TRIANGLES,0,b.length/2),h.bindFramebuffer(h.FRAMEBUFFER,null)}function attachTexture(e,i,s){h.activeTexture(i),h.bindTexture(h.TEXTURE_2D,T[e]),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.LINEAR),h.uniform1i(h.getUniformLocation(t,e),s)}function initProgram(e,t){var i=compileShader(h.VERTEX_SHADER,e),s=compileShader(h.FRAGMENT_SHADER,t),d=h.createProgram();if(h.attachShader(d,i),h.attachShader(d,s),h.linkProgram(d),!h.getProgramParameter(d,h.LINK_STATUS)){var u=h.getProgramInfoLog(d);throw h.deleteProgram(d),new Error("GL program linking failed: "+u)}return d}return d.drawFrame=function(T){var k=T.format,P=!t||e.width!==k.displayWidth||e.height!==k.displayHeight;if(P&&(e.width=k.displayWidth,e.height=k.displayHeight,d.clear()),t||function(){if(WebGLFrameSink.stripe){i=initProgram(s.vertexStripe,s.fragmentStripe),h.getAttribLocation(i,"aPosition"),l=h.createBuffer();var e=new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]);h.bindBuffer(h.ARRAY_BUFFER,l),h.bufferData(h.ARRAY_BUFFER,e,h.STATIC_DRAW),f=h.getAttribLocation(i,"aTexturePosition"),_=h.getUniformLocation(i,"uStripe"),p=h.getUniformLocation(i,"uTexture")}t=initProgram(s.vertex,s.fragment),u=h.createBuffer(),h.bindBuffer(h.ARRAY_BUFFER,u),h.bufferData(h.ARRAY_BUFFER,b,h.STATIC_DRAW),c=h.getAttribLocation(t,"aPosition"),m=h.createBuffer(),g=h.getAttribLocation(t,"aLumaPosition"),v=h.createBuffer(),y=h.getAttribLocation(t,"aChromaPosition")}(),P){var setupTexturePosition=function(e,t,i){var s=k.cropLeft/i,d=(k.cropLeft+k.cropWidth)/i,u=(k.cropTop+k.cropHeight)/k.height,c=k.cropTop/k.height,l=new Float32Array([s,u,d,u,s,c,s,c,d,u,d,c]);h.bindBuffer(h.ARRAY_BUFFER,e),h.bufferData(h.ARRAY_BUFFER,l,h.STATIC_DRAW)};setupTexturePosition(m,0,T.y.stride),setupTexturePosition(v,0,T.u.stride*k.width/k.chromaWidth)}uploadTexture("uTextureY",T.y.stride,k.height,T.y.bytes),uploadTexture("uTextureCb",T.u.stride,k.chromaHeight,T.u.bytes),uploadTexture("uTextureCr",T.v.stride,k.chromaHeight,T.v.bytes),WebGLFrameSink.stripe&&(unpackTexture("uTextureY",T.y.stride,k.height),unpackTexture("uTextureCb",T.u.stride,k.chromaHeight),unpackTexture("uTextureCr",T.v.stride,k.chromaHeight)),h.useProgram(t),h.viewport(0,0,e.width,e.height),attachTexture("uTextureY",h.TEXTURE0,0),attachTexture("uTextureCb",h.TEXTURE1,1),attachTexture("uTextureCr",h.TEXTURE2,2),h.bindBuffer(h.ARRAY_BUFFER,u),h.enableVertexAttribArray(c),h.vertexAttribPointer(c,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,m),h.enableVertexAttribArray(g),h.vertexAttribPointer(g,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,v),h.enableVertexAttribArray(y),h.vertexAttribPointer(y,2,h.FLOAT,!1,0,0),h.drawArrays(h.TRIANGLES,0,b.length/2)},d.clear=function(){h.viewport(0,0,e.width,e.height),h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT)},d.clear(),d}WebGLFrameSink.stripe=-1!==navigator.userAgent.indexOf("Windows"),WebGLFrameSink.contextForCanvas=function(e){var t={preferLowPowerToHighPerformance:!0,powerPreference:"low-power",failIfMajorPerformanceCaveat:!0,preserveDrawingBuffer:!0};return e.getContext("webgl",t)||e.getContext("experimental-webgl",t)},WebGLFrameSink.isAvailable=function(){var e,t=document.createElement("canvas");t.width=1,t.height=1;try{e=WebGLFrameSink.contextForCanvas(t)}catch(e){return!1}if(e){var i=e.TEXTURE0,s=e.createTexture(),d=new Uint8Array(16),h=WebGLFrameSink.stripe?1:4,u=WebGLFrameSink.stripe?e.RGBA:e.LUMINANCE,c=WebGLFrameSink.stripe?e.NEAREST:e.LINEAR;return e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,c),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,c),e.texImage2D(e.TEXTURE_2D,0,u,h,4,0,u,e.UNSIGNED_BYTE,d),!e.getError()}return!1},WebGLFrameSink.prototype=Object.create(t.prototype),e.exports=WebGLFrameSink}()},627:(e,t,i)=>{!function(){var t=i(877);e.exports={convertYCbCr:function(e,i){var s=0|e.format.width,d=0|e.format.height,h=0|t(e.format.width/e.format.chromaWidth),u=0|t(e.format.height/e.format.chromaHeight),c=e.y.bytes,l=e.u.bytes,f=e.v.bytes,_=0|e.y.stride,p=0|e.u.stride,m=0|e.v.stride,g=s<<2,v=0,y=0,b=0,T=0,k=0,P=0,w=0,E=0,x=0,A=0,R=0,O=0,F=0,S=0,C=0,B=0,D=0,M=0;if(1==h&&1==u)for(w=0,E=g,M=0,B=0;B<d;B+=2){for(b=(y=B*_|0)+_|0,T=M*p|0,k=M*m|0,C=0;C<s;C+=2)x=0|l[T++],O=(409*(A=0|f[k++])|0)-57088|0,F=(100*x|0)+(208*A|0)-34816|0,S=(516*x|0)-70912|0,R=298*c[y++]|0,i[w]=R+O>>8,i[w+1]=R-F>>8,i[w+2]=R+S>>8,w+=4,R=298*c[y++]|0,i[w]=R+O>>8,i[w+1]=R-F>>8,i[w+2]=R+S>>8,w+=4,R=298*c[b++]|0,i[E]=R+O>>8,i[E+1]=R-F>>8,i[E+2]=R+S>>8,E+=4,R=298*c[b++]|0,i[E]=R+O>>8,i[E+1]=R-F>>8,i[E+2]=R+S>>8,E+=4;w+=g,E+=g,M++}else for(P=0,B=0;B<d;B++)for(D=0,v=B*_|0,T=(M=B>>u)*p|0,k=M*m|0,C=0;C<s;C++)x=0|l[T+(D=C>>h)],O=(409*(A=0|f[k+D])|0)-57088|0,F=(100*x|0)+(208*A|0)-34816|0,S=(516*x|0)-70912|0,R=298*c[v++]|0,i[P]=R+O>>8,i[P+1]=R-F>>8,i[P+2]=R+S>>8,P+=4}}}()},877:e=>{e.exports=function(e){for(var t=0,i=e>>1;0!=i;)i>>=1,t++;if(e!==1<<t)throw"chroma plane dimensions must be power of 2 ratio to luma plane dimensions; got "+e;return t}},731:(e,t,i)=>{!function(){var t=i(487),s=i(926),d=i(895),h={FrameSink:t,SoftwareFrameSink:s,WebGLFrameSink:d,attach:function(e,t){return("webGL"in(t=t||{})?t.webGL:d.isAvailable())?new d(e,t):new s(e,t)}};e.exports=h}()}},t={};function __webpack_require__(i){var s=t[i];if(void 0!==s)return s.exports;var d=t[i]={exports:{}};return e[i](d,d.exports,__webpack_require__),d.exports}var i={};return(()=>{var e=i,t=__webpack_require__(318);Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"OGVCompat",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"OGVLoader",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(e,"OGVMediaError",{enumerable:!0,get:function(){return h.default}}),Object.defineProperty(e,"OGVMediaType",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"OGVPlayer",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"OGVTimeRanges",{enumerable:!0,get:function(){return l.default}}),e.OGVVersion=void 0;var s=t(__webpack_require__(523)),d=t(__webpack_require__(964)),h=t(__webpack_require__(759)),u=t(__webpack_require__(278)),c=t(__webpack_require__(869)),l=t(__webpack_require__(168)),f="1.8.4-20210702161914-bd3a07f";e.OGVVersion=f,"object"==typeof window&&(window.OGVCompat=s.default,window.OGVLoader=d.default,window.OGVMediaError=h.default,window.OGVMediaType=u.default,window.OGVTimeRanges=l.default,window.OGVPlayer=c.default,window.OGVVersion=f)})(),i})()},"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("media_videojs/local/ogv/ogv",[],t):"object"==typeof exports?exports.ogvjs=t():e.ogvjs=t(); /*! highlight.js v9.18.1 | BSD3 License | git.io/hljslicense */ !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"==typeof exports||exports.nodeType?n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define('filter_syntaxhighlighter/hljs', [],function(){return n.hljs})):e(exports)}(function(a){var f=[],i=Object.keys,_={},c={},C=!0,n=/^(no-?highlight|plain|text)$/i,l=/\blang(?:uage)?-([\w-]+)\b/i,t=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,r={case_insensitive:"cI",lexemes:"l",contains:"c",keywords:"k",subLanguage:"sL",className:"cN",begin:"b",beginKeywords:"bK",end:"e",endsWithParent:"eW",illegal:"i",excludeBegin:"eB",excludeEnd:"eE",returnBegin:"rB",returnEnd:"rE",variants:"v",IDENT_RE:"IR",UNDERSCORE_IDENT_RE:"UIR",NUMBER_RE:"NR",C_NUMBER_RE:"CNR",BINARY_NUMBER_RE:"BNR",RE_STARTERS_RE:"RSR",BACKSLASH_ESCAPE:"BE",APOS_STRING_MODE:"ASM",QUOTE_STRING_MODE:"QSM",PHRASAL_WORDS_MODE:"PWM",C_LINE_COMMENT_MODE:"CLCM",C_BLOCK_COMMENT_MODE:"CBCM",HASH_COMMENT_MODE:"HCM",NUMBER_MODE:"NM",C_NUMBER_MODE:"CNM",BINARY_NUMBER_MODE:"BNM",CSS_NUMBER_MODE:"CSSNM",REGEXP_MODE:"RM",TITLE_MODE:"TM",UNDERSCORE_TITLE_MODE:"UTM",COMMENT:"C",beginRe:"bR",endRe:"eR",illegalRe:"iR",lexemesRe:"lR",terminators:"t",terminator_end:"tE"},m="</span>",O="Could not find the language '{}', did you forget to load/include a language module?",B={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},o="of and for in not or if then".split(" ");function x(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function g(e){return e.nodeName.toLowerCase()}function u(e){return n.test(e)}function s(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function E(e){var a=[];return function e(n,t){for(var r=n.firstChild;r;r=r.nextSibling)3===r.nodeType?t+=r.nodeValue.length:1===r.nodeType&&(a.push({event:"start",offset:t,node:r}),t=e(r,t),g(r).match(/br|hr|img|input/)||a.push({event:"stop",offset:t,node:r}));return t}(e,0),a}function d(e,n,t){var r=0,a="",i=[];function o(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset<n[0].offset?e:n:"start"===n[0].event?e:n:e.length?e:n}function c(e){a+="<"+g(e)+f.map.call(e.attributes,function(e){return" "+e.nodeName+'="'+x(e.value).replace(/"/g,""")+'"'}).join("")+">"}function l(e){a+="</"+g(e)+">"}function u(e){("start"===e.event?c:l)(e.node)}for(;e.length||n.length;){var s=o();if(a+=x(t.substring(r,s[0].offset)),r=s[0].offset,s===e){for(i.reverse().forEach(l);u(s.splice(0,1)[0]),(s=o())===e&&s.length&&s[0].offset===r;);i.reverse().forEach(c)}else"start"===s[0].event?i.push(s[0].node):i.pop(),u(s.splice(0,1)[0])}return a+x(t.substr(r))}function R(n){return n.v&&!n.cached_variants&&(n.cached_variants=n.v.map(function(e){return s(n,{v:null},e)})),n.cached_variants?n.cached_variants:function e(n){return!!n&&(n.eW||e(n.starts))}(n)?[s(n,{starts:n.starts?s(n.starts):null})]:Object.isFrozen(n)?[s(n)]:[n]}function p(e){if(r&&!e.langApiRestored){for(var n in e.langApiRestored=!0,r)e[n]&&(e[r[n]]=e[n]);(e.c||[]).concat(e.v||[]).forEach(p)}}function v(n,r){var a={};return"string"==typeof n?t("keyword",n):i(n).forEach(function(e){t(e,n[e])}),a;function t(t,e){r&&(e=e.toLowerCase()),e.split(" ").forEach(function(e){var n=e.split("|");a[n[0]]=[t,function(e,n){return n?Number(n):function(e){return-1!=o.indexOf(e.toLowerCase())}(e)?0:1}(n[0],n[1])]})}}function S(r){function s(e){return e&&e.source||e}function f(e,n){return new RegExp(s(e),"m"+(r.cI?"i":"")+(n?"g":""))}function a(a){var i,e,o={},c=[],l={},t=1;function n(e,n){o[t]=e,c.push([e,n]),t+=function(e){return new RegExp(e.toString()+"|").exec("").length-1}(n)+1}for(var r=0;r<a.c.length;r++){n(e=a.c[r],e.bK?"\\.?(?:"+e.b+")\\.?":e.b)}a.tE&&n("end",a.tE),a.i&&n("illegal",a.i);var u=c.map(function(e){return e[1]});return i=f(function(e,n){for(var t=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./,r=0,a="",i=0;i<e.length;i++){var o=r+=1,c=s(e[i]);for(0<i&&(a+=n),a+="(";0<c.length;){var l=t.exec(c);if(null==l){a+=c;break}a+=c.substring(0,l.index),c=c.substring(l.index+l[0].length),"\\"==l[0][0]&&l[1]?a+="\\"+String(Number(l[1])+o):(a+=l[0],"("==l[0]&&r++)}a+=")"}return a}(u,"|"),!0),l.lastIndex=0,l.exec=function(e){var n;if(0===c.length)return null;i.lastIndex=l.lastIndex;var t=i.exec(e);if(!t)return null;for(var r=0;r<t.length;r++)if(null!=t[r]&&null!=o[""+r]){n=o[""+r];break}return"string"==typeof n?(t.type=n,t.extra=[a.i,a.tE]):(t.type="begin",t.rule=n),t},l}if(r.c&&-1!=r.c.indexOf("self")){if(!C)throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");r.c=r.c.filter(function(e){return"self"!=e})}!function n(t,e){t.compiled||(t.compiled=!0,t.k=t.k||t.bK,t.k&&(t.k=v(t.k,r.cI)),t.lR=f(t.l||/\w+/,!0),e&&(t.bK&&(t.b="\\b("+t.bK.split(" ").join("|")+")\\b"),t.b||(t.b=/\B|\b/),t.bR=f(t.b),t.endSameAsBegin&&(t.e=t.b),t.e||t.eW||(t.e=/\B|\b/),t.e&&(t.eR=f(t.e)),t.tE=s(t.e)||"",t.eW&&e.tE&&(t.tE+=(t.e?"|":"")+e.tE)),t.i&&(t.iR=f(t.i)),null==t.relevance&&(t.relevance=1),t.c||(t.c=[]),t.c=Array.prototype.concat.apply([],t.c.map(function(e){return R("self"===e?t:e)})),t.c.forEach(function(e){n(e,t)}),t.starts&&n(t.starts,e),t.t=a(t))}(r)}function T(n,e,a,t){var i=e;function o(e,n){if(function(e,n){var t=e&&e.exec(n);return t&&0===t.index}(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}if(e.eW)return o(e.parent,n)}function c(e,n,t,r){if(!t&&""===n)return"";if(!e)return n;var a='<span class="'+(r?"":B.classPrefix);return(a+=e+'">')+n+(t?"":m)}function l(){p+=null!=d.sL?function(){var e="string"==typeof d.sL;if(e&&!_[d.sL])return x(v);var n=e?T(d.sL,v,!0,R[d.sL]):w(v,d.sL.length?d.sL:void 0);return 0<d.relevance&&(M+=n.relevance),e&&(R[d.sL]=n.top),c(n.language,n.value,!1,!0)}():function(){var e,n,t,r,a,i,o;if(!d.k)return x(v);for(r="",n=0,d.lR.lastIndex=0,t=d.lR.exec(v);t;)r+=x(v.substring(n,t.index)),a=d,i=t,void 0,o=g.cI?i[0].toLowerCase():i[0],(e=a.k.hasOwnProperty(o)&&a.k[o])?(M+=e[1],r+=c(e[0],x(t[0]))):r+=x(t[0]),n=d.lR.lastIndex,t=d.lR.exec(v);return r+x(v.substr(n))}(),v=""}function u(e){p+=e.cN?c(e.cN,"",!0):"",d=Object.create(e,{parent:{value:d}})}function s(e){var n=e[0],t=e.rule;return t&&t.endSameAsBegin&&(t.eR=function(e){return new RegExp(e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(n)),t.skip?v+=n:(t.eB&&(v+=n),l(),t.rB||t.eB||(v=n)),u(t),t.rB?0:n.length}var f={};function r(e,n){var t=n&&n[0];if(v+=e,null==t)return l(),0;if("begin"==f.type&&"end"==n.type&&f.index==n.index&&""===t)return v+=i.slice(n.index,n.index+1),1;if("begin"===(f=n).type)return s(n);if("illegal"===n.type&&!a)throw new Error('Illegal lexeme "'+t+'" for mode "'+(d.cN||"<unnamed>")+'"');if("end"===n.type){var r=function(e){var n=e[0],t=i.substr(e.index),r=o(d,t);if(r){var a=d;for(a.skip?v+=n:(a.rE||a.eE||(v+=n),l(),a.eE&&(v=n));d.cN&&(p+=m),d.skip||d.sL||(M+=d.relevance),(d=d.parent)!==r.parent;);return r.starts&&(r.endSameAsBegin&&(r.starts.eR=r.eR),u(r.starts)),a.rE?0:n.length}}(n);if(null!=r)return r}return v+=t,t.length}var g=D(n);if(!g)throw console.error(O.replace("{}",n)),new Error('Unknown language: "'+n+'"');S(g);var E,d=t||g,R={},p="";for(E=d;E!==g;E=E.parent)E.cN&&(p=c(E.cN,"",!0)+p);var v="",M=0;try{for(var b,h,N=0;d.t.lastIndex=N,b=d.t.exec(i);)h=r(i.substring(N,b.index),b),N=b.index+h;for(r(i.substr(N)),E=d;E.parent;E=E.parent)E.cN&&(p+=m);return{relevance:M,value:p,i:!1,language:n,top:d}}catch(e){if(e.message&&-1!==e.message.indexOf("Illegal"))return{i:!0,relevance:0,value:x(i)};if(C)return{relevance:0,value:x(i),language:n,top:d,errorRaised:e};throw e}}function w(t,e){e=e||B.languages||i(_);var r={relevance:0,value:x(t)},a=r;return e.filter(D).filter(L).forEach(function(e){var n=T(e,t,!1);n.language=e,n.relevance>a.relevance&&(a=n),n.relevance>r.relevance&&(a=r,r=n)}),a.language&&(r.second_best=a),r}function M(e){return B.tabReplace||B.useBR?e.replace(t,function(e,n){return B.useBR&&"\n"===e?"<br>":B.tabReplace?n.replace(/\t/g,B.tabReplace):""}):e}function b(e){var n,t,r,a,i,o=function(e){var n,t,r,a,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=l.exec(i)){var o=D(t[1]);return o||(console.warn(O.replace("{}",t[1])),console.warn("Falling back to no-highlight mode for this block.",e)),o?t[1]:"no-highlight"}for(n=0,r=(i=i.split(/\s+/)).length;n<r;n++)if(u(a=i[n])||D(a))return a}(e);u(o)||(B.useBR?(n=document.createElement("div")).innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n"):n=e,i=n.textContent,r=o?T(o,i,!0):w(i),(t=E(n)).length&&((a=document.createElement("div")).innerHTML=r.value,r.value=d(t,E(a),i)),r.value=M(r.value),e.innerHTML=r.value,e.className=function(e,n,t){var r=n?c[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}(e.className,o,r.language),e.result={language:r.language,re:r.relevance},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.relevance}))}function h(){if(!h.called){h.called=!0;var e=document.querySelectorAll("pre code");f.forEach.call(e,b)}}var N={disableAutodetect:!0};function D(e){return e=(e||"").toLowerCase(),_[e]||_[c[e]]}function L(e){var n=D(e);return n&&!n.disableAutodetect}return a.highlight=T,a.highlightAuto=w,a.fixMarkup=M,a.highlightBlock=b,a.configure=function(e){B=s(B,e)},a.initHighlighting=h,a.initHighlightingOnLoad=function(){window.addEventListener("DOMContentLoaded",h,!1),window.addEventListener("load",h,!1)},a.registerLanguage=function(n,e){var t;try{t=e(a)}catch(e){if(console.error("Language definition for '{}' could not be registered.".replace("{}",n)),!C)throw e;console.error(e),t=N}p(_[n]=t),t.rawDefinition=e.bind(null,a),t.aliases&&t.aliases.forEach(function(e){c[e]=n})},a.listLanguages=function(){return i(_)},a.getLanguage=D,a.requireLanguage=function(e){var n=D(e);if(n)return n;throw new Error("The '{}' language is required, but not loaded.".replace("{}",e))},a.autoDetection=L,a.inherit=s,a.debugMode=function(){C=!1},a.IR=a.IDENT_RE="[a-zA-Z]\\w*",a.UIR=a.UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",a.NR=a.NUMBER_RE="\\b\\d+(\\.\\d+)?",a.CNR=a.C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",a.BNR=a.BINARY_NUMBER_RE="\\b(0b[01]+)",a.RSR=a.RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",a.BE=a.BACKSLASH_ESCAPE={b:"\\\\[\\s\\S]",relevance:0},a.ASM=a.APOS_STRING_MODE={cN:"string",b:"'",e:"'",i:"\\n",c:[a.BE]},a.QSM=a.QUOTE_STRING_MODE={cN:"string",b:'"',e:'"',i:"\\n",c:[a.BE]},a.PWM=a.PHRASAL_WORDS_MODE={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},a.C=a.COMMENT=function(e,n,t){var r=a.inherit({cN:"comment",b:e,e:n,c:[]},t||{});return r.c.push(a.PWM),r.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",relevance:0}),r},a.CLCM=a.C_LINE_COMMENT_MODE=a.C("//","$"),a.CBCM=a.C_BLOCK_COMMENT_MODE=a.C("/\\*","\\*/"),a.HCM=a.HASH_COMMENT_MODE=a.C("#","$"),a.NM=a.NUMBER_MODE={cN:"number",b:a.NR,relevance:0},a.CNM=a.C_NUMBER_MODE={cN:"number",b:a.CNR,relevance:0},a.BNM=a.BINARY_NUMBER_MODE={cN:"number",b:a.BNR,relevance:0},a.CSSNM=a.CSS_NUMBER_MODE={cN:"number",b:a.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},a.RM=a.REGEXP_MODE={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[a.BE,{b:/\[/,e:/\]/,relevance:0,c:[a.BE]}]},a.TM=a.TITLE_MODE={cN:"title",b:a.IR,relevance:0},a.UTM=a.UNDERSCORE_TITLE_MODE={cN:"title",b:a.UIR,relevance:0},a.METHOD_GUARD={b:"\\.\\s*"+a.UIR,relevance:0},[a.BE,a.ASM,a.QSM,a.PWM,a.C,a.CLCM,a.CBCM,a.HCM,a.NM,a.CNM,a.BNM,a.CSSNM,a.RM,a.TM,a.UTM,a.METHOD_GUARD].forEach(function(e){!function n(t){Object.freeze(t);var r="function"==typeof t;Object.getOwnPropertyNames(t).forEach(function(e){!t.hasOwnProperty(e)||null===t[e]||"object"!=typeof t[e]&&"function"!=typeof t[e]||r&&("caller"===e||"callee"===e||"arguments"===e)||Object.isFrozen(t[e])||n(t[e])});return t}(e)}),a});hljs.registerLanguage("swift",function(e){var i={keyword:"#available #colorLiteral #column #else #elseif #endif #file #fileLiteral #function #if #imageLiteral #line #selector #sourceLocation _ __COLUMN__ __FILE__ __FUNCTION__ __LINE__ Any as as! as? associatedtype associativity break case catch class continue convenience default defer deinit didSet do dynamic dynamicType else enum extension fallthrough false fileprivate final for func get guard if import in indirect infix init inout internal is lazy left let mutating nil none nonmutating open operator optional override postfix precedence prefix private protocol Protocol public repeat required rethrows return right self Self set static struct subscript super switch throw throws true try try! try? Type typealias unowned var weak where while willSet",literal:"true false nil",built_in:"abs advance alignof alignofValue anyGenerator assert assertionFailure bridgeFromObjectiveC bridgeFromObjectiveCUnconditional bridgeToObjectiveC bridgeToObjectiveCUnconditional c contains count countElements countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump encodeBitsAsWords enumerate equal fatalError filter find getBridgedObjectiveCType getVaList indices insertionSort isBridgedToObjectiveC isBridgedVerbatimToObjectiveC isUniquelyReferenced isUniquelyReferencedNonObjC join lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition posix precondition preconditionFailure print println quickSort readLine reduce reflect reinterpretCast reverse roundUpToAlignment sizeof sizeofValue sort split startsWith stride strideof strideofValue swap toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast unsafeUnwrap unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer withUnsafePointerToObject withUnsafeMutablePointer withUnsafeMutablePointers withUnsafePointer withUnsafePointers withVaList zip"},t=e.C("/\\*","\\*/",{c:["self"]}),n={cN:"subst",b:/\\\(/,e:"\\)",k:i,c:[]},r={cN:"string",c:[e.BE,n],v:[{b:/"""/,e:/"""/},{b:/"/,e:/"/}]},a={cN:"number",b:"\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b",relevance:0};return n.c=[a],{k:i,c:[r,e.CLCM,t,{cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*[!?]"},{cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*",relevance:0},a,{cN:"function",bK:"func",e:"{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{b:/</,e:/>/},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:i,c:["self",a,r,e.CBCM,{b:":"}],i:/["']/}],i:/\[|%/},{cN:"class",bK:"struct protocol class extension enum",k:i,e:"\\{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/})]},{cN:"meta",b:"(@discardableResult|@warn_unused_result|@exported|@lazy|@noescape|@NSCopying|@NSManaged|@objc|@objcMembers|@convention|@required|@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|@infix|@prefix|@postfix|@autoclosure|@testable|@available|@nonobjc|@NSApplicationMain|@UIApplicationMain|@dynamicMemberLookup|@propertyWrapper)"},{bK:"import",e:/$/,c:[e.CLCM,t]}]}});hljs.registerLanguage("less",function(e){function r(e){return{cN:"string",b:"~?"+e+".*?"+e}}function t(e,r,t){return{cN:e,b:r,relevance:t}}var a="[\\w-]+",c="("+a+"|@{"+a+"})",s=[],n=[],b={b:"\\(",e:"\\)",c:n,relevance:0};n.push(e.CLCM,e.CBCM,r("'"),r('"'),e.CSSNM,{b:"(url|data-uri)\\(",starts:{cN:"string",e:"[\\)\\n]",eE:!0}},t("number","#[0-9A-Fa-f]+\\b"),b,t("variable","@@?"+a,10),t("variable","@{"+a+"}"),t("built_in","~?`[^`]*?`"),{cN:"attribute",b:a+"\\s*:",e:":",rB:!0,eE:!0},{cN:"meta",b:"!important"});var i=n.concat({b:"{",e:"}",c:s}),l={bK:"when",eW:!0,c:[{bK:"and not"}].concat(n)},o={b:c+"\\s*:",rB:!0,e:"[;}]",relevance:0,c:[{cN:"attribute",b:c,e:":",eE:!0,starts:{eW:!0,i:"[<=$]",relevance:0,c:n}}]},u={cN:"keyword",b:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{e:"[;{}]",rE:!0,c:n,relevance:0}},v={cN:"variable",v:[{b:"@"+a+"\\s*:",relevance:15},{b:"@"+a}],starts:{e:"[;}]",rE:!0,c:i}},C={v:[{b:"[\\.#:&\\[>]",e:"[;{}]"},{b:c,e:"{"}],rB:!0,rE:!0,i:"[<='$\"]",relevance:0,c:[e.CLCM,e.CBCM,l,t("keyword","all\\b"),t("variable","@{"+a+"}"),t("selector-tag",c+"%?",0),t("selector-id","#"+c),t("selector-class","\\."+c,0),t("selector-tag","&",0),{cN:"selector-attr",b:"\\[",e:"\\]"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"\\(",e:"\\)",c:i},{b:"!important"}]};return s.push(e.CLCM,e.CBCM,u,v,o,C),{cI:!0,i:"[=>'/<($\"]",c:s}});hljs.registerLanguage("ruby",function(e){var c="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},r={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},n=[e.C("#","$",{c:[r]}),e.C("^\\=begin","^\\=end",{c:[r],relevance:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:b},t={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<[-~]?'?(\w+)(?:.|\n)*?\n\s*\1\b/,rB:!0,c:[{b:/<<[-~]?'?/},{b:/\w+/,endSameAsBegin:!0,c:[e.BE,s]}]}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:b},l=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(n)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:c}),i].concat(n)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",relevance:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:c}],relevance:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:b},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(n),relevance:0}].concat(n);s.c=l;var d=[{b:/^\s*=>/,starts:{e:"$",c:i.c=l}},{cN:"meta",b:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:b,i:/\/\*/,c:n.concat(d).concat(l)}});hljs.registerLanguage("lua",function(e){var t="\\[=*\\[",a="\\]=*\\]",n={b:t,e:a,c:["self"]},l=[e.C("--(?!"+t+")","$"),e.C("--"+t,a,{c:[n],relevance:10})];return{l:e.UIR,k:{literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstringmodule next pairs pcall print rawequal rawget rawset require select setfenvsetmetatable tonumber tostring type unpack xpcall arg selfcoroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},c:l.concat([{cN:"function",bK:"function",e:"\\)",c:[e.inherit(e.TM,{b:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{cN:"params",b:"\\(",eW:!0,c:l}].concat(l)},e.CNM,e.ASM,e.QSM,{cN:"string",b:t,e:a,c:[n],relevance:5}])}});hljs.registerLanguage("matlab",function(e){var a="('|\\.')+",s={relevance:0,c:[{b:a}]};return{k:{keyword:"break case catch classdef continue else elseif end enumerated events for function global if methods otherwise parfor persistent properties return spmd switch try while",built_in:"sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i inf nan isnan isinf isfinite j why compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun legend intersect ismember procrustes hold num2cell "},i:'(//|"|#|/\\*|\\s+/\\w+)',c:[{cN:"function",bK:"function",e:"$",c:[e.UTM,{cN:"params",v:[{b:"\\(",e:"\\)"},{b:"\\[",e:"\\]"}]}]},{cN:"built_in",b:/true|false/,relevance:0,starts:s},{b:"[a-zA-Z][a-zA-Z_0-9]*"+a,relevance:0},{cN:"number",b:e.CNR,relevance:0,starts:s},{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{b:/\]|}|\)/,relevance:0,starts:s},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}],starts:s},e.C("^\\s*\\%\\{\\s*$","^\\s*\\%\\}\\s*$"),e.C("\\%","$")]}});hljs.registerLanguage("apache",function(e){var r={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:"</?",e:">"},{cN:"attribute",b:/\w+/,relevance:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,relevance:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",r]},r,e.QSM]}}],i:/\S/}});hljs.registerLanguage("yaml",function(e){var b="true false yes no null",a={cN:"string",relevance:0,v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/\S+/}],c:[e.BE,{cN:"template-variable",v:[{b:"{{",e:"}}"},{b:"%{",e:"}"}]}]};return{cI:!0,aliases:["yml","YAML","yaml"],c:[{cN:"attr",v:[{b:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{b:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{b:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{cN:"meta",b:"^---s*$",relevance:10},{cN:"string",b:"[\\|>]([0-9]?[+-])?[ ]*\\n( *)[\\S ]+\\n(\\2[\\S ]+\\n?)*"},{b:"<%[%=-]?",e:"[%-]?%>",sL:"ruby",eB:!0,eE:!0,relevance:0},{cN:"type",b:"!"+e.UIR},{cN:"type",b:"!!"+e.UIR},{cN:"meta",b:"&"+e.UIR+"$"},{cN:"meta",b:"\\*"+e.UIR+"$"},{cN:"bullet",b:"\\-(?=[ ]|$)",relevance:0},e.HCM,{bK:b,k:{literal:b}},{cN:"number",b:e.CNR+"\\b"},a]}});hljs.registerLanguage("plaintext",function(e){return{disableAutodetect:!0}});hljs.registerLanguage("puppet",function(e){var s=e.C("#","$"),r="([A-Za-z_]|::)(\\w|::)*",a=e.inherit(e.TM,{b:r}),i={cN:"variable",b:"\\$"+r},n={cN:"string",c:[e.BE,i],v:[{b:/'/,e:/'/},{b:/"/,e:/"/}]};return{aliases:["pp"],c:[s,i,n,{bK:"class",e:"\\{|;",i:/=/,c:[a,s]},{bK:"define",e:/\{/,c:[{cN:"section",b:e.IR,endsParent:!0}]},{b:e.IR+"\\s+\\{",rB:!0,e:/\S/,c:[{cN:"keyword",b:e.IR},{b:/\{/,e:/\}/,k:{keyword:"and case default else elsif false if in import enherits node or true undef unless main settings $string ",literal:"alias audit before loglevel noop require subscribe tag owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check en_address ip_address realname command environment hour monute month monthday special target weekday creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey sslverify mounted",built_in:"architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version"},relevance:0,c:[n,s,{b:"[a-zA-Z_]+\\s*=>",rB:!0,e:"=>",c:[{cN:"attr",b:e.IR}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},i]}],relevance:0}]}});hljs.registerLanguage("xml",function(e){var c={cN:"symbol",b:"&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;"},s={b:"\\s",c:[{cN:"meta-keyword",b:"#?[a-z_][a-z1-9_-]+",i:"\\n"}]},a=e.inherit(s,{b:"\\(",e:"\\)"}),t=e.inherit(e.ASM,{cN:"meta-string"}),l=e.inherit(e.QSM,{cN:"meta-string"}),r={eW:!0,i:/</,relevance:0,c:[{cN:"attr",b:"[A-Za-z0-9\\._:-]+",relevance:0},{b:/=\s*/,relevance:0,c:[{cN:"string",endsParent:!0,v:[{b:/"/,e:/"/,c:[c]},{b:/'/,e:/'/,c:[c]},{b:/[^\s"'=<>`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],cI:!0,c:[{cN:"meta",b:"<![a-z]",e:">",relevance:10,c:[s,l,t,a,{b:"\\[",e:"\\]",c:[{cN:"meta",b:"<![a-z]",e:">",c:[s,a,l,t]}]}]},e.C("\x3c!--","--\x3e",{relevance:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",relevance:10},c,{cN:"meta",b:/<\?xml/,e:/\?>/,relevance:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0},{b:'b"',e:'"',skip:!0},{b:"b'",e:"'",skip:!0},e.inherit(e.ASM,{i:null,cN:null,c:null,skip:!0}),e.inherit(e.QSM,{i:null,cN:null,c:null,skip:!0})]},{cN:"tag",b:"<style(?=\\s|>)",e:">",k:{name:"style"},c:[r],starts:{e:"</style>",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"<script(?=\\s|>)",e:">",k:{name:"script"},c:[r],starts:{e:"<\/script>",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"name",b:/[^\/><\s]+/,relevance:0},r]}]}});hljs.registerLanguage("twig",function(e){var t="attribute block constant cycle date dump include max min parent random range source template_from_string",a={bK:t,k:{name:t},relevance:0,c:[{cN:"params",b:"\\(",e:"\\)"}]},r={b:/\|[A-Za-z_]+:?/,k:"abs batch capitalize column convert_encoding date date_modify default escape filter first format inky_to_html inline_css join json_encode keys last length lower map markdown merge nl2br number_format raw reduce replace reverse round slice sort spaceless split striptags title trim upper url_encode",c:[a]},c="apply autoescape block deprecated do embed extends filter flush for from if import include macro sandbox set use verbatim with";return c=c+" "+c.split(" ").map(function(e){return"end"+e}).join(" "),{aliases:["craftcms"],cI:!0,sL:"xml",c:[e.C(/\{#/,/#}/),{cN:"template-tag",b:/\{%/,e:/%}/,c:[{cN:"name",b:/\w+/,k:c,starts:{eW:!0,c:[r,a],relevance:0}}]},{cN:"template-variable",b:/\{\{/,e:/}}/,c:["self",r,a]}]}});hljs.registerLanguage("kotlin",function(e){var t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual trait volatile transient native default",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},a={cN:"symbol",b:e.UIR+"@"},n={cN:"subst",b:"\\${",e:"}",c:[e.CNM]},c={cN:"variable",b:"\\$"+e.UIR},r={cN:"string",v:[{b:'"""',e:'"""(?=[^"])',c:[c,n]},{b:"'",e:"'",i:/\n/,c:[e.BE]},{b:'"',e:'"',i:/\n/,c:[e.BE,c,n]}]};n.c.push(r);var i={cN:"meta",b:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UIR+")?"},l={cN:"meta",b:"@"+e.UIR,c:[{b:/\(/,e:/\)/,c:[e.inherit(r,{cN:"meta-string"})]}]},s={cN:"number",b:"\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",relevance:0},b=e.C("/\\*","\\*/",{c:[e.CBCM]}),o={v:[{cN:"type",b:e.UIR},{b:/\(/,e:/\)/,c:[]}]},d=o;return d.v[1].c=[o],o.v[1].c=[d],{aliases:["kt"],k:t,c:[e.C("/\\*\\*","\\*/",{relevance:0,c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,b,{cN:"keyword",b:/\b(break|continue|return|this)\b/,starts:{c:[{cN:"symbol",b:/@\w+/}]}},a,i,l,{cN:"function",bK:"fun",e:"[(]|$",rB:!0,eE:!0,k:t,i:/fun\s+(<.*>)?[^\s\(]+(\s+[^\s\(]+)\s*=/,relevance:5,c:[{b:e.UIR+"\\s*\\(",rB:!0,relevance:0,c:[e.UTM]},{cN:"type",b:/</,e:/>/,k:"reified",relevance:0},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:t,relevance:0,c:[{b:/:/,e:/[=,\/]/,eW:!0,c:[o,e.CLCM,b],relevance:0},e.CLCM,b,i,l,r,e.CNM]},b]},{cN:"class",bK:"class interface trait",e:/[:\{(]|$/,eE:!0,i:"extends implements",c:[{bK:"public protected internal private constructor"},e.UTM,{cN:"type",b:/</,e:/>/,eB:!0,eE:!0,relevance:0},{cN:"type",b:/[,:]\s*/,e:/[<\(,]|$/,eB:!0,rE:!0},i,l]},r,{cN:"meta",b:"^#!/usr/bin/env",e:"$",i:"\n"},s]}});hljs.registerLanguage("javascript",function(e){var r="<>",a="</>",t={b:/<[A-Za-z0-9\\._:-]+/,e:/\/[A-Za-z0-9\\._:-]+>|\/>/},c="[A-Za-z$_][0-9A-Za-z$_]*",n={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},s={cN:"number",v:[{b:"\\b(0[bB][01]+)n?"},{b:"\\b(0[oO][0-7]+)n?"},{b:e.CNR+"n?"}],relevance:0},o={cN:"subst",b:"\\$\\{",e:"\\}",k:n,c:[]},i={b:"html`",e:"",starts:{e:"`",rE:!1,c:[e.BE,o],sL:"xml"}},b={b:"css`",e:"",starts:{e:"`",rE:!1,c:[e.BE,o],sL:"css"}},l={cN:"string",b:"`",e:"`",c:[e.BE,o]};o.c=[e.ASM,e.QSM,i,b,l,s,e.RM];var u=o.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx","mjs","cjs"],k:n,c:[{cN:"meta",relevance:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,i,b,l,e.CLCM,e.C("/\\*\\*","\\*/",{relevance:0,c:[{cN:"doctag",b:"@[A-Za-z]+",c:[{cN:"type",b:"\\{",e:"\\}",relevance:0},{cN:"variable",b:c+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{b:/(?=[^\n])\s/,relevance:0}]}]}),e.CBCM,s,{b:/[{,\n]\s*/,relevance:0,c:[{b:c+"\\s*:",rB:!0,relevance:0,c:[{cN:"attr",b:c,relevance:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+c+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:c},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:n,c:u}]}]},{cN:"",b:/\s/,e:/\s*/,skip:!0},{v:[{b:r,e:a},{b:t.b,e:t.e}],sL:"xml",c:[{b:t.b,e:t.e,skip:!0,c:["self"]}]}],relevance:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:c}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:u}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor get set",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("scss",function(e){var t="@[a-z-]+",r={cN:"variable",b:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b"},i={cN:"number",b:"#[0-9A-Fa-f]+"};e.CSSNM,e.QSM,e.ASM,e.CBCM;return{cI:!0,i:"[=/|']",c:[e.CLCM,e.CBCM,{cN:"selector-id",b:"\\#[A-Za-z0-9_-]+",relevance:0},{cN:"selector-class",b:"\\.[A-Za-z0-9_-]+",relevance:0},{cN:"selector-attr",b:"\\[",e:"\\]",i:"$"},{cN:"selector-tag",b:"\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|frame|frameset|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|samp|script|section|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|tt|ul|var|video)\\b",relevance:0},{cN:"selector-pseudo",b:":(visited|valid|root|right|required|read-write|read-only|out-range|optional|only-of-type|only-child|nth-of-type|nth-last-of-type|nth-last-child|nth-child|not|link|left|last-of-type|last-child|lang|invalid|indeterminate|in-range|hover|focus|first-of-type|first-line|first-letter|first-child|first|enabled|empty|disabled|default|checked|before|after|active)"},{cN:"selector-pseudo",b:"::(after|before|choices|first-letter|first-line|repeat-index|repeat-item|selection|value)"},r,{cN:"attribute",b:"\\b(src|z-index|word-wrap|word-spacing|word-break|width|widows|white-space|visibility|vertical-align|unicode-bidi|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform-style|transform-origin|transform|top|text-underline-position|text-transform|text-shadow|text-rendering|text-overflow|text-indent|text-decoration-style|text-decoration-line|text-decoration-color|text-decoration|text-align-last|text-align|tab-size|table-layout|right|resize|quotes|position|pointer-events|perspective-origin|perspective|page-break-inside|page-break-before|page-break-after|padding-top|padding-right|padding-left|padding-bottom|padding|overflow-y|overflow-x|overflow-wrap|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|order|opacity|object-position|object-fit|normal|none|nav-up|nav-right|nav-left|nav-index|nav-down|min-width|min-height|max-width|max-height|mask|marks|margin-top|margin-right|margin-left|margin-bottom|margin|list-style-type|list-style-position|list-style-image|list-style|line-height|letter-spacing|left|justify-content|initial|inherit|ime-mode|image-orientation|image-resolution|image-rendering|icon|hyphens|height|font-weight|font-variant-ligatures|font-variant|font-style|font-stretch|font-size-adjust|font-size|font-language-override|font-kerning|font-feature-settings|font-family|font|float|flex-wrap|flex-shrink|flex-grow|flex-flow|flex-direction|flex-basis|flex|filter|empty-cells|display|direction|cursor|counter-reset|counter-increment|content|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|columns|color|clip-path|clip|clear|caption-side|break-inside|break-before|break-after|box-sizing|box-shadow|box-decoration-break|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-left-width|border-left-style|border-left-color|border-left|border-image-width|border-image-source|border-image-slice|border-image-repeat|border-image-outset|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-attachment|background-blend-mode|background|backface-visibility|auto|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|align-self|align-items|align-content)\\b",i:"[^\\s]"},{b:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{b:":",e:";",c:[r,i,e.CSSNM,e.QSM,e.ASM,{cN:"meta",b:"!important"}]},{b:"@(page|font-face)",l:t,k:"@page @font-face"},{b:"@",e:"[{;]",rB:!0,k:"and or not only",c:[{b:t,cN:"keyword"},r,e.QSM,e.ASM,i,e.CSSNM]}]}});hljs.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},s={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,relevance:0}]},c=[e.BE,r,n],a=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),s,{cN:"string",c:c,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",relevance:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",relevance:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",relevance:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",relevance:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",relevance:5},{b:"qw\\s+q",e:"q",relevance:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],relevance:0},{b:"-?\\w+\\s*\\=\\>",c:[],relevance:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",relevance:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",relevance:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],relevance:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,relevance:5,c:[e.TM]},{b:"-\\w\\b",relevance:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=a,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:s.c=a}});hljs.registerLanguage("go",function(e){var n={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:n,i:"</",c:[e.CLCM,e.CBCM,{cN:"string",v:[e.QSM,e.ASM,{b:"`",e:"`"}]},{cN:"number",v:[{b:e.CNR+"[i]",relevance:1},e.CNM]},{b:/:=/},{cN:"function",bK:"func",e:"\\s*(\\{|$)",eE:!0,c:[e.TM,{cN:"params",b:/\(/,e:/\)/,k:n,i:/["']/}]}]}});hljs.registerLanguage("gauss",function(o){function e(e,t,a){var r=o.inherit({cN:"function",bK:e,e:t,eE:!0,c:[].concat(d)},a||{});return r.c.push(l),r.c.push(o.CNM),r.c.push(o.CBCM),r.c.push(n),r}var t={keyword:"bool break call callexe checkinterrupt clear clearg closeall cls comlog compile continue create debug declare delete disable dlibrary dllcall do dos ed edit else elseif enable end endfor endif endp endo errorlog errorlogat expr external fn for format goto gosub graph if keyword let lib library line load loadarray loadexe loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen scroll setarray show sparse stop string struct system trace trap threadfor threadendfor threadbegin threadjoin threadstat threadend until use while winprint ne ge le gt lt and xor or not eq eqv",built_in:"abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester strtrim",literal:"DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR"},n=o.C("@","@"),a={cN:"meta",b:"#",e:"$",k:{"meta-keyword":"define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline"},c:[{b:/\\\n/,relevance:0},{bK:"include",e:"$",k:{"meta-keyword":"include"},c:[{cN:"meta-string",b:'"',e:'"',i:"\\n"}]},o.CLCM,o.CBCM,n]},r={b:/\bstruct\s+/,e:/\s/,k:"struct",c:[{cN:"type",b:o.UIR,relevance:0}]},d=[{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,eW:!0,relevance:0,c:[{cN:"literal",b:/\.\.\./},o.CNM,o.CBCM,n,r]}],l={cN:"title",b:o.UIR,relevance:0},s={cN:"built_in",b:"\\b("+t.built_in.split(" ").join("|")+")\\b"},i={cN:"string",b:'"',e:'"',c:[o.BE],relevance:0},c={b:o.UIR+"\\s*\\(",rB:!0,k:t,relevance:0,c:[{bK:t.keyword},s,{cN:"built_in",b:o.UIR,relevance:0}]},p={b:/\(/,e:/\)/,relevance:0,k:{built_in:t.built_in,literal:t.literal},c:[o.CNM,o.CBCM,n,s,c,i,"self"]};return c.c.push(p),{aliases:["gss"],cI:!0,k:t,i:/(\{[%#]|[%#]\}| <- )/,c:[o.CNM,o.CLCM,o.CBCM,n,i,a,{cN:"keyword",b:/\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/},e("proc keyword",";"),e("fn","="),{bK:"for threadfor",e:/;/,relevance:0,c:[o.CBCM,n,p]},{v:[{b:o.UIR+"\\."+o.UIR},{b:o.UIR+"\\s*="}],relevance:0},c,r]}});hljs.registerLanguage("cpp",function(e){function t(e){return"(?:"+e+")?"}var r="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",i="("+r+"|"+t(a)+"[a-zA-Z_]\\w*"+t("<.*?>")+")",c={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},s={cN:"string",v:[{b:'(u8?|U|L)?"',e:'"',i:"\\n",c:[e.BE]},{b:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",e:"'",i:"."},{b:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\((?:.|\n)*?\)\1"/}]},n={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},o={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},c:[{b:/\\\n/,relevance:0},e.inherit(s,{cN:"meta-string"}),{cN:"meta-string",b:/<.*?>/,e:/$/,i:"\\n"},e.CLCM,e.CBCM]},l={cN:"title",b:t(a)+e.IR,relevance:0},u=t(a)+e.IR+"\\s*\\(",p={keyword:"int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_tshort reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr _Bool complex _Complex imaginary _Imaginary",literal:"true false nullptr NULL"},m=[c,e.CLCM,e.CBCM,n,s],d={v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:p,c:m.concat([{b:/\(/,e:/\)/,k:p,c:m.concat(["self"]),relevance:0}]),relevance:0},b={cN:"function",b:"("+i+"[\\*&\\s]+)+"+u,rB:!0,e:/[{;=]/,eE:!0,k:p,i:/[^\w\s\*&:<>]/,c:[{b:r,k:p,relevance:0},{b:u,rB:!0,c:[l],relevance:0},{cN:"params",b:/\(/,e:/\)/,k:p,relevance:0,c:[e.CLCM,e.CBCM,s,n,c,{b:/\(/,e:/\)/,k:p,relevance:0,c:["self",e.CLCM,e.CBCM,s,n,c]}]},c,e.CLCM,e.CBCM,o]};return{aliases:["c","cc","h","c++","h++","hpp","hh","hxx","cxx"],k:p,i:"</",c:[].concat(d,b,m,[o,{b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:p,c:["self",c]},{b:e.IR+"::",k:p},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b:/</,e:/>/,c:["self"]},e.TM]}]),exports:{preprocessor:o,strings:s,k:p}}});hljs.registerLanguage("x86asm",function(s){return{cI:!0,l:"[.%]?"+s.IR,k:{keyword:"lock rep repe repz repne repnz xaquire xrelease bnd nobnd aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63",built_in:"ip eip rip al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 cs ds es fs gs ss st st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ymm0 ymm1 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9 ymm10 ymm11 ymm12 ymm13 ymm14 ymm15 ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 zmm0 zmm1 zmm2 zmm3 zmm4 zmm5 zmm6 zmm7 zmm8 zmm9 zmm10 zmm11 zmm12 zmm13 zmm14 zmm15 zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 k0 k1 k2 k3 k4 k5 k6 k7 bnd0 bnd1 bnd2 bnd3 cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d r0h r1h r2h r3h r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l db dw dd dq dt ddq do dy dz resb resw resd resq rest resdq reso resy resz incbin equ times byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr",meta:"%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif %if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep %endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment .nolist __FILE__ __LINE__ __SECT__ __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ __UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__ __PASS__ struc endstruc istruc at iend align alignb sectalign daz nodaz up down zero default option assume public bits use16 use32 use64 default section segment absolute extern global common cpu float __utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ __float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ __Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__"},c:[s.C(";","$",{relevance:0}),{cN:"number",v:[{b:"\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|(0[Xx])?[0-9][0-9_]*\\.?[0-9_]*(?:[pP](?:[+-]?[0-9_]+)?)?)\\b",relevance:0},{b:"\\$[0-9][0-9A-Fa-f]*",relevance:0},{b:"\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b"},{b:"\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b"}]},s.QSM,{cN:"string",v:[{b:"'",e:"[^\\\\]'"},{b:"`",e:"[^\\\\]`"}],relevance:0},{cN:"symbol",v:[{b:"^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)"},{b:"^\\s*%%[A-Za-z0-9_$#@~.?]*:"}],relevance:0},{cN:"subst",b:"%[0-9]+",relevance:0},{cN:"subst",b:"%!S+",relevance:0},{cN:"meta",b:/^\s*\.[\w_-]+/}]}});hljs.registerLanguage("vbnet",function(e){return{aliases:["vb"],cI:!0,k:{keyword:"addhandler addressof alias and andalso aggregate ansi as async assembly auto await binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into is isfalse isnot istrue iterator join key let lib like loop me mid mod module mustinherit mustoverride mybase myclass nameof namespace narrowing new next not notinheritable notoverridable of off on operator option optional or order orelse overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim rem removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly xor yield",built_in:"boolean byte cbool cbyte cchar cdate cdec cdbl char cint clng cobj csbyte cshort csng cstr ctype date decimal directcast double gettype getxmlnamespace iif integer long object sbyte short single string trycast typeof uinteger ulong ushort",literal:"true false nothing"},i:"//|{|}|endif|gosub|variant|wend|^\\$ ",c:[e.inherit(e.QSM,{c:[{b:'""'}]}),e.C("'","$",{rB:!0,c:[{cN:"doctag",b:"'''|\x3c!--|--\x3e",c:[e.PWM]},{cN:"doctag",b:"</?",e:">",c:[e.PWM]}]}),e.CNM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elseif end region externalsource"}}]}});hljs.registerLanguage("scala",function(e){var t={cN:"subst",v:[{b:"\\$[A-Za-z0-9_]+"},{b:"\\${",e:"}"}]},a={cN:"string",v:[{b:'"',e:'"',i:"\\n",c:[e.BE]},{b:'"""',e:'"""',relevance:10},{b:'[a-z]+"',e:'"',i:"\\n",c:[e.BE,t]},{cN:"string",b:'[a-z]+"""',e:'"""',c:[t],relevance:10}]},c={cN:"type",b:"\\b[A-Z][A-Za-z0-9_]*",relevance:0},r={cN:"title",b:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,relevance:0},n={cN:"class",bK:"class object trait type",e:/[:={\[\n;]/,eE:!0,c:[{bK:"extends with",relevance:10},{b:/\[/,e:/\]/,eB:!0,eE:!0,relevance:0,c:[c]},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,relevance:0,c:[c]},r]},l={cN:"function",bK:"def",e:/[:={\[(\n;]/,eE:!0,c:[r]};return{k:{literal:"true false null",keyword:"type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit"},c:[e.CLCM,e.CBCM,a,{cN:"symbol",b:"'\\w[\\w\\d_]*(?!')"},c,l,n,e.CNM,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("arduino",function(e){var t="boolean byte word String",r="setup loopKeyboardController MouseController SoftwareSerial EthernetServer EthernetClient LiquidCrystal RobotControl GSMVoiceCall EthernetUDP EsploraTFT HttpClient RobotMotor WiFiClient GSMScanner FileSystem Scheduler GSMServer YunClient YunServer IPAddress GSMClient GSMModem Keyboard Ethernet Console GSMBand Esplora Stepper Process WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage Client Server GSMPIN FileIO Bridge Serial EEPROM Stream Mouse Audio Servo File Task GPRS WiFi Wire TFT GSM SPI SD runShellCommandAsynchronously analogWriteResolution retrieveCallingNumber printFirmwareVersion analogReadResolution sendDigitalPortPair noListenOnLocalhost readJoystickButton setFirmwareVersion readJoystickSwitch scrollDisplayRight getVoiceCallStatus scrollDisplayLeft writeMicroseconds delayMicroseconds beginTransmission getSignalStrength runAsynchronously getAsynchronously listenOnLocalhost getCurrentCarrier readAccelerometer messageAvailable sendDigitalPorts lineFollowConfig countryNameWrite runShellCommand readStringUntil rewindDirectory readTemperature setClockDivider readLightSensor endTransmission analogReference detachInterrupt countryNameRead attachInterrupt encryptionType readBytesUntil robotNameWrite readMicrophone robotNameRead cityNameWrite userNameWrite readJoystickY readJoystickX mouseReleased openNextFile scanNetworks noInterrupts digitalWrite beginSpeaker mousePressed isActionDone mouseDragged displayLogos noAutoscroll addParameter remoteNumber getModifiers keyboardRead userNameRead waitContinue processInput parseCommand printVersion readNetworks writeMessage blinkVersion cityNameRead readMessage setDataMode parsePacket isListening setBitOrder beginPacket isDirectory motorsWrite drawCompass digitalRead clearScreen serialEvent rightToLeft setTextSize leftToRight requestFrom keyReleased compassRead analogWrite interrupts WiFiServer disconnect playMelody parseFloat autoscroll getPINUsed setPINUsed setTimeout sendAnalog readSlider analogRead beginWrite createChar motorsStop keyPressed tempoWrite readButton subnetMask debugPrint macAddress writeGreen randomSeed attachGPRS readString sendString remotePort releaseAll mouseMoved background getXChange getYChange answerCall getResult voiceCall endPacket constrain getSocket writeJSON getButton available connected findUntil readBytes exitValue readGreen writeBlue startLoop IPAddress isPressed sendSysex pauseMode gatewayIP setCursor getOemKey tuneWrite noDisplay loadImage switchPIN onRequest onReceive changePIN playFile noBuffer parseInt overflow checkPIN knobRead beginTFT bitClear updateIR bitWrite position writeRGB highByte writeRed setSpeed readBlue noStroke remoteIP transfer shutdown hangCall beginSMS endWrite attached maintain noCursor checkReg checkPUK shiftOut isValid shiftIn pulseIn connect println localIP pinMode getIMEI display noBlink process getBand running beginSD drawBMP lowByte setBand release bitRead prepare pointTo readRed setMode noFill remove listen stroke detach attach noTone exists buffer height bitSet circle config cursor random IRread setDNS endSMS getKey micros millis begin print write ready flush width isPIN blink clear press mkdir rmdir close point yield image BSSID click delay read text move peek beep rect line open seek fill size turn stop home find step tone sqrt RSSI SSID end bit tan cos sin pow map abs max min get run put",i="DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL DEFAULT OUTPUT INPUT HIGH LOW",o=e.requireLanguage("cpp").rawDefinition(),a=o.k;return a.keyword+=" "+t,a.literal+=" "+i,a.built_in+=" "+r,o});hljs.registerLanguage("handlebars",function(e){var t={"builtin-name":"each in with if else unless bindattr action collection debugger log outlet template unbound view yield lookup"},a={b:/".*?"|'.*?'|\[.*?\]|\w+/},l=e.inherit(a,{k:t,starts:{eW:!0,relevance:0,c:[e.inherit(a,{relevance:0})]}}),i=e.inherit(l,{cN:"name"}),n=e.inherit(l,{relevance:0});return{aliases:["hbs","html.hbs","html.handlebars"],cI:!0,sL:"xml",c:[{b:/\\\{\{/,skip:!0},{b:/\\\\(?=\{\{)/,skip:!0},e.C(/\{\{!--/,/--\}\}/),e.C(/\{\{!/,/\}\}/),{cN:"template-tag",b:/\{\{\{\{(?!\/)/,e:/\}\}\}\}/,c:[i],starts:{e:/\{\{\{\{\//,rE:!0,sL:"xml"}},{cN:"template-tag",b:/\{\{\{\{\//,e:/\}\}\}\}/,c:[i]},{cN:"template-tag",b:/\{\{[#\/]/,e:/\}\}/,c:[i]},{cN:"template-variable",b:/\{\{\{/,e:/\}\}\}/,k:t,c:[n]},{cN:"template-variable",b:/\{\{/,e:/\}\}/,k:t,c:[n]}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},relevance:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",relevance:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],relevance:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],relevance:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",relevance:0},{cN:"bullet",b:"^\\s*([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",relevance:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```\\w*\\s*$",e:"^```[ ]*$"},{b:"`.+?`"},{b:"^( {4}|\\t)",e:"$",relevance:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,relevance:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],relevance:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("lisp",function(e){var b="[a-zA-Z_\\-\\+\\*\\/\\<\\=\\>\\&\\#][a-zA-Z0-9_\\-\\+\\*\\/\\<\\=\\>\\&\\#!]*",c="\\|[^]*?\\|",a="(\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|\\-)?\\d+)?",l={cN:"literal",b:"\\b(t{1}|nil)\\b"},n={cN:"number",v:[{b:a,relevance:0},{b:"#(b|B)[0-1]+(/[0-1]+)?"},{b:"#(o|O)[0-7]+(/[0-7]+)?"},{b:"#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?"},{b:"#(c|C)\\("+a+" +"+a,e:"\\)"}]},r=e.inherit(e.QSM,{i:null}),i=e.C(";","$",{relevance:0}),t={b:"\\*",e:"\\*"},v={cN:"symbol",b:"[:&]"+b},s={b:b,relevance:0},u={b:c},d={c:[n,r,t,v,{b:"\\(",e:"\\)",c:["self",l,r,n,s]},s],v:[{b:"['`]\\(",e:"\\)"},{b:"\\(quote ",e:"\\)",k:{name:"quote"}},{b:"'"+c}]},f={v:[{b:"'"+b},{b:"#'"+b+"(::"+b+")*"}]},m={b:"\\(\\s*",e:"\\)"},o={eW:!0,relevance:0};return m.c=[{cN:"name",v:[{b:b},{b:c}]},o],o.c=[d,f,m,l,n,r,i,t,v,u,s],{i:/\S/,c:[n,{cN:"meta",b:"^#!",e:"$"},l,r,i,d,f,m,s]}});hljs.registerLanguage("properties",function(e){var r="[ \\t\\f]*",t="("+r+"[:=]"+r+"|[ \\t\\f]+)",n="([^\\\\\\W:= \\t\\f\\n]|\\\\.)+",a="([^\\\\:= \\t\\f\\n]|\\\\.)+",c={e:t,relevance:0,starts:{cN:"string",e:/$/,relevance:0,c:[{b:"\\\\\\n"}]}};return{cI:!0,i:/\S/,c:[e.C("^\\s*[!#]","$"),{b:n+t,rB:!0,c:[{cN:"attr",b:n,endsParent:!0,relevance:0}],starts:c},{b:a+t,rB:!0,relevance:0,c:[{cN:"meta",b:a,endsParent:!0,relevance:0}],starts:c},{cN:"attr",relevance:0,b:a+r+"$"}]}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},a={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,relevance:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],relevance:0},e.HCM,a,{cN:"",b:/\\"/},{cN:"string",b:/'/,e:/'/},t]}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env arg user onbuild stopsignal",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{e:/[^\\]$/,sL:"bash"}}],i:"</"}});hljs.registerLanguage("haml",function(e){return{cI:!0,c:[{cN:"meta",b:"^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$",relevance:10},e.C("^\\s*(!=#|=#|-#|/).*$",!1,{relevance:0}),{b:"^\\s*(-|=|!=)(?!#)",starts:{e:"\\n",sL:"ruby"}},{cN:"tag",b:"^\\s*%",c:[{cN:"selector-tag",b:"\\w+"},{cN:"selector-id",b:"#[\\w-]+"},{cN:"selector-class",b:"\\.[\\w-]+"},{b:"{\\s*",e:"\\s*}",c:[{b:":\\w+\\s*=>",e:",\\s+",rB:!0,eW:!0,c:[{cN:"attr",b:":\\w+"},e.ASM,e.QSM,{b:"\\w+",relevance:0}]}]},{b:"\\(\\s*",e:"\\s*\\)",eE:!0,c:[{b:"\\w+\\s*=",e:"\\s+",rB:!0,eW:!0,c:[{cN:"attr",b:"\\w+",relevance:0},e.ASM,e.QSM,{b:"\\w+",relevance:0}]}]}]},{b:"^\\s*[=~]\\s*"},{b:"#{",starts:{e:"}",sL:"ruby"}}]}});hljs.registerLanguage("python",function(e){var r={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10",built_in:"Ellipsis NotImplemented",literal:"False None True"},b={cN:"meta",b:/^(>>>|\.\.\.) /},c={cN:"subst",b:/\{/,e:/\}/,k:r,i:/#/},a={b:/\{\{/,relevance:0},l={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[e.BE,b],relevance:10},{b:/(u|b)?r?"""/,e:/"""/,c:[e.BE,b],relevance:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[e.BE,b,a,c]},{b:/(fr|rf|f)"""/,e:/"""/,c:[e.BE,b,a,c]},{b:/(u|r|ur)'/,e:/'/,relevance:10},{b:/(u|r|ur)"/,e:/"/,relevance:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[e.BE,a,c]},{b:/(fr|rf|f)"/,e:/"/,c:[e.BE,a,c]},e.ASM,e.QSM]},n={cN:"number",relevance:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},i={cN:"params",b:/\(/,e:/\)/,c:["self",b,n,l,e.HCM]};return c.c=[l,n,b],{aliases:["py","gyp","ipython"],k:r,i:/(<\/|->|\?)|=>/,c:[b,n,{bK:"if",relevance:0},l,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,i,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("django",function(e){var t={b:/\|[A-Za-z]+:?/,k:{name:"truncatewords removetags linebreaksbr yesno get_digit timesince random striptags filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort dictsortreversed default_if_none pluralize lower join center default truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize localtime utc timezone"},c:[e.QSM,e.ASM]};return{aliases:["jinja"],cI:!0,sL:"xml",c:[e.C(/\{%\s*comment\s*%}/,/\{%\s*endcomment\s*%}/),e.C(/\{#/,/#}/),{cN:"template-tag",b:/\{%/,e:/%}/,c:[{cN:"name",b:/\w+/,k:{name:"comment endcomment load templatetag ifchanged endifchanged if endif firstof for endfor ifnotequal endifnotequal widthratio extends include spaceless endspaceless regroup ifequal endifequal ssi now with cycle url filter endfilter debug block endblock else autoescape endautoescape csrf_token empty elif endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix plural get_current_language language get_available_languages get_current_language_bidi get_language_info get_language_info_list localize endlocalize localtime endlocaltime timezone endtimezone get_current_timezone verbatim"},starts:{eW:!0,k:"in by as",c:[t],relevance:0}}]},{cN:"template-variable",b:/\{\{/,e:/}}/,c:[t]}]}});hljs.registerLanguage("vbscript",function(e){return{aliases:["vbs"],cI:!0,k:{keyword:"call class const dim do loop erase execute executeglobal exit for each next function if then else on error option explicit new private property let get public randomize redim rem select case set stop sub while wend with end to elseif is or xor and not class_initialize class_terminate default preserve in me byval byref step resume goto",built_in:"lcase month vartype instrrev ubound setlocale getobject rgb getref string weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency conversions csng timevalue second year space abs clng timeserial fixs len asc isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim strcomp int createobject loadpicture tan formatnumber mid scriptenginebuildversion scriptengine split scriptengineminorversion cint sin datepart ltrim sqr scriptenginemajorversion time derived eval date formatpercent exp inputbox left ascw chrw regexp server response request cstr err",literal:"true false null nothing empty"},i:"//",c:[e.inherit(e.QSM,{c:[{b:'""'}]}),e.C(/'/,/$/,{relevance:0}),e.CNM]}});hljs.registerLanguage("ini",function(e){var b={cN:"number",relevance:0,v:[{b:/([\+\-]+)?[\d]+_[\d_]+/},{b:e.NR}]},a=e.C();a.v=[{b:/;/,e:/$/},{b:/#/,e:/$/}];var c={cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},r={cN:"literal",b:/\bon|off|true|false|yes|no\b/},n={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",relevance:10},{b:'"""',e:'"""',relevance:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[a,{cN:"section",b:/\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_\.-]+(?=\s*=\s*)/,cN:"attr",starts:{e:/$/,c:[a,{b:/\[/,e:/\]/,c:[a,r,c,n,b,"self"],relevance:0},r,c,n,b]}}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",relevance:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/^\*{15}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",relevance:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment values with",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select self semi sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null unknown",built_in:"array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp tinyint varchar varchar2 varying void"},c:[{cN:"string",b:"'",e:"'",c:[{b:"''"}]},{cN:"string",b:'"',e:'"',c:[{b:'""'}]},{cN:"string",b:"`",e:"`"},e.CNM,e.CBCM,t,e.HCM]},e.CBCM,t,e.HCM]}});hljs.registerLanguage("vala",function(e){return{k:{keyword:"char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double bool struct enum string void weak unowned owned async signal static abstract interface override virtual delegate if while do for foreach else switch case break default return try catch public private protected internal using new this get set const stdout stdin stderr var",built_in:"DBus GLib CCode Gee Object Gtk Posix",literal:"false true null"},c:[{cN:"class",bK:"class interface namespace",e:"{",eE:!0,i:"[^,:\\n\\s\\.]",c:[e.UTM]},e.CLCM,e.CBCM,{cN:"string",b:'"""',e:'"""',relevance:5},e.ASM,e.QSM,e.CNM,{cN:"meta",b:"^#",e:"$",relevance:2}]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.CLCM,e.CBCM],c=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:c,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})].concat(n),i:"\\S"},a={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return c.push(t,a),n.forEach(function(e){c.push(e)}),{c:c,k:i,i:"\\S"}});hljs.registerLanguage("rust",function(e){var t="([ui](8|16|32|64|128|size)|f(32|64))?",r="drop i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 str char bool Box Option Result String Vec Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator SliceConcatExt ToString assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!";return{aliases:["rs"],k:{keyword:"abstract as async await become box break const continue crate do dyn else enum extern false final fn for if impl in let loop macro match mod move mut override priv pub ref return self Self static struct super trait true try type typeof unsafe unsized use virtual where while yield",literal:"true false Some None Ok Err",built_in:r},l:e.IR+"!?",i:"</",c:[e.CLCM,e.C("/\\*","\\*/",{c:["self"]}),e.inherit(e.QSM,{b:/b?"/,i:null}),{cN:"string",v:[{b:/r(#*)"(.|\n)*?"\1(?!#)/},{b:/b?'\\?(x\w{2}|u\w{4}|U\w{8}|.)'/}]},{cN:"symbol",b:/'[a-zA-Z_][a-zA-Z0-9_]*/},{cN:"number",v:[{b:"\\b0b([01_]+)"+t},{b:"\\b0o([0-7_]+)"+t},{b:"\\b0x([A-Fa-f0-9_]+)"+t},{b:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+t}],relevance:0},{cN:"function",bK:"fn",e:"(\\(|<)",eE:!0,c:[e.UTM]},{cN:"meta",b:"#\\!?\\[",e:"\\]",c:[{cN:"meta-string",b:/"/,e:/"/}]},{cN:"class",bK:"type",e:";",c:[e.inherit(e.UTM,{endsParent:!0})],i:"\\S"},{cN:"class",bK:"trait enum struct union",e:"{",c:[e.inherit(e.UTM,{endsParent:!0})],i:"[\\w\\d]"},{b:e.IR+"::",k:{built_in:r}},{b:"->"}]}});hljs.registerLanguage("java",function(e){var a="false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",t={cN:"number",b:"\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",relevance:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{relevance:0,c:[{b:/\w+@/,relevance:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",relevance:0},{cN:"function",b:"([À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(<[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(\\s*,\\s*[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*)*>)?\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,relevance:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,relevance:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},t,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("cs",function(e){var a={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let nameof on orderby partial remove select set value var when where yield",literal:"null false true"},i={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},c={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},r=e.inherit(c,{i:/\n/}),n={cN:"subst",b:"{",e:"}",k:a},t=e.inherit(n,{i:/\n/}),s={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,t]},l={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},n]},b=e.inherit(l,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},t]});n.c=[l,s,c,e.ASM,e.QSM,i,e.CBCM],t.c=[b,s,r,e.ASM,e.QSM,i,e.inherit(e.CBCM,{i:/\n/})];var o={v:[l,s,c,e.ASM,e.QSM]},d=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp","c#"],k:a,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",relevance:0},{b:"\x3c!--|--\x3e"},{b:"</?",e:">"}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},o,i,{bK:"class interface",e:/[{;=]/,i:/[^\s:,]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",relevance:0},{cN:"function",b:"("+d+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/\s*[{;=]/,eE:!0,k:a,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],relevance:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:a,relevance:0,c:[o,i,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("mathematica",function(e){return{aliases:["mma","wl"],l:"(\\$|\\b)"+e.IR+"\\b",k:"AASTriangle AbelianGroup Abort AbortKernels AbortProtect AbortScheduledTask Above Abs AbsArg AbsArgPlot Absolute AbsoluteCorrelation AbsoluteCorrelationFunction AbsoluteCurrentValue AbsoluteDashing AbsoluteFileName AbsoluteOptions AbsolutePointSize AbsoluteThickness AbsoluteTime AbsoluteTiming AcceptanceThreshold AccountingForm Accumulate Accuracy AccuracyGoal ActionDelay ActionMenu ActionMenuBox ActionMenuBoxOptions Activate Active ActiveClassification ActiveClassificationObject ActiveItem ActivePrediction ActivePredictionObject ActiveStyle AcyclicGraphQ AddOnHelpPath AddSides AddTo AddToSearchIndex AddUsers AdjacencyGraph AdjacencyList AdjacencyMatrix AdjustmentBox AdjustmentBoxOptions AdjustTimeSeriesForecast AdministrativeDivisionData AffineHalfSpace AffineSpace AffineStateSpaceModel AffineTransform After AggregatedEntityClass AggregationLayer AircraftData AirportData AirPressureData AirTemperatureData AiryAi AiryAiPrime AiryAiZero AiryBi AiryBiPrime AiryBiZero AlgebraicIntegerQ AlgebraicNumber AlgebraicNumberDenominator AlgebraicNumberNorm AlgebraicNumberPolynomial AlgebraicNumberTrace AlgebraicRules AlgebraicRulesData Algebraics AlgebraicUnitQ Alignment AlignmentMarker AlignmentPoint All AllowAdultContent AllowedCloudExtraParameters AllowedCloudParameterExtensions AllowedDimensions AllowedFrequencyRange AllowedHeads AllowGroupClose AllowIncomplete AllowInlineCells AllowKernelInitialization AllowLooseGrammar AllowReverseGroupClose AllowScriptLevelChange AllTrue Alphabet AlphabeticOrder AlphabeticSort AlphaChannel AlternateImage AlternatingFactorial AlternatingGroup AlternativeHypothesis Alternatives AltitudeMethod AmbientLight AmbiguityFunction AmbiguityList Analytic AnatomyData AnatomyForm AnatomyPlot3D AnatomySkinStyle AnatomyStyling AnchoredSearch And AndersonDarlingTest AngerJ AngleBisector AngleBracket AnglePath AnglePath3D AngleVector AngularGauge Animate AnimationCycleOffset AnimationCycleRepetitions AnimationDirection AnimationDisplayTime AnimationRate AnimationRepetitions AnimationRunning AnimationRunTime AnimationTimeIndex Animator AnimatorBox AnimatorBoxOptions AnimatorElements Annotate Annotation AnnotationDelete AnnotationNames AnnotationRules AnnotationValue Annuity AnnuityDue Annulus AnomalyDetection AnomalyDetectorFunction Anonymous Antialiasing AntihermitianMatrixQ Antisymmetric AntisymmetricMatrixQ Antonyms AnyOrder AnySubset AnyTrue Apart ApartSquareFree APIFunction Appearance AppearanceElements AppearanceRules AppellF1 Append AppendCheck AppendLayer AppendTo ApplicationIdentificationKey Apply ApplySides ArcCos ArcCosh ArcCot ArcCoth ArcCsc ArcCsch ArcCurvature ARCHProcess ArcLength ArcSec ArcSech ArcSin ArcSinDistribution ArcSinh ArcTan ArcTanh Area Arg ArgMax ArgMin ArgumentCountQ ARIMAProcess ArithmeticGeometricMean ARMAProcess Around AroundReplace ARProcess Array ArrayComponents ArrayDepth ArrayFilter ArrayFlatten ArrayMesh ArrayPad ArrayPlot ArrayQ ArrayResample ArrayReshape ArrayRules Arrays Arrow Arrow3DBox ArrowBox Arrowheads ASATriangle Ask AskAppend AskConfirm AskDisplay AskedQ AskedValue AskFunction AskState AskTemplateDisplay AspectRatio AspectRatioFixed Assert AssociateTo Association AssociationFormat AssociationMap AssociationQ AssociationThread AssumeDeterministic Assuming Assumptions AstronomicalData AsymptoticDSolveValue AsymptoticEqual AsymptoticEquivalent AsymptoticGreater AsymptoticGreaterEqual AsymptoticIntegrate AsymptoticLess AsymptoticLessEqual AsymptoticOutputTracker AsymptoticRSolveValue AsymptoticSolve AsymptoticSum Asynchronous AsynchronousTaskObject AsynchronousTasks Atom AtomCoordinates AtomCount AtomDiagramCoordinates AtomList AtomQ AttentionLayer Attributes Audio AudioAmplify AudioAnnotate AudioAnnotationLookup AudioBlockMap AudioCapture AudioChannelAssignment AudioChannelCombine AudioChannelMix AudioChannels AudioChannelSeparate AudioData AudioDelay AudioDelete AudioDevice AudioDistance AudioFade AudioFrequencyShift AudioGenerator AudioIdentify AudioInputDevice AudioInsert AudioIntervals AudioJoin AudioLabel AudioLength AudioLocalMeasurements AudioLooping AudioLoudness AudioMeasurements AudioNormalize AudioOutputDevice AudioOverlay AudioPad AudioPan AudioPartition AudioPause AudioPitchShift AudioPlay AudioPlot AudioQ AudioRecord AudioReplace AudioResample AudioReverb AudioSampleRate AudioSpectralMap AudioSpectralTransformation AudioSplit AudioStop AudioStream AudioStreams AudioTimeStretch AudioTrim AudioType AugmentedPolyhedron AugmentedSymmetricPolynomial Authenticate Authentication AuthenticationDialog AutoAction Autocomplete AutocompletionFunction AutoCopy AutocorrelationTest AutoDelete AutoEvaluateEvents AutoGeneratedPackage AutoIndent AutoIndentSpacings AutoItalicWords AutoloadPath AutoMatch Automatic AutomaticImageSize AutoMultiplicationSymbol AutoNumberFormatting AutoOpenNotebooks AutoOpenPalettes AutoQuoteCharacters AutoRefreshed AutoRemove AutorunSequencing AutoScaling AutoScroll AutoSpacing AutoStyleOptions AutoStyleWords AutoSubmitting Axes AxesEdge AxesLabel AxesOrigin AxesStyle AxiomaticTheory AxisBabyMonsterGroupB Back Background BackgroundAppearance BackgroundTasksSettings Backslash Backsubstitution Backward Ball Band BandpassFilter BandstopFilter BarabasiAlbertGraphDistribution BarChart BarChart3D BarcodeImage BarcodeRecognize BaringhausHenzeTest BarLegend BarlowProschanImportance BarnesG BarOrigin BarSpacing BartlettHannWindow BartlettWindow BaseDecode BaseEncode BaseForm Baseline BaselinePosition BaseStyle BasicRecurrentLayer BatchNormalizationLayer BatchSize BatesDistribution BattleLemarieWavelet BayesianMaximization BayesianMaximizationObject BayesianMinimization BayesianMinimizationObject Because BeckmannDistribution Beep Before Begin BeginDialogPacket BeginFrontEndInteractionPacket BeginPackage BellB BellY Below BenfordDistribution BeniniDistribution BenktanderGibratDistribution BenktanderWeibullDistribution BernoulliB BernoulliDistribution BernoulliGraphDistribution BernoulliProcess BernsteinBasis BesselFilterModel BesselI BesselJ BesselJZero BesselK BesselY BesselYZero Beta BetaBinomialDistribution BetaDistribution BetaNegativeBinomialDistribution BetaPrimeDistribution BetaRegularized Between BetweennessCentrality BeveledPolyhedron BezierCurve BezierCurve3DBox BezierCurve3DBoxOptions BezierCurveBox BezierCurveBoxOptions BezierFunction BilateralFilter Binarize BinaryDeserialize BinaryDistance BinaryFormat BinaryImageQ BinaryRead BinaryReadList BinarySerialize BinaryWrite BinCounts BinLists Binomial BinomialDistribution BinomialProcess BinormalDistribution BiorthogonalSplineWavelet BipartiteGraphQ BiquadraticFilterModel BirnbaumImportance BirnbaumSaundersDistribution BitAnd BitClear BitGet BitLength BitNot BitOr BitSet BitShiftLeft BitShiftRight BitXor BiweightLocation BiweightMidvariance Black BlackmanHarrisWindow BlackmanNuttallWindow BlackmanWindow Blank BlankForm BlankNullSequence BlankSequence Blend Block BlockchainAddressData BlockchainBase BlockchainBlockData BlockchainContractValue BlockchainData BlockchainGet BlockchainKeyEncode BlockchainPut BlockchainTokenData BlockchainTransaction BlockchainTransactionData BlockchainTransactionSign BlockchainTransactionSubmit BlockMap BlockRandom BlomqvistBeta BlomqvistBetaTest Blue Blur BodePlot BohmanWindow Bold Bond BondCount BondList BondQ Bookmarks Boole BooleanConsecutiveFunction BooleanConvert BooleanCountingFunction BooleanFunction BooleanGraph BooleanMaxterms BooleanMinimize BooleanMinterms BooleanQ BooleanRegion Booleans BooleanStrings BooleanTable BooleanVariables BorderDimensions BorelTannerDistribution Bottom BottomHatTransform BoundaryDiscretizeGraphics BoundaryDiscretizeRegion BoundaryMesh BoundaryMeshRegion BoundaryMeshRegionQ BoundaryStyle BoundedRegionQ BoundingRegion Bounds Box BoxBaselineShift BoxData BoxDimensions Boxed Boxes BoxForm BoxFormFormatTypes BoxFrame BoxID BoxMargins BoxMatrix BoxObject BoxRatios BoxRotation BoxRotationPoint BoxStyle BoxWhiskerChart Bra BracketingBar BraKet BrayCurtisDistance BreadthFirstScan Break BridgeData BrightnessEqualize BroadcastStationData Brown BrownForsytheTest BrownianBridgeProcess BrowserCategory BSplineBasis BSplineCurve BSplineCurve3DBox BSplineCurve3DBoxOptions BSplineCurveBox BSplineCurveBoxOptions BSplineFunction BSplineSurface BSplineSurface3DBox BSplineSurface3DBoxOptions BubbleChart BubbleChart3D BubbleScale BubbleSizes BuildingData BulletGauge BusinessDayQ ButterflyGraph ButterworthFilterModel Button ButtonBar ButtonBox ButtonBoxOptions ButtonCell ButtonContents ButtonData ButtonEvaluator ButtonExpandable ButtonFrame ButtonFunction ButtonMargins ButtonMinHeight ButtonNote ButtonNotebook ButtonSource ButtonStyle ButtonStyleMenuListing Byte ByteArray ByteArrayFormat ByteArrayQ ByteArrayToString ByteCount ByteOrderingC CachedValue CacheGraphics CachePersistence CalendarConvert CalendarData CalendarType Callout CalloutMarker CalloutStyle CallPacket CanberraDistance Cancel CancelButton CandlestickChart CanonicalGraph CanonicalizePolygon CanonicalizePolyhedron CanonicalName CanonicalWarpingCorrespondence CanonicalWarpingDistance CantorMesh CantorStaircase Cap CapForm CapitalDifferentialD Capitalize CapsuleShape CaptureRunning CardinalBSplineBasis CarlemanLinearize CarmichaelLambda CaseOrdering Cases CaseSensitive Cashflow Casoratian Catalan CatalanNumber Catch Catenate CatenateLayer CauchyDistribution CauchyWindow CayleyGraph CDF CDFDeploy CDFInformation CDFWavelet Ceiling CelestialSystem Cell CellAutoOverwrite CellBaseline CellBoundingBox CellBracketOptions CellChangeTimes CellContents CellContext CellDingbat CellDynamicExpression CellEditDuplicate CellElementsBoundingBox CellElementSpacings CellEpilog CellEvaluationDuplicate CellEvaluationFunction CellEvaluationLanguage CellEventActions CellFrame CellFrameColor CellFrameLabelMargins CellFrameLabels CellFrameMargins CellGroup CellGroupData CellGrouping CellGroupingRules CellHorizontalScrolling CellID CellLabel CellLabelAutoDelete CellLabelMargins CellLabelPositioning CellLabelStyle CellLabelTemplate CellMargins CellObject CellOpen CellPrint CellProlog Cells CellSize CellStyle CellTags CellularAutomaton CensoredDistribution Censoring Center CenterArray CenterDot CentralFeature CentralMoment CentralMomentGeneratingFunction Cepstrogram CepstrogramArray CepstrumArray CForm ChampernowneNumber ChangeOptions ChannelBase ChannelBrokerAction ChannelDatabin ChannelHistoryLength ChannelListen ChannelListener ChannelListeners ChannelListenerWait ChannelObject ChannelPreSendFunction ChannelReceiverFunction ChannelSend ChannelSubscribers ChanVeseBinarize Character CharacterCounts CharacterEncoding CharacterEncodingsPath CharacteristicFunction CharacteristicPolynomial CharacterName CharacterRange Characters ChartBaseStyle ChartElementData ChartElementDataFunction ChartElementFunction ChartElements ChartLabels ChartLayout ChartLegends ChartStyle Chebyshev1FilterModel Chebyshev2FilterModel ChebyshevDistance ChebyshevT ChebyshevU Check CheckAbort CheckAll Checkbox CheckboxBar CheckboxBox CheckboxBoxOptions ChemicalData ChessboardDistance ChiDistribution ChineseRemainder ChiSquareDistribution ChoiceButtons ChoiceDialog CholeskyDecomposition Chop ChromaticityPlot ChromaticityPlot3D ChromaticPolynomial Circle CircleBox CircleDot CircleMinus CirclePlus CirclePoints CircleThrough CircleTimes CirculantGraph CircularOrthogonalMatrixDistribution CircularQuaternionMatrixDistribution CircularRealMatrixDistribution CircularSymplecticMatrixDistribution CircularUnitaryMatrixDistribution Circumsphere CityData ClassifierFunction ClassifierInformation ClassifierMeasurements ClassifierMeasurementsObject Classify ClassPriors Clear ClearAll ClearAttributes ClearCookies ClearPermissions ClearSystemCache ClebschGordan ClickPane Clip ClipboardNotebook ClipFill ClippingStyle ClipPlanes ClipPlanesStyle ClipRange Clock ClockGauge ClockwiseContourIntegral Close Closed CloseKernels ClosenessCentrality Closing ClosingAutoSave ClosingEvent CloudAccountData CloudBase CloudConnect CloudDeploy CloudDirectory CloudDisconnect CloudEvaluate CloudExport CloudExpression CloudExpressions CloudFunction CloudGet CloudImport CloudLoggingData CloudObject CloudObjectInformation CloudObjectInformationData CloudObjectNameFormat CloudObjects CloudObjectURLType CloudPublish CloudPut CloudRenderingMethod CloudSave CloudShare CloudSubmit CloudSymbol CloudUnshare ClusterClassify ClusterDissimilarityFunction ClusteringComponents ClusteringTree CMYKColor Coarse CodeAssistOptions Coefficient CoefficientArrays CoefficientDomain CoefficientList CoefficientRules CoifletWavelet Collect Colon ColonForm ColorBalance ColorCombine ColorConvert ColorCoverage ColorData ColorDataFunction ColorDetect ColorDistance ColorFunction ColorFunctionScaling Colorize ColorNegate ColorOutput ColorProfileData ColorQ ColorQuantize ColorReplace ColorRules ColorSelectorSettings ColorSeparate ColorSetter ColorSetterBox ColorSetterBoxOptions ColorSlider ColorsNear ColorSpace ColorToneMapping Column ColumnAlignments ColumnBackgrounds ColumnForm ColumnLines ColumnsEqual ColumnSpacings ColumnWidths CombinedEntityClass CombinerFunction CometData CommonDefaultFormatTypes Commonest CommonestFilter CommonName CommonUnits CommunityBoundaryStyle CommunityGraphPlot CommunityLabels CommunityRegionStyle CompanyData CompatibleUnitQ CompilationOptions CompilationTarget Compile Compiled CompiledCodeFunction CompiledFunction CompilerOptions Complement CompleteGraph CompleteGraphQ CompleteKaryTree CompletionsListPacket Complex Complexes ComplexExpand ComplexInfinity ComplexityFunction ComplexListPlot ComplexPlot ComplexPlot3D ComponentMeasurements ComponentwiseContextMenu Compose ComposeList ComposeSeries CompositeQ Composition CompoundElement CompoundExpression CompoundPoissonDistribution CompoundPoissonProcess CompoundRenewalProcess Compress CompressedData ComputeUncertainty Condition ConditionalExpression Conditioned Cone ConeBox ConfidenceLevel ConfidenceRange ConfidenceTransform ConfigurationPath ConformAudio ConformImages Congruent ConicHullRegion ConicHullRegion3DBox ConicHullRegionBox ConicOptimization Conjugate ConjugateTranspose Conjunction Connect ConnectedComponents ConnectedGraphComponents ConnectedGraphQ ConnectedMeshComponents ConnectedMoleculeComponents ConnectedMoleculeQ ConnectionSettings ConnectLibraryCallbackFunction ConnectSystemModelComponents ConnesWindow ConoverTest ConsoleMessage ConsoleMessagePacket ConsolePrint Constant ConstantArray ConstantArrayLayer ConstantImage ConstantPlusLayer ConstantRegionQ Constants ConstantTimesLayer ConstellationData ConstrainedMax ConstrainedMin Construct Containing ContainsAll ContainsAny ContainsExactly ContainsNone ContainsOnly ContentFieldOptions ContentLocationFunction ContentObject ContentPadding ContentsBoundingBox ContentSelectable ContentSize Context ContextMenu Contexts ContextToFileName Continuation Continue ContinuedFraction ContinuedFractionK ContinuousAction ContinuousMarkovProcess ContinuousTask ContinuousTimeModelQ ContinuousWaveletData ContinuousWaveletTransform ContourDetect ContourGraphics ContourIntegral ContourLabels ContourLines ContourPlot ContourPlot3D Contours ContourShading ContourSmoothing ContourStyle ContraharmonicMean ContrastiveLossLayer Control ControlActive ControlAlignment ControlGroupContentsBox ControllabilityGramian ControllabilityMatrix ControllableDecomposition ControllableModelQ ControllerDuration ControllerInformation ControllerInformationData ControllerLinking ControllerManipulate ControllerMethod ControllerPath ControllerState ControlPlacement ControlsRendering ControlType Convergents ConversionOptions ConversionRules ConvertToBitmapPacket ConvertToPostScript ConvertToPostScriptPacket ConvexHullMesh ConvexPolygonQ ConvexPolyhedronQ ConvolutionLayer Convolve ConwayGroupCo1 ConwayGroupCo2 ConwayGroupCo3 CookieFunction Cookies CoordinateBoundingBox CoordinateBoundingBoxArray CoordinateBounds CoordinateBoundsArray CoordinateChartData CoordinatesToolOptions CoordinateTransform CoordinateTransformData CoprimeQ Coproduct CopulaDistribution Copyable CopyDatabin CopyDirectory CopyFile CopyTag CopyToClipboard CornerFilter CornerNeighbors Correlation CorrelationDistance CorrelationFunction CorrelationTest Cos Cosh CoshIntegral CosineDistance CosineWindow CosIntegral Cot Coth Count CountDistinct CountDistinctBy CounterAssignments CounterBox CounterBoxOptions CounterClockwiseContourIntegral CounterEvaluator CounterFunction CounterIncrements CounterStyle CounterStyleMenuListing CountRoots CountryData Counts CountsBy Covariance CovarianceEstimatorFunction CovarianceFunction CoxianDistribution CoxIngersollRossProcess CoxModel CoxModelFit CramerVonMisesTest CreateArchive CreateCellID CreateChannel CreateCloudExpression CreateDatabin CreateDataSystemModel CreateDialog CreateDirectory CreateDocument CreateFile CreateIntermediateDirectories CreateManagedLibraryExpression CreateNotebook CreatePalette CreatePalettePacket CreatePermissionsGroup CreateScheduledTask CreateSearchIndex CreateSystemModel CreateTemporary CreateUUID CreateWindow CriterionFunction CriticalityFailureImportance CriticalitySuccessImportance CriticalSection Cross CrossEntropyLossLayer CrossingCount CrossingDetect CrossingPolygon CrossMatrix Csc Csch CTCLossLayer Cube CubeRoot Cubics Cuboid CuboidBox Cumulant CumulantGeneratingFunction Cup CupCap Curl CurlyDoubleQuote CurlyQuote CurrencyConvert CurrentDate CurrentImage CurrentlySpeakingPacket CurrentNotebookImage CurrentScreenImage CurrentValue Curry CurvatureFlowFilter CurveClosed Cyan CycleGraph CycleIndexPolynomial Cycles CyclicGroup Cyclotomic Cylinder CylinderBox CylindricalDecompositionD DagumDistribution DamData DamerauLevenshteinDistance DampingFactor Darker Dashed Dashing DatabaseConnect DatabaseDisconnect DatabaseReference Databin DatabinAdd DatabinRemove Databins DatabinUpload DataCompression DataDistribution DataRange DataReversed Dataset Date DateBounds Dated DateDelimiters DateDifference DatedUnit DateFormat DateFunction DateHistogram DateList DateListLogPlot DateListPlot DateListStepPlot DateObject DateObjectQ DateOverlapsQ DatePattern DatePlus DateRange DateReduction DateString DateTicksFormat DateValue DateWithinQ DaubechiesWavelet DavisDistribution DawsonF DayCount DayCountConvention DayHemisphere DaylightQ DayMatchQ DayName DayNightTerminator DayPlus DayRange DayRound DeBruijnGraph DeBruijnSequence Debug DebugTag Decapitalize Decimal DecimalForm DeclareKnownSymbols DeclarePackage Decompose DeconvolutionLayer Decrement Decrypt DecryptFile DedekindEta DeepSpaceProbeData Default DefaultAxesStyle DefaultBaseStyle DefaultBoxStyle DefaultButton DefaultColor DefaultControlPlacement DefaultDuplicateCellStyle DefaultDuration DefaultElement DefaultFaceGridsStyle DefaultFieldHintStyle DefaultFont DefaultFontProperties DefaultFormatType DefaultFormatTypeForStyle DefaultFrameStyle DefaultFrameTicksStyle DefaultGridLinesStyle DefaultInlineFormatType DefaultInputFormatType DefaultLabelStyle DefaultMenuStyle DefaultNaturalLanguage DefaultNewCellStyle DefaultNewInlineCellStyle DefaultNotebook DefaultOptions DefaultOutputFormatType DefaultPrintPrecision DefaultStyle DefaultStyleDefinitions DefaultTextFormatType DefaultTextInlineFormatType DefaultTicksStyle DefaultTooltipStyle DefaultValue DefaultValues Defer DefineExternal DefineInputStreamMethod DefineOutputStreamMethod DefineResourceFunction Definition Degree DegreeCentrality DegreeGraphDistribution DegreeLexicographic DegreeReverseLexicographic DEigensystem DEigenvalues Deinitialization Del DelaunayMesh Delayed Deletable Delete DeleteAnomalies DeleteBorderComponents DeleteCases DeleteChannel DeleteCloudExpression DeleteContents DeleteDirectory DeleteDuplicates DeleteDuplicatesBy DeleteFile DeleteMissing DeleteObject DeletePermissionsKey DeleteSearchIndex DeleteSmallComponents DeleteStopwords DeleteWithContents DeletionWarning DelimitedArray DelimitedSequence Delimiter DelimiterFlashTime DelimiterMatching Delimiters DeliveryFunction Dendrogram Denominator DensityGraphics DensityHistogram DensityPlot DensityPlot3D DependentVariables Deploy Deployed Depth DepthFirstScan Derivative DerivativeFilter DerivedKey DescriptorStateSpace DesignMatrix DestroyAfterEvaluation Det DeviceClose DeviceConfigure DeviceExecute DeviceExecuteAsynchronous DeviceObject DeviceOpen DeviceOpenQ DeviceRead DeviceReadBuffer DeviceReadLatest DeviceReadList DeviceReadTimeSeries Devices DeviceStreams DeviceWrite DeviceWriteBuffer DGaussianWavelet DiacriticalPositioning Diagonal DiagonalizableMatrixQ DiagonalMatrix DiagonalMatrixQ Dialog DialogIndent DialogInput DialogLevel DialogNotebook DialogProlog DialogReturn DialogSymbols Diamond DiamondMatrix DiceDissimilarity DictionaryLookup DictionaryWordQ DifferenceDelta DifferenceOrder DifferenceQuotient DifferenceRoot DifferenceRootReduce Differences DifferentialD DifferentialRoot DifferentialRootReduce DifferentiatorFilter DigitalSignature DigitBlock DigitBlockMinimum DigitCharacter DigitCount DigitQ DihedralAngle DihedralGroup Dilation DimensionalCombinations DimensionalMeshComponents DimensionReduce DimensionReducerFunction DimensionReduction Dimensions DiracComb DiracDelta DirectedEdge DirectedEdges DirectedGraph DirectedGraphQ DirectedInfinity Direction Directive Directory DirectoryName DirectoryQ DirectoryStack DirichletBeta DirichletCharacter DirichletCondition DirichletConvolve DirichletDistribution DirichletEta DirichletL DirichletLambda DirichletTransform DirichletWindow DisableConsolePrintPacket DisableFormatting DiscreteChirpZTransform DiscreteConvolve DiscreteDelta DiscreteHadamardTransform DiscreteIndicator DiscreteLimit DiscreteLQEstimatorGains DiscreteLQRegulatorGains DiscreteLyapunovSolve DiscreteMarkovProcess DiscreteMaxLimit DiscreteMinLimit DiscretePlot DiscretePlot3D DiscreteRatio DiscreteRiccatiSolve DiscreteShift DiscreteTimeModelQ DiscreteUniformDistribution DiscreteVariables DiscreteWaveletData DiscreteWaveletPacketTransform DiscreteWaveletTransform DiscretizeGraphics DiscretizeRegion Discriminant DisjointQ Disjunction Disk DiskBox DiskMatrix DiskSegment Dispatch DispatchQ DispersionEstimatorFunction Display DisplayAllSteps DisplayEndPacket DisplayFlushImagePacket DisplayForm DisplayFunction DisplayPacket DisplayRules DisplaySetSizePacket DisplayString DisplayTemporary DisplayWith DisplayWithRef DisplayWithVariable DistanceFunction DistanceMatrix DistanceTransform Distribute Distributed DistributedContexts DistributeDefinitions DistributionChart DistributionDomain DistributionFitTest DistributionParameterAssumptions DistributionParameterQ Dithering Div Divergence Divide DivideBy Dividers DivideSides Divisible Divisors DivisorSigma DivisorSum DMSList DMSString Do DockedCells DocumentGenerator DocumentGeneratorInformation DocumentGeneratorInformationData DocumentGenerators DocumentNotebook DocumentWeightingRules Dodecahedron DomainRegistrationInformation DominantColors DOSTextFormat Dot DotDashed DotEqual DotLayer DotPlusLayer Dotted DoubleBracketingBar DoubleContourIntegral DoubleDownArrow DoubleLeftArrow DoubleLeftRightArrow DoubleLeftTee DoubleLongLeftArrow DoubleLongLeftRightArrow DoubleLongRightArrow DoubleRightArrow DoubleRightTee DoubleUpArrow DoubleUpDownArrow DoubleVerticalBar DoublyInfinite Down DownArrow DownArrowBar DownArrowUpArrow DownLeftRightVector DownLeftTeeVector DownLeftVector DownLeftVectorBar DownRightTeeVector DownRightVector DownRightVectorBar Downsample DownTee DownTeeArrow DownValues DragAndDrop DrawEdges DrawFrontFaces DrawHighlighted Drop DropoutLayer DSolve DSolveValue Dt DualLinearProgramming DualPolyhedron DualSystemsModel DumpGet DumpSave DuplicateFreeQ Duration Dynamic DynamicBox DynamicBoxOptions DynamicEvaluationTimeout DynamicGeoGraphics DynamicImage DynamicLocation DynamicModule DynamicModuleBox DynamicModuleBoxOptions DynamicModuleParent DynamicModuleValues DynamicName DynamicNamespace DynamicReference DynamicSetting DynamicUpdating DynamicWrapper DynamicWrapperBox DynamicWrapperBoxOptionsE EarthImpactData EarthquakeData EccentricityCentrality Echo EchoFunction EclipseType EdgeAdd EdgeBetweennessCentrality EdgeCapacity EdgeCapForm EdgeColor EdgeConnectivity EdgeContract EdgeCost EdgeCount EdgeCoverQ EdgeCycleMatrix EdgeDashing EdgeDelete EdgeDetect EdgeForm EdgeIndex EdgeJoinForm EdgeLabeling EdgeLabels EdgeLabelStyle EdgeList EdgeOpacity EdgeQ EdgeRenderingFunction EdgeRules EdgeShapeFunction EdgeStyle EdgeThickness EdgeWeight EdgeWeightedGraphQ Editable EditButtonSettings EditCellTagsSettings EditDistance EffectiveInterest Eigensystem Eigenvalues EigenvectorCentrality Eigenvectors Element ElementData ElementwiseLayer ElidedForms Eliminate EliminationOrder Ellipsoid EllipticE EllipticExp EllipticExpPrime EllipticF EllipticFilterModel EllipticK EllipticLog EllipticNomeQ EllipticPi EllipticReducedHalfPeriods EllipticTheta EllipticThetaPrime EmbedCode EmbeddedHTML EmbeddedService EmbeddingLayer EmbeddingObject EmitSound EmphasizeSyntaxErrors EmpiricalDistribution Empty EmptyGraphQ EmptyRegion EnableConsolePrintPacket Enabled Encode Encrypt EncryptedObject EncryptFile End EndAdd EndDialogPacket EndFrontEndInteractionPacket EndOfBuffer EndOfFile EndOfLine EndOfString EndPackage EngineEnvironment EngineeringForm Enter EnterExpressionPacket EnterTextPacket Entity EntityClass EntityClassList EntityCopies EntityFunction EntityGroup EntityInstance EntityList EntityPrefetch EntityProperties EntityProperty EntityPropertyClass EntityRegister EntityStore EntityStores EntityTypeName EntityUnregister EntityValue Entropy EntropyFilter Environment Epilog EpilogFunction Equal EqualColumns EqualRows EqualTilde EqualTo EquatedTo Equilibrium EquirippleFilterKernel Equivalent Erf Erfc Erfi ErlangB ErlangC ErlangDistribution Erosion ErrorBox ErrorBoxOptions ErrorNorm ErrorPacket ErrorsDialogSettings EscapeRadius EstimatedBackground EstimatedDistribution EstimatedProcess EstimatorGains EstimatorRegulator EuclideanDistance EulerAngles EulerCharacteristic EulerE EulerGamma EulerianGraphQ EulerMatrix EulerPhi Evaluatable Evaluate Evaluated EvaluatePacket EvaluateScheduledTask EvaluationBox EvaluationCell EvaluationCompletionAction EvaluationData EvaluationElements EvaluationEnvironment EvaluationMode EvaluationMonitor EvaluationNotebook EvaluationObject EvaluationOrder Evaluator EvaluatorNames EvenQ EventData EventEvaluator EventHandler EventHandlerTag EventLabels EventSeries ExactBlackmanWindow ExactNumberQ ExactRootIsolation ExampleData Except ExcludedForms ExcludedLines ExcludedPhysicalQuantities ExcludePods Exclusions ExclusionsStyle Exists Exit ExitDialog ExoplanetData Exp Expand ExpandAll ExpandDenominator ExpandFileName ExpandNumerator Expectation ExpectationE ExpectedValue ExpGammaDistribution ExpIntegralE ExpIntegralEi ExpirationDate Exponent ExponentFunction ExponentialDistribution ExponentialFamily ExponentialGeneratingFunction ExponentialMovingAverage ExponentialPowerDistribution ExponentPosition ExponentStep Export ExportAutoReplacements ExportByteArray ExportForm ExportPacket ExportString Expression ExpressionCell ExpressionPacket ExpressionUUID ExpToTrig ExtendedEntityClass ExtendedGCD Extension ExtentElementFunction ExtentMarkers ExtentSize ExternalBundle ExternalCall ExternalDataCharacterEncoding ExternalEvaluate ExternalFunction ExternalFunctionName ExternalObject ExternalOptions ExternalSessionObject ExternalSessions ExternalTypeSignature ExternalValue Extract ExtractArchive ExtractLayer ExtremeValueDistributionFaceForm FaceGrids FaceGridsStyle FacialFeatures Factor FactorComplete Factorial Factorial2 FactorialMoment FactorialMomentGeneratingFunction FactorialPower FactorInteger FactorList FactorSquareFree FactorSquareFreeList FactorTerms FactorTermsList Fail Failure FailureAction FailureDistribution FailureQ False FareySequence FARIMAProcess FeatureDistance FeatureExtract FeatureExtraction FeatureExtractor FeatureExtractorFunction FeatureNames FeatureNearest FeatureSpacePlot FeatureSpacePlot3D FeatureTypes FEDisableConsolePrintPacket FeedbackLinearize FeedbackSector FeedbackSectorStyle FeedbackType FEEnableConsolePrintPacket FetalGrowthData Fibonacci Fibonorial FieldCompletionFunction FieldHint FieldHintStyle FieldMasked FieldSize File FileBaseName FileByteCount FileConvert FileDate FileExistsQ FileExtension FileFormat FileHandler FileHash FileInformation FileName FileNameDepth FileNameDialogSettings FileNameDrop FileNameForms FileNameJoin FileNames FileNameSetter FileNameSplit FileNameTake FilePrint FileSize FileSystemMap FileSystemScan FileTemplate FileTemplateApply FileType FilledCurve FilledCurveBox FilledCurveBoxOptions Filling FillingStyle FillingTransform FilteredEntityClass FilterRules FinancialBond FinancialData FinancialDerivative FinancialIndicator Find FindAnomalies FindArgMax FindArgMin FindChannels FindClique FindClusters FindCookies FindCurvePath FindCycle FindDevices FindDistribution FindDistributionParameters FindDivisions FindEdgeCover FindEdgeCut FindEdgeIndependentPaths FindEquationalProof FindEulerianCycle FindExternalEvaluators FindFaces FindFile FindFit FindFormula FindFundamentalCycles FindGeneratingFunction FindGeoLocation FindGeometricConjectures FindGeometricTransform FindGraphCommunities FindGraphIsomorphism FindGraphPartition FindHamiltonianCycle FindHamiltonianPath FindHiddenMarkovStates FindIndependentEdgeSet FindIndependentVertexSet FindInstance FindIntegerNullVector FindKClan FindKClique FindKClub FindKPlex FindLibrary FindLinearRecurrence FindList FindMatchingColor FindMaximum FindMaximumFlow FindMaxValue FindMeshDefects FindMinimum FindMinimumCostFlow FindMinimumCut FindMinValue FindMoleculeSubstructure FindPath FindPeaks FindPermutation FindPostmanTour FindProcessParameters FindRepeat FindRoot FindSequenceFunction FindSettings FindShortestPath FindShortestTour FindSpanningTree FindSystemModelEquilibrium FindTextualAnswer FindThreshold FindTransientRepeat FindVertexCover FindVertexCut FindVertexIndependentPaths Fine FinishDynamic FiniteAbelianGroupCount FiniteGroupCount FiniteGroupData First FirstCase FirstPassageTimeDistribution FirstPosition FischerGroupFi22 FischerGroupFi23 FischerGroupFi24Prime FisherHypergeometricDistribution FisherRatioTest FisherZDistribution Fit FitAll FitRegularization FittedModel FixedOrder FixedPoint FixedPointList FlashSelection Flat Flatten FlattenAt FlattenLayer FlatTopWindow FlipView Floor FlowPolynomial FlushPrintOutputPacket Fold FoldList FoldPair FoldPairList FollowRedirects Font FontColor FontFamily FontForm FontName FontOpacity FontPostScriptName FontProperties FontReencoding FontSize FontSlant FontSubstitutions FontTracking FontVariations FontWeight For ForAll Format FormatRules FormatType FormatTypeAutoConvert FormatValues FormBox FormBoxOptions FormControl FormFunction FormLayoutFunction FormObject FormPage FormTheme FormulaData FormulaLookup FortranForm Forward ForwardBackward Fourier FourierCoefficient FourierCosCoefficient FourierCosSeries FourierCosTransform FourierDCT FourierDCTFilter FourierDCTMatrix FourierDST FourierDSTMatrix FourierMatrix FourierParameters FourierSequenceTransform FourierSeries FourierSinCoefficient FourierSinSeries FourierSinTransform FourierTransform FourierTrigSeries FractionalBrownianMotionProcess FractionalGaussianNoiseProcess FractionalPart FractionBox FractionBoxOptions FractionLine Frame FrameBox FrameBoxOptions Framed FrameInset FrameLabel Frameless FrameMargins FrameRate FrameStyle FrameTicks FrameTicksStyle FRatioDistribution FrechetDistribution FreeQ FrenetSerretSystem FrequencySamplingFilterKernel FresnelC FresnelF FresnelG FresnelS Friday FrobeniusNumber FrobeniusSolve FromAbsoluteTime FromCharacterCode FromCoefficientRules FromContinuedFraction FromDate FromDigits FromDMS FromEntity FromJulianDate FromLetterNumber FromPolarCoordinates FromRomanNumeral FromSphericalCoordinates FromUnixTime Front FrontEndDynamicExpression FrontEndEventActions FrontEndExecute FrontEndObject FrontEndResource FrontEndResourceString FrontEndStackSize FrontEndToken FrontEndTokenExecute FrontEndValueCache FrontEndVersion FrontFaceColor FrontFaceOpacity Full FullAxes FullDefinition FullForm FullGraphics FullInformationOutputRegulator FullOptions FullRegion FullSimplify Function FunctionCompile FunctionCompileExport FunctionCompileExportByteArray FunctionCompileExportLibrary FunctionCompileExportString FunctionDomain FunctionExpand FunctionInterpolation FunctionPeriod FunctionRange FunctionSpace FussellVeselyImportanceGaborFilter GaborMatrix GaborWavelet GainMargins GainPhaseMargins GalaxyData GalleryView Gamma GammaDistribution GammaRegularized GapPenalty GARCHProcess GatedRecurrentLayer Gather GatherBy GaugeFaceElementFunction GaugeFaceStyle GaugeFrameElementFunction GaugeFrameSize GaugeFrameStyle GaugeLabels GaugeMarkers GaugeStyle GaussianFilter GaussianIntegers GaussianMatrix GaussianOrthogonalMatrixDistribution GaussianSymplecticMatrixDistribution GaussianUnitaryMatrixDistribution GaussianWindow GCD GegenbauerC General GeneralizedLinearModelFit GenerateAsymmetricKeyPair GenerateConditions GeneratedCell GeneratedDocumentBinding GenerateDerivedKey GenerateDigitalSignature GenerateDocument GeneratedParameters GeneratedQuantityMagnitudes GenerateHTTPResponse GenerateSecuredAuthenticationKey GenerateSymmetricKey GeneratingFunction GeneratorDescription GeneratorHistoryLength GeneratorOutputType Generic GenericCylindricalDecomposition GenomeData GenomeLookup GeoAntipode GeoArea GeoArraySize GeoBackground GeoBoundingBox GeoBounds GeoBoundsRegion GeoBubbleChart GeoCenter GeoCircle GeodesicClosing GeodesicDilation GeodesicErosion GeodesicOpening GeoDestination GeodesyData GeoDirection GeoDisk GeoDisplacement GeoDistance GeoDistanceList GeoElevationData GeoEntities GeoGraphics GeogravityModelData GeoGridDirectionDifference GeoGridLines GeoGridLinesStyle GeoGridPosition GeoGridRange GeoGridRangePadding GeoGridUnitArea GeoGridUnitDistance GeoGridVector GeoGroup GeoHemisphere GeoHemisphereBoundary GeoHistogram GeoIdentify GeoImage GeoLabels GeoLength GeoListPlot GeoLocation GeologicalPeriodData GeomagneticModelData GeoMarker GeometricAssertion GeometricBrownianMotionProcess GeometricDistribution GeometricMean GeometricMeanFilter GeometricScene GeometricTransformation GeometricTransformation3DBox GeometricTransformation3DBoxOptions GeometricTransformationBox GeometricTransformationBoxOptions GeoModel GeoNearest GeoPath GeoPosition GeoPositionENU GeoPositionXYZ GeoProjection GeoProjectionData GeoRange GeoRangePadding GeoRegionValuePlot GeoResolution GeoScaleBar GeoServer GeoSmoothHistogram GeoStreamPlot GeoStyling GeoStylingImageFunction GeoVariant GeoVector GeoVectorENU GeoVectorPlot GeoVectorXYZ GeoVisibleRegion GeoVisibleRegionBoundary GeoWithinQ GeoZoomLevel GestureHandler GestureHandlerTag Get GetBoundingBoxSizePacket GetContext GetEnvironment GetFileName GetFrontEndOptionsDataPacket GetLinebreakInformationPacket GetMenusPacket GetPageBreakInformationPacket Glaisher GlobalClusteringCoefficient GlobalPreferences GlobalSession Glow GoldenAngle GoldenRatio GompertzMakehamDistribution GoodmanKruskalGamma GoodmanKruskalGammaTest Goto Grad Gradient GradientFilter GradientOrientationFilter GrammarApply GrammarRules GrammarToken Graph Graph3D GraphAssortativity GraphAutomorphismGroup GraphCenter GraphComplement GraphData GraphDensity GraphDiameter GraphDifference GraphDisjointUnion GraphDistance GraphDistanceMatrix GraphElementData GraphEmbedding GraphHighlight GraphHighlightStyle GraphHub Graphics Graphics3D Graphics3DBox Graphics3DBoxOptions GraphicsArray GraphicsBaseline GraphicsBox GraphicsBoxOptions GraphicsColor GraphicsColumn GraphicsComplex GraphicsComplex3DBox GraphicsComplex3DBoxOptions GraphicsComplexBox GraphicsComplexBoxOptions GraphicsContents GraphicsData GraphicsGrid GraphicsGridBox GraphicsGroup GraphicsGroup3DBox GraphicsGroup3DBoxOptions GraphicsGroupBox GraphicsGroupBoxOptions GraphicsGrouping GraphicsHighlightColor GraphicsRow GraphicsSpacing GraphicsStyle GraphIntersection GraphLayout GraphLinkEfficiency GraphPeriphery GraphPlot GraphPlot3D GraphPower GraphPropertyDistribution GraphQ GraphRadius GraphReciprocity GraphRoot GraphStyle GraphUnion Gray GrayLevel Greater GreaterEqual GreaterEqualLess GreaterEqualThan GreaterFullEqual GreaterGreater GreaterLess GreaterSlantEqual GreaterThan GreaterTilde Green GreenFunction Grid GridBaseline GridBox GridBoxAlignment GridBoxBackground GridBoxDividers GridBoxFrame GridBoxItemSize GridBoxItemStyle GridBoxOptions GridBoxSpacings GridCreationSettings GridDefaultElement GridElementStyleOptions GridFrame GridFrameMargins GridGraph GridLines GridLinesStyle GroebnerBasis GroupActionBase GroupBy GroupCentralizer GroupElementFromWord GroupElementPosition GroupElementQ GroupElements GroupElementToWord GroupGenerators Groupings GroupMultiplicationTable GroupOrbits GroupOrder GroupPageBreakWithin GroupSetwiseStabilizer GroupStabilizer GroupStabilizerChain GroupTogetherGrouping GroupTogetherNestedGrouping GrowCutComponents Gudermannian GuidedFilter GumbelDistributionHaarWavelet HadamardMatrix HalfLine HalfNormalDistribution HalfPlane HalfSpace HamiltonianGraphQ HammingDistance HammingWindow HandlerFunctions HandlerFunctionsKeys HankelH1 HankelH2 HankelMatrix HankelTransform HannPoissonWindow HannWindow HaradaNortonGroupHN HararyGraph HarmonicMean HarmonicMeanFilter HarmonicNumber Hash Haversine HazardFunction Head HeadCompose HeaderLines Heads HeavisideLambda HeavisidePi HeavisideTheta HeldGroupHe HeldPart HelpBrowserLookup HelpBrowserNotebook HelpBrowserSettings Here HermiteDecomposition HermiteH HermitianMatrixQ HessenbergDecomposition Hessian HexadecimalCharacter Hexahedron HexahedronBox HexahedronBoxOptions HiddenMarkovProcess HiddenSurface Highlighted HighlightGraph HighlightImage HighlightMesh HighpassFilter HigmanSimsGroupHS HilbertCurve HilbertFilter HilbertMatrix Histogram Histogram3D HistogramDistribution HistogramList HistogramTransform HistogramTransformInterpolation HistoricalPeriodData HitMissTransform HITSCentrality HjorthDistribution HodgeDual HoeffdingD HoeffdingDTest Hold HoldAll HoldAllComplete HoldComplete HoldFirst HoldForm HoldPattern HoldRest HolidayCalendar HomeDirectory HomePage Horizontal HorizontalForm HorizontalGauge HorizontalScrollPosition HornerForm HostLookup HotellingTSquareDistribution HoytDistribution HTMLSave HTTPErrorResponse HTTPRedirect HTTPRequest HTTPRequestData HTTPResponse Hue HumanGrowthData HumpDownHump HumpEqual HurwitzLerchPhi HurwitzZeta HyperbolicDistribution HypercubeGraph HyperexponentialDistribution Hyperfactorial Hypergeometric0F1 Hypergeometric0F1Regularized Hypergeometric1F1 Hypergeometric1F1Regularized Hypergeometric2F1 Hypergeometric2F1Regularized HypergeometricDistribution HypergeometricPFQ HypergeometricPFQRegularized HypergeometricU Hyperlink HyperlinkCreationSettings Hyperplane Hyphenation HyphenationOptions HypoexponentialDistribution HypothesisTestDataI IconData Iconize IconizedObject IconRules Icosahedron Identity IdentityMatrix If IgnoreCase IgnoreDiacritics IgnorePunctuation IgnoreSpellCheck IgnoringInactive Im Image Image3D Image3DProjection Image3DSlices ImageAccumulate ImageAdd ImageAdjust ImageAlign ImageApply ImageApplyIndexed ImageAspectRatio ImageAssemble ImageAugmentationLayer ImageBoundingBoxes ImageCache ImageCacheValid ImageCapture ImageCaptureFunction ImageCases ImageChannels ImageClip ImageCollage ImageColorSpace ImageCompose ImageContainsQ ImageContents ImageConvolve ImageCooccurrence ImageCorners ImageCorrelate ImageCorrespondingPoints ImageCrop ImageData ImageDeconvolve ImageDemosaic ImageDifference ImageDimensions ImageDisplacements ImageDistance ImageEffect ImageExposureCombine ImageFeatureTrack ImageFileApply ImageFileFilter ImageFileScan ImageFilter ImageFocusCombine ImageForestingComponents ImageFormattingWidth ImageForwardTransformation ImageGraphics ImageHistogram ImageIdentify ImageInstanceQ ImageKeypoints ImageLevels ImageLines ImageMargins ImageMarker ImageMarkers ImageMeasurements ImageMesh ImageMultiply ImageOffset ImagePad ImagePadding ImagePartition ImagePeriodogram ImagePerspectiveTransformation ImagePosition ImagePreviewFunction ImagePyramid ImagePyramidApply ImageQ ImageRangeCache ImageRecolor ImageReflect ImageRegion ImageResize ImageResolution ImageRestyle ImageRotate ImageRotated ImageSaliencyFilter ImageScaled ImageScan ImageSize ImageSizeAction ImageSizeCache ImageSizeMultipliers ImageSizeRaw ImageSubtract ImageTake ImageTransformation ImageTrim ImageType ImageValue ImageValuePositions ImagingDevice ImplicitRegion Implies Import ImportAutoReplacements ImportByteArray ImportOptions ImportString ImprovementImportance In Inactivate Inactive IncidenceGraph IncidenceList IncidenceMatrix IncludeAromaticBonds IncludeConstantBasis IncludeDefinitions IncludeDirectories IncludeFileExtension IncludeGeneratorTasks IncludeHydrogens IncludeInflections IncludeMetaInformation IncludePods IncludeQuantities IncludeRelatedTables IncludeSingularTerm IncludeWindowTimes Increment IndefiniteMatrixQ Indent IndentingNewlineSpacings IndentMaxFraction IndependenceTest IndependentEdgeSetQ IndependentPhysicalQuantity IndependentUnit IndependentUnitDimension IndependentVertexSetQ Indeterminate IndeterminateThreshold IndexCreationOptions Indexed IndexGraph IndexTag Inequality InexactNumberQ InexactNumbers InfiniteLine InfinitePlane Infinity Infix InflationAdjust InflationMethod Information InformationData InformationDataGrid Inherited InheritScope InhomogeneousPoissonProcess InitialEvaluationHistory Initialization InitializationCell InitializationCellEvaluation InitializationCellWarning InitializationObjects InitializationValue Initialize InitialSeeding InlineCounterAssignments InlineCounterIncrements InlineRules Inner InnerPolygon InnerPolyhedron Inpaint Input InputAliases InputAssumptions InputAutoReplacements InputField InputFieldBox InputFieldBoxOptions InputForm InputGrouping InputNamePacket InputNotebook InputPacket InputSettings InputStream InputString InputStringPacket InputToBoxFormPacket Insert InsertionFunction InsertionPointObject InsertLinebreaks InsertResults Inset Inset3DBox Inset3DBoxOptions InsetBox InsetBoxOptions Insphere Install InstallService InstanceNormalizationLayer InString Integer IntegerDigits IntegerExponent IntegerLength IntegerName IntegerPart IntegerPartitions IntegerQ IntegerReverse Integers IntegerString Integral Integrate Interactive InteractiveTradingChart Interlaced Interleaving InternallyBalancedDecomposition InterpolatingFunction InterpolatingPolynomial Interpolation InterpolationOrder InterpolationPoints InterpolationPrecision Interpretation InterpretationBox InterpretationBoxOptions InterpretationFunction Interpreter InterpretTemplate InterquartileRange Interrupt InterruptSettings IntersectingQ Intersection Interval IntervalIntersection IntervalMarkers IntervalMarkersStyle IntervalMemberQ IntervalSlider IntervalUnion Into Inverse InverseBetaRegularized InverseCDF InverseChiSquareDistribution InverseContinuousWaveletTransform InverseDistanceTransform InverseEllipticNomeQ InverseErf InverseErfc InverseFourier InverseFourierCosTransform InverseFourierSequenceTransform InverseFourierSinTransform InverseFourierTransform InverseFunction InverseFunctions InverseGammaDistribution InverseGammaRegularized InverseGaussianDistribution InverseGudermannian InverseHankelTransform InverseHaversine InverseImagePyramid InverseJacobiCD InverseJacobiCN InverseJacobiCS InverseJacobiDC InverseJacobiDN InverseJacobiDS InverseJacobiNC InverseJacobiND InverseJacobiNS InverseJacobiSC InverseJacobiSD InverseJacobiSN InverseLaplaceTransform InverseMellinTransform InversePermutation InverseRadon InverseRadonTransform InverseSeries InverseShortTimeFourier InverseSpectrogram InverseSurvivalFunction InverseTransformedRegion InverseWaveletTransform InverseWeierstrassP InverseWishartMatrixDistribution InverseZTransform Invisible InvisibleApplication InvisibleTimes IPAddress IrreduciblePolynomialQ IslandData IsolatingInterval IsomorphicGraphQ IsotopeData Italic Item ItemAspectRatio ItemBox ItemBoxOptions ItemSize ItemStyle ItoProcessJaccardDissimilarity JacobiAmplitude Jacobian JacobiCD JacobiCN JacobiCS JacobiDC JacobiDN JacobiDS JacobiNC JacobiND JacobiNS JacobiP JacobiSC JacobiSD JacobiSN JacobiSymbol JacobiZeta JankoGroupJ1 JankoGroupJ2 JankoGroupJ3 JankoGroupJ4 JarqueBeraALMTest JohnsonDistribution Join JoinAcross Joined JoinedCurve JoinedCurveBox JoinedCurveBoxOptions JoinForm JordanDecomposition JordanModelDecomposition JulianDate JuliaSetBoettcher JuliaSetIterationCount JuliaSetPlot JuliaSetPointsK KagiChart KaiserBesselWindow KaiserWindow KalmanEstimator KalmanFilter KarhunenLoeveDecomposition KaryTree KatzCentrality KCoreComponents KDistribution KEdgeConnectedComponents KEdgeConnectedGraphQ KelvinBei KelvinBer KelvinKei KelvinKer KendallTau KendallTauTest KernelExecute KernelFunction KernelMixtureDistribution Kernels Ket Key KeyCollisionFunction KeyComplement KeyDrop KeyDropFrom KeyExistsQ KeyFreeQ KeyIntersection KeyMap KeyMemberQ KeypointStrength Keys KeySelect KeySort KeySortBy KeyTake KeyUnion KeyValueMap KeyValuePattern Khinchin KillProcess KirchhoffGraph KirchhoffMatrix KleinInvariantJ KnapsackSolve KnightTourGraph KnotData KnownUnitQ KochCurve KolmogorovSmirnovTest KroneckerDelta KroneckerModelDecomposition KroneckerProduct KroneckerSymbol KuiperTest KumaraswamyDistribution Kurtosis KuwaharaFilter KVertexConnectedComponents KVertexConnectedGraphQLABColor Label Labeled LabeledSlider LabelingFunction LabelingSize LabelStyle LabelVisibility LaguerreL LakeData LambdaComponents LambertW LaminaData LanczosWindow LandauDistribution Language LanguageCategory LanguageData LanguageIdentify LanguageOptions LaplaceDistribution LaplaceTransform Laplacian LaplacianFilter LaplacianGaussianFilter Large Larger Last Latitude LatitudeLongitude LatticeData LatticeReduce Launch LaunchKernels LayeredGraphPlot LayerSizeFunction LayoutInformation LCHColor LCM LeaderSize LeafCount LeapYearQ LearnDistribution LearnedDistribution LearningRate LearningRateMultipliers LeastSquares LeastSquaresFilterKernel Left LeftArrow LeftArrowBar LeftArrowRightArrow LeftDownTeeVector LeftDownVector LeftDownVectorBar LeftRightArrow LeftRightVector LeftTee LeftTeeArrow LeftTeeVector LeftTriangle LeftTriangleBar LeftTriangleEqual LeftUpDownVector LeftUpTeeVector LeftUpVector LeftUpVectorBar LeftVector LeftVectorBar LegendAppearance Legended LegendFunction LegendLabel LegendLayout LegendMargins LegendMarkers LegendMarkerSize LegendreP LegendreQ LegendreType Length LengthWhile LerchPhi Less LessEqual LessEqualGreater LessEqualThan LessFullEqual LessGreater LessLess LessSlantEqual LessThan LessTilde LetterCharacter LetterCounts LetterNumber LetterQ Level LeveneTest LeviCivitaTensor LevyDistribution Lexicographic LibraryDataType LibraryFunction LibraryFunctionError LibraryFunctionInformation LibraryFunctionLoad LibraryFunctionUnload LibraryLoad LibraryUnload LicenseID LiftingFilterData LiftingWaveletTransform LightBlue LightBrown LightCyan Lighter LightGray LightGreen Lighting LightingAngle LightMagenta LightOrange LightPink LightPurple LightRed LightSources LightYellow Likelihood Limit LimitsPositioning LimitsPositioningTokens LindleyDistribution Line Line3DBox Line3DBoxOptions LinearFilter LinearFractionalOptimization LinearFractionalTransform LinearGradientImage LinearizingTransformationData LinearLayer LinearModelFit LinearOffsetFunction LinearOptimization LinearProgramming LinearRecurrence LinearSolve LinearSolveFunction LineBox LineBoxOptions LineBreak LinebreakAdjustments LineBreakChart LinebreakSemicolonWeighting LineBreakWithin LineColor LineGraph LineIndent LineIndentMaxFraction LineIntegralConvolutionPlot LineIntegralConvolutionScale LineLegend LineOpacity LineSpacing LineWrapParts LinkActivate LinkClose LinkConnect LinkConnectedQ LinkCreate LinkError LinkFlush LinkFunction LinkHost LinkInterrupt LinkLaunch LinkMode LinkObject LinkOpen LinkOptions LinkPatterns LinkProtocol LinkRankCentrality LinkRead LinkReadHeld LinkReadyQ Links LinkService LinkWrite LinkWriteHeld LiouvilleLambda List Listable ListAnimate ListContourPlot ListContourPlot3D ListConvolve ListCorrelate ListCurvePathPlot ListDeconvolve ListDensityPlot ListDensityPlot3D Listen ListFormat ListFourierSequenceTransform ListInterpolation ListLineIntegralConvolutionPlot ListLinePlot ListLogLinearPlot ListLogLogPlot ListLogPlot ListPicker ListPickerBox ListPickerBoxBackground ListPickerBoxOptions ListPlay ListPlot ListPlot3D ListPointPlot3D ListPolarPlot ListQ ListSliceContourPlot3D ListSliceDensityPlot3D ListSliceVectorPlot3D ListStepPlot ListStreamDensityPlot ListStreamPlot ListSurfacePlot3D ListVectorDensityPlot ListVectorPlot ListVectorPlot3D ListZTransform Literal LiteralSearch LocalAdaptiveBinarize LocalCache LocalClusteringCoefficient LocalizeDefinitions LocalizeVariables LocalObject LocalObjects LocalResponseNormalizationLayer LocalSubmit LocalSymbol LocalTime LocalTimeZone LocationEquivalenceTest LocationTest Locator LocatorAutoCreate LocatorBox LocatorBoxOptions LocatorCentering LocatorPane LocatorPaneBox LocatorPaneBoxOptions LocatorRegion Locked Log Log10 Log2 LogBarnesG LogGamma LogGammaDistribution LogicalExpand LogIntegral LogisticDistribution LogisticSigmoid LogitModelFit LogLikelihood LogLinearPlot LogLogisticDistribution LogLogPlot LogMultinormalDistribution LogNormalDistribution LogPlot LogRankTest LogSeriesDistribution LongEqual Longest LongestCommonSequence LongestCommonSequencePositions LongestCommonSubsequence LongestCommonSubsequencePositions LongestMatch LongestOrderedSequence LongForm Longitude LongLeftArrow LongLeftRightArrow LongRightArrow LongShortTermMemoryLayer Lookup Loopback LoopFreeGraphQ LossFunction LowerCaseQ LowerLeftArrow LowerRightArrow LowerTriangularize LowerTriangularMatrixQ LowpassFilter LQEstimatorGains LQGRegulator LQOutputRegulatorGains LQRegulatorGains LUBackSubstitution LucasL LuccioSamiComponents LUDecomposition LunarEclipse LUVColor LyapunovSolve LyonsGroupLyMachineID MachineName MachineNumberQ MachinePrecision MacintoshSystemPageSetup Magenta Magnification Magnify MailAddressValidation MailExecute MailFolder MailItem MailReceiverFunction MailResponseFunction MailSearch MailServerConnect MailServerConnection MailSettings MainSolve MaintainDynamicCaches Majority MakeBoxes MakeExpression MakeRules ManagedLibraryExpressionID ManagedLibraryExpressionQ MandelbrotSetBoettcher MandelbrotSetDistance MandelbrotSetIterationCount MandelbrotSetMemberQ MandelbrotSetPlot MangoldtLambda ManhattanDistance Manipulate Manipulator MannedSpaceMissionData MannWhitneyTest MantissaExponent Manual Map MapAll MapAt MapIndexed MAProcess MapThread MarchenkoPasturDistribution MarcumQ MardiaCombinedTest MardiaKurtosisTest MardiaSkewnessTest MarginalDistribution MarkovProcessProperties Masking MatchingDissimilarity MatchLocalNameQ MatchLocalNames MatchQ Material MathematicalFunctionData MathematicaNotation MathieuC MathieuCharacteristicA MathieuCharacteristicB MathieuCharacteristicExponent MathieuCPrime MathieuGroupM11 MathieuGroupM12 MathieuGroupM22 MathieuGroupM23 MathieuGroupM24 MathieuS MathieuSPrime MathMLForm MathMLText Matrices MatrixExp MatrixForm MatrixFunction MatrixLog MatrixNormalDistribution MatrixPlot MatrixPower MatrixPropertyDistribution MatrixQ MatrixRank MatrixTDistribution Max MaxBend MaxCellMeasure MaxColorDistance MaxDetect MaxDuration MaxExtraBandwidths MaxExtraConditions MaxFeatureDisplacement MaxFeatures MaxFilter MaximalBy Maximize MaxItems MaxIterations MaxLimit MaxMemoryUsed MaxMixtureKernels MaxOverlapFraction MaxPlotPoints MaxPoints MaxRecursion MaxStableDistribution MaxStepFraction MaxSteps MaxStepSize MaxTrainingRounds MaxValue MaxwellDistribution MaxWordGap McLaughlinGroupMcL Mean MeanAbsoluteLossLayer MeanAround MeanClusteringCoefficient MeanDegreeConnectivity MeanDeviation MeanFilter MeanGraphDistance MeanNeighborDegree MeanShift MeanShiftFilter MeanSquaredLossLayer Median MedianDeviation MedianFilter MedicalTestData Medium MeijerG MeijerGReduce MeixnerDistribution MellinConvolve MellinTransform MemberQ MemoryAvailable MemoryConstrained MemoryConstraint MemoryInUse MengerMesh Menu MenuAppearance MenuCommandKey MenuEvaluator MenuItem MenuList MenuPacket MenuSortingValue MenuStyle MenuView Merge MergeDifferences MergingFunction MersennePrimeExponent MersennePrimeExponentQ Mesh MeshCellCentroid MeshCellCount MeshCellHighlight MeshCellIndex MeshCellLabel MeshCellMarker MeshCellMeasure MeshCellQuality MeshCells MeshCellShapeFunction MeshCellStyle MeshCoordinates MeshFunctions MeshPrimitives MeshQualityGoal MeshRange MeshRefinementFunction MeshRegion MeshRegionQ MeshShading MeshStyle Message MessageDialog MessageList MessageName MessageObject MessageOptions MessagePacket Messages MessagesNotebook MetaCharacters MetaInformation MeteorShowerData Method MethodOptions MexicanHatWavelet MeyerWavelet Midpoint Min MinColorDistance MinDetect MineralData MinFilter MinimalBy MinimalPolynomial MinimalStateSpaceModel Minimize MinimumTimeIncrement MinIntervalSize MinkowskiQuestionMark MinLimit MinMax MinorPlanetData Minors MinRecursion MinSize MinStableDistribution Minus MinusPlus MinValue Missing MissingBehavior MissingDataMethod MissingDataRules MissingQ MissingString MissingStyle MissingValuePattern MittagLefflerE MixedFractionParts MixedGraphQ MixedMagnitude MixedRadix MixedRadixQuantity MixedUnit MixtureDistribution Mod Modal Mode Modular ModularInverse ModularLambda Module Modulus MoebiusMu Molecule MoleculeContainsQ MoleculeEquivalentQ MoleculeGraph MoleculeModify MoleculePattern MoleculePlot MoleculePlot3D MoleculeProperty MoleculeQ MoleculeValue Moment Momentary MomentConvert MomentEvaluate MomentGeneratingFunction MomentOfInertia Monday Monitor MonomialList MonomialOrder MonsterGroupM MoonPhase MoonPosition MorletWavelet MorphologicalBinarize MorphologicalBranchPoints MorphologicalComponents MorphologicalEulerNumber MorphologicalGraph MorphologicalPerimeter MorphologicalTransform MortalityData Most MountainData MouseAnnotation MouseAppearance MouseAppearanceTag MouseButtons Mouseover MousePointerNote MousePosition MovieData MovingAverage MovingMap MovingMedian MoyalDistribution Multicolumn MultiedgeStyle MultigraphQ MultilaunchWarning MultiLetterItalics MultiLetterStyle MultilineFunction Multinomial MultinomialDistribution MultinormalDistribution MultiplicativeOrder Multiplicity MultiplySides Multiselection MultivariateHypergeometricDistribution MultivariatePoissonDistribution MultivariateTDistributionN NakagamiDistribution NameQ Names NamespaceBox NamespaceBoxOptions Nand NArgMax NArgMin NBernoulliB NBodySimulation NBodySimulationData NCache NDEigensystem NDEigenvalues NDSolve NDSolveValue Nearest NearestFunction NearestNeighborGraph NearestTo NebulaData NeedCurrentFrontEndPackagePacket NeedCurrentFrontEndSymbolsPacket NeedlemanWunschSimilarity Needs Negative NegativeBinomialDistribution NegativeDefiniteMatrixQ NegativeIntegers NegativeMultinomialDistribution NegativeRationals NegativeReals NegativeSemidefiniteMatrixQ NeighborhoodData NeighborhoodGraph Nest NestedGreaterGreater NestedLessLess NestedScriptRules NestGraph NestList NestWhile NestWhileList NetAppend NetBidirectionalOperator NetChain NetDecoder NetDelete NetDrop NetEncoder NetEvaluationMode NetExtract NetFlatten NetFoldOperator NetGraph NetInformation NetInitialize NetInsert NetInsertSharedArrays NetJoin NetMapOperator NetMapThreadOperator NetMeasurements NetModel NetNestOperator NetPairEmbeddingOperator NetPort NetPortGradient NetPrepend NetRename NetReplace NetReplacePart NetSharedArray NetStateObject NetTake NetTrain NetTrainResultsObject NetworkPacketCapture NetworkPacketRecording NetworkPacketRecordingDuring NetworkPacketTrace NeumannValue NevilleThetaC NevilleThetaD NevilleThetaN NevilleThetaS NewPrimitiveStyle NExpectation Next NextCell NextDate NextPrime NextScheduledTaskTime NHoldAll NHoldFirst NHoldRest NicholsGridLines NicholsPlot NightHemisphere NIntegrate NMaximize NMaxValue NMinimize NMinValue NominalVariables NonAssociative NoncentralBetaDistribution NoncentralChiSquareDistribution NoncentralFRatioDistribution NoncentralStudentTDistribution NonCommutativeMultiply NonConstants NondimensionalizationTransform None NoneTrue NonlinearModelFit NonlinearStateSpaceModel NonlocalMeansFilter NonNegative NonNegativeIntegers NonNegativeRationals NonNegativeReals NonPositive NonPositiveIntegers NonPositiveRationals NonPositiveReals Nor NorlundB Norm Normal NormalDistribution NormalGrouping NormalizationLayer Normalize Normalized NormalizedSquaredEuclideanDistance NormalMatrixQ NormalsFunction NormFunction Not NotCongruent NotCupCap NotDoubleVerticalBar Notebook NotebookApply NotebookAutoSave NotebookClose NotebookConvertSettings NotebookCreate NotebookCreateReturnObject NotebookDefault NotebookDelete NotebookDirectory NotebookDynamicExpression NotebookEvaluate NotebookEventActions NotebookFileName NotebookFind NotebookFindReturnObject NotebookGet NotebookGetLayoutInformationPacket NotebookGetMisspellingsPacket NotebookImport NotebookInformation NotebookInterfaceObject NotebookLocate NotebookObject NotebookOpen NotebookOpenReturnObject NotebookPath NotebookPrint NotebookPut NotebookPutReturnObject NotebookRead NotebookResetGeneratedCells Notebooks NotebookSave NotebookSaveAs NotebookSelection NotebookSetupLayoutInformationPacket NotebooksMenu NotebookTemplate NotebookWrite NotElement NotEqualTilde NotExists NotGreater NotGreaterEqual NotGreaterFullEqual NotGreaterGreater NotGreaterLess NotGreaterSlantEqual NotGreaterTilde Nothing NotHumpDownHump NotHumpEqual NotificationFunction NotLeftTriangle NotLeftTriangleBar NotLeftTriangleEqual NotLess NotLessEqual NotLessFullEqual NotLessGreater NotLessLess NotLessSlantEqual NotLessTilde NotNestedGreaterGreater NotNestedLessLess NotPrecedes NotPrecedesEqual NotPrecedesSlantEqual NotPrecedesTilde NotReverseElement NotRightTriangle NotRightTriangleBar NotRightTriangleEqual NotSquareSubset NotSquareSubsetEqual NotSquareSuperset NotSquareSupersetEqual NotSubset NotSubsetEqual NotSucceeds NotSucceedsEqual NotSucceedsSlantEqual NotSucceedsTilde NotSuperset NotSupersetEqual NotTilde NotTildeEqual NotTildeFullEqual NotTildeTilde NotVerticalBar Now NoWhitespace NProbability NProduct NProductFactors NRoots NSolve NSum NSumTerms NuclearExplosionData NuclearReactorData Null NullRecords NullSpace NullWords Number NumberCompose NumberDecompose NumberExpand NumberFieldClassNumber NumberFieldDiscriminant NumberFieldFundamentalUnits NumberFieldIntegralBasis NumberFieldNormRepresentatives NumberFieldRegulator NumberFieldRootsOfUnity NumberFieldSignature NumberForm NumberFormat NumberLinePlot NumberMarks NumberMultiplier NumberPadding NumberPoint NumberQ NumberSeparator NumberSigns NumberString Numerator NumeratorDenominator NumericalOrder NumericalSort NumericArray NumericArrayQ NumericArrayType NumericFunction NumericQ NuttallWindow NValues NyquistGridLines NyquistPlotO ObservabilityGramian ObservabilityMatrix ObservableDecomposition ObservableModelQ OceanData Octahedron OddQ Off Offset OLEData On ONanGroupON Once OneIdentity Opacity OpacityFunction OpacityFunctionScaling Open OpenAppend Opener OpenerBox OpenerBoxOptions OpenerView OpenFunctionInspectorPacket Opening OpenRead OpenSpecialOptions OpenTemporary OpenWrite Operate OperatingSystem OptimumFlowData Optional OptionalElement OptionInspectorSettings OptionQ Options OptionsPacket OptionsPattern OptionValue OptionValueBox OptionValueBoxOptions Or Orange Order OrderDistribution OrderedQ Ordering OrderingBy OrderingLayer Orderless OrderlessPatternSequence OrnsteinUhlenbeckProcess Orthogonalize OrthogonalMatrixQ Out Outer OuterPolygon OuterPolyhedron OutputAutoOverwrite OutputControllabilityMatrix OutputControllableModelQ OutputForm OutputFormData OutputGrouping OutputMathEditExpression OutputNamePacket OutputResponse OutputSizeLimit OutputStream Over OverBar OverDot Overflow OverHat Overlaps Overlay OverlayBox OverlayBoxOptions Overscript OverscriptBox OverscriptBoxOptions OverTilde OverVector OverwriteTarget OwenT OwnValuesPackage PackingMethod PaddedForm Padding PaddingLayer PaddingSize PadeApproximant PadLeft PadRight PageBreakAbove PageBreakBelow PageBreakWithin PageFooterLines PageFooters PageHeaderLines PageHeaders PageHeight PageRankCentrality PageTheme PageWidth Pagination PairedBarChart PairedHistogram PairedSmoothHistogram PairedTTest PairedZTest PaletteNotebook PalettePath PalindromeQ Pane PaneBox PaneBoxOptions Panel PanelBox PanelBoxOptions Paneled PaneSelector PaneSelectorBox PaneSelectorBoxOptions PaperWidth ParabolicCylinderD ParagraphIndent ParagraphSpacing ParallelArray ParallelCombine ParallelDo Parallelepiped ParallelEvaluate Parallelization Parallelize ParallelMap ParallelNeeds Parallelogram ParallelProduct ParallelSubmit ParallelSum ParallelTable ParallelTry Parameter ParameterEstimator ParameterMixtureDistribution ParameterVariables ParametricFunction ParametricNDSolve ParametricNDSolveValue ParametricPlot ParametricPlot3D ParametricRegion ParentBox ParentCell ParentConnect ParentDirectory ParentForm Parenthesize ParentList ParentNotebook ParetoDistribution ParetoPickandsDistribution ParkData Part PartBehavior PartialCorrelationFunction PartialD ParticleAcceleratorData ParticleData Partition PartitionGranularity PartitionsP PartitionsQ PartLayer PartOfSpeech PartProtection ParzenWindow PascalDistribution PassEventsDown PassEventsUp Paste PasteAutoQuoteCharacters PasteBoxFormInlineCells PasteButton Path PathGraph PathGraphQ Pattern PatternSequence PatternTest PauliMatrix PaulWavelet Pause PausedTime PDF PeakDetect PeanoCurve PearsonChiSquareTest PearsonCorrelationTest PearsonDistribution PercentForm PerfectNumber PerfectNumberQ PerformanceGoal Perimeter PeriodicBoundaryCondition PeriodicInterpolation Periodogram PeriodogramArray Permanent Permissions PermissionsGroup PermissionsGroupMemberQ PermissionsGroups PermissionsKey PermissionsKeys PermutationCycles PermutationCyclesQ PermutationGroup PermutationLength PermutationList PermutationListQ PermutationMax PermutationMin PermutationOrder PermutationPower PermutationProduct PermutationReplace Permutations PermutationSupport Permute PeronaMalikFilter Perpendicular PerpendicularBisector PersistenceLocation PersistenceTime PersistentObject PersistentObjects PersistentValue PersonData PERTDistribution PetersenGraph PhaseMargins PhaseRange PhysicalSystemData Pi Pick PIDData PIDDerivativeFilter PIDFeedforward PIDTune Piecewise PiecewiseExpand PieChart PieChart3D PillaiTrace PillaiTraceTest PingTime Pink PitchRecognize Pivoting PixelConstrained PixelValue PixelValuePositions Placed Placeholder PlaceholderReplace Plain PlanarAngle PlanarGraph PlanarGraphQ PlanckRadiationLaw PlaneCurveData PlanetaryMoonData PlanetData PlantData Play PlayRange Plot Plot3D Plot3Matrix PlotDivision PlotJoined PlotLabel PlotLabels PlotLayout PlotLegends PlotMarkers PlotPoints PlotRange PlotRangeClipping PlotRangeClipPlanesStyle PlotRangePadding PlotRegion PlotStyle PlotTheme Pluralize Plus PlusMinus Pochhammer PodStates PodWidth Point Point3DBox Point3DBoxOptions PointBox PointBoxOptions PointFigureChart PointLegend PointSize PoissonConsulDistribution PoissonDistribution PoissonProcess PoissonWindow PolarAxes PolarAxesOrigin PolarGridLines PolarPlot PolarTicks PoleZeroMarkers PolyaAeppliDistribution PolyGamma Polygon Polygon3DBox Polygon3DBoxOptions PolygonalNumber PolygonAngle PolygonBox PolygonBoxOptions PolygonCoordinates PolygonDecomposition PolygonHoleScale PolygonIntersections PolygonScale Polyhedron PolyhedronAngle PolyhedronCoordinates PolyhedronData PolyhedronDecomposition PolyhedronGenus PolyLog PolynomialExtendedGCD PolynomialForm PolynomialGCD PolynomialLCM PolynomialMod PolynomialQ PolynomialQuotient PolynomialQuotientRemainder PolynomialReduce PolynomialRemainder Polynomials PoolingLayer PopupMenu PopupMenuBox PopupMenuBoxOptions PopupView PopupWindow Position PositionIndex Positive PositiveDefiniteMatrixQ PositiveIntegers PositiveRationals PositiveReals PositiveSemidefiniteMatrixQ PossibleZeroQ Postfix PostScript Power PowerDistribution PowerExpand PowerMod PowerModList PowerRange PowerSpectralDensity PowersRepresentations PowerSymmetricPolynomial Precedence PrecedenceForm Precedes PrecedesEqual PrecedesSlantEqual PrecedesTilde Precision PrecisionGoal PreDecrement Predict PredictionRoot PredictorFunction PredictorInformation PredictorMeasurements PredictorMeasurementsObject PreemptProtect PreferencesPath Prefix PreIncrement Prepend PrependLayer PrependTo PreprocessingRules PreserveColor PreserveImageOptions Previous PreviousCell PreviousDate PriceGraphDistribution PrimaryPlaceholder Prime PrimeNu PrimeOmega PrimePi PrimePowerQ PrimeQ Primes PrimeZetaP PrimitivePolynomialQ PrimitiveRoot PrimitiveRootList PrincipalComponents PrincipalValue Print PrintableASCIIQ PrintAction PrintForm PrintingCopies PrintingOptions PrintingPageRange PrintingStartingPageNumber PrintingStyleEnvironment Printout3D Printout3DPreviewer PrintPrecision PrintTemporary Prism PrismBox PrismBoxOptions PrivateCellOptions PrivateEvaluationOptions PrivateFontOptions PrivateFrontEndOptions PrivateKey PrivateNotebookOptions PrivatePaths Probability ProbabilityDistribution ProbabilityPlot ProbabilityPr ProbabilityScalePlot ProbitModelFit ProcessConnection ProcessDirectory ProcessEnvironment Processes ProcessEstimator ProcessInformation ProcessObject ProcessParameterAssumptions ProcessParameterQ ProcessStateDomain ProcessStatus ProcessTimeDomain Product ProductDistribution ProductLog ProgressIndicator ProgressIndicatorBox ProgressIndicatorBoxOptions Projection Prolog PromptForm ProofObject Properties Property PropertyList PropertyValue Proportion Proportional Protect Protected ProteinData Pruning PseudoInverse PsychrometricPropertyData PublicKey PublisherID PulsarData PunctuationCharacter Purple Put PutAppend Pyramid PyramidBox PyramidBoxOptionsQBinomial QFactorial QGamma QHypergeometricPFQ QnDispersion QPochhammer QPolyGamma QRDecomposition QuadraticIrrationalQ QuadraticOptimization Quantile QuantilePlot Quantity QuantityArray QuantityDistribution QuantityForm QuantityMagnitude QuantityQ QuantityUnit QuantityVariable QuantityVariableCanonicalUnit QuantityVariableDimensions QuantityVariableIdentifier QuantityVariablePhysicalQuantity Quartics QuartileDeviation Quartiles QuartileSkewness Query QueueingNetworkProcess QueueingProcess QueueProperties Quiet Quit Quotient QuotientRemainderRadialGradientImage RadialityCentrality RadicalBox RadicalBoxOptions RadioButton RadioButtonBar RadioButtonBox RadioButtonBoxOptions Radon RadonTransform RamanujanTau RamanujanTauL RamanujanTauTheta RamanujanTauZ Ramp Random RandomChoice RandomColor RandomComplex RandomEntity RandomFunction RandomGeoPosition RandomGraph RandomImage RandomInstance RandomInteger RandomPermutation RandomPoint RandomPolygon RandomPolyhedron RandomPrime RandomReal RandomSample RandomSeed RandomSeeding RandomVariate RandomWalkProcess RandomWord Range RangeFilter RangeSpecification RankedMax RankedMin RarerProbability Raster Raster3D Raster3DBox Raster3DBoxOptions RasterArray RasterBox RasterBoxOptions Rasterize RasterSize Rational RationalFunctions Rationalize Rationals Ratios RawArray RawBoxes RawData RawMedium RayleighDistribution Re Read ReadByteArray ReadLine ReadList ReadProtected ReadString Real RealAbs RealBlockDiagonalForm RealDigits RealExponent Reals RealSign Reap RecognitionPrior RecognitionThreshold Record RecordLists RecordSeparators Rectangle RectangleBox RectangleBoxOptions RectangleChart RectangleChart3D RectangularRepeatingElement RecurrenceFilter RecurrenceTable RecurringDigitsForm Red Reduce RefBox ReferenceLineStyle ReferenceMarkers ReferenceMarkerStyle Refine ReflectionMatrix ReflectionTransform Refresh RefreshRate Region RegionBinarize RegionBoundary RegionBounds RegionCentroid RegionDifference RegionDimension RegionDisjoint RegionDistance RegionDistanceFunction RegionEmbeddingDimension RegionEqual RegionFunction RegionImage RegionIntersection RegionMeasure RegionMember RegionMemberFunction RegionMoment RegionNearest RegionNearestFunction RegionPlot RegionPlot3D RegionProduct RegionQ RegionResize RegionSize RegionSymmetricDifference RegionUnion RegionWithin RegisterExternalEvaluator RegularExpression Regularization RegularlySampledQ RegularPolygon ReIm ReImLabels ReImPlot ReImStyle Reinstall RelationalDatabase RelationGraph Release ReleaseHold ReliabilityDistribution ReliefImage ReliefPlot RemoteAuthorizationCaching RemoteConnect RemoteConnectionObject RemoteFile RemoteRun RemoteRunProcess Remove RemoveAlphaChannel RemoveAsynchronousTask RemoveAudioStream RemoveBackground RemoveChannelListener RemoveChannelSubscribers Removed RemoveDiacritics RemoveInputStreamMethod RemoveOutputStreamMethod RemoveProperty RemoveScheduledTask RemoveUsers RenameDirectory RenameFile RenderAll RenderingOptions RenewalProcess RenkoChart RepairMesh Repeated RepeatedNull RepeatedString RepeatedTiming RepeatingElement Replace ReplaceAll ReplaceHeldPart ReplaceImageValue ReplaceList ReplacePart ReplacePixelValue ReplaceRepeated ReplicateLayer RequiredPhysicalQuantities Resampling ResamplingAlgorithmData ResamplingMethod Rescale RescalingTransform ResetDirectory ResetMenusPacket ResetScheduledTask ReshapeLayer Residue ResizeLayer Resolve ResourceAcquire ResourceData ResourceFunction ResourceObject ResourceRegister ResourceRemove ResourceSearch ResourceSubmissionObject ResourceSubmit ResourceSystemBase ResourceUpdate ResponseForm Rest RestartInterval Restricted Resultant ResumePacket Return ReturnEntersInput ReturnExpressionPacket ReturnInputFormPacket ReturnPacket ReturnReceiptFunction ReturnTextPacket Reverse ReverseBiorthogonalSplineWavelet ReverseElement ReverseEquilibrium ReverseGraph ReverseSort ReverseSortBy ReverseUpEquilibrium RevolutionAxis RevolutionPlot3D RGBColor RiccatiSolve RiceDistribution RidgeFilter RiemannR RiemannSiegelTheta RiemannSiegelZ RiemannXi Riffle Right RightArrow RightArrowBar RightArrowLeftArrow RightComposition RightCosetRepresentative RightDownTeeVector RightDownVector RightDownVectorBar RightTee RightTeeArrow RightTeeVector RightTriangle RightTriangleBar RightTriangleEqual RightUpDownVector RightUpTeeVector RightUpVector RightUpVectorBar RightVector RightVectorBar RiskAchievementImportance RiskReductionImportance RogersTanimotoDissimilarity RollPitchYawAngles RollPitchYawMatrix RomanNumeral Root RootApproximant RootIntervals RootLocusPlot RootMeanSquare RootOfUnityQ RootReduce Roots RootSum Rotate RotateLabel RotateLeft RotateRight RotationAction RotationBox RotationBoxOptions RotationMatrix RotationTransform Round RoundImplies RoundingRadius Row RowAlignments RowBackgrounds RowBox RowHeights RowLines RowMinHeight RowReduce RowsEqual RowSpacings RSolve RSolveValue RudinShapiro RudvalisGroupRu Rule RuleCondition RuleDelayed RuleForm RulePlot RulerUnits Run RunProcess RunScheduledTask RunThrough RuntimeAttributes RuntimeOptions RussellRaoDissimilaritySameQ SameTest SampledEntityClass SampleDepth SampledSoundFunction SampledSoundList SampleRate SamplingPeriod SARIMAProcess SARMAProcess SASTriangle SatelliteData SatisfiabilityCount SatisfiabilityInstances SatisfiableQ Saturday Save Saveable SaveAutoDelete SaveConnection SaveDefinitions SavitzkyGolayMatrix SawtoothWave Scale Scaled ScaleDivisions ScaledMousePosition ScaleOrigin ScalePadding ScaleRanges ScaleRangeStyle ScalingFunctions ScalingMatrix ScalingTransform Scan ScheduledTask ScheduledTaskActiveQ ScheduledTaskInformation ScheduledTaskInformationData ScheduledTaskObject ScheduledTasks SchurDecomposition ScientificForm ScientificNotationThreshold ScorerGi ScorerGiPrime ScorerHi ScorerHiPrime ScreenRectangle ScreenStyleEnvironment ScriptBaselineShifts ScriptForm ScriptLevel ScriptMinSize ScriptRules ScriptSizeMultipliers Scrollbars ScrollingOptions ScrollPosition SearchAdjustment SearchIndexObject SearchIndices SearchQueryString SearchResultObject Sec Sech SechDistribution SecondOrderConeOptimization SectionGrouping SectorChart SectorChart3D SectorOrigin SectorSpacing SecuredAuthenticationKey SecuredAuthenticationKeys SeedRandom Select Selectable SelectComponents SelectedCells SelectedNotebook SelectFirst Selection SelectionAnimate SelectionCell SelectionCellCreateCell SelectionCellDefaultStyle SelectionCellParentStyle SelectionCreateCell SelectionDebuggerTag SelectionDuplicateCell SelectionEvaluate SelectionEvaluateCreateCell SelectionMove SelectionPlaceholder SelectionSetStyle SelectWithContents SelfLoops SelfLoopStyle SemanticImport SemanticImportString SemanticInterpretation SemialgebraicComponentInstances SemidefiniteOptimization SendMail SendMessage Sequence SequenceAlignment SequenceAttentionLayer SequenceCases SequenceCount SequenceFold SequenceFoldList SequenceForm SequenceHold SequenceLastLayer SequenceMostLayer SequencePosition SequencePredict SequencePredictorFunction SequenceReplace SequenceRestLayer SequenceReverseLayer SequenceSplit Series SeriesCoefficient SeriesData ServiceConnect ServiceDisconnect ServiceExecute ServiceObject ServiceRequest ServiceResponse ServiceSubmit SessionSubmit SessionTime Set SetAccuracy SetAlphaChannel SetAttributes Setbacks SetBoxFormNamesPacket SetCloudDirectory SetCookies SetDelayed SetDirectory SetEnvironment SetEvaluationNotebook SetFileDate SetFileLoadingContext SetNotebookStatusLine SetOptions SetOptionsPacket SetPermissions SetPrecision SetProperty SetSecuredAuthenticationKey SetSelectedNotebook SetSharedFunction SetSharedVariable SetSpeechParametersPacket SetStreamPosition SetSystemModel SetSystemOptions Setter SetterBar SetterBox SetterBoxOptions Setting SetUsers SetValue Shading Shallow ShannonWavelet ShapiroWilkTest Share SharingList Sharpen ShearingMatrix ShearingTransform ShellRegion ShenCastanMatrix ShiftedGompertzDistribution ShiftRegisterSequence Short ShortDownArrow Shortest ShortestMatch ShortestPathFunction ShortLeftArrow ShortRightArrow ShortTimeFourier ShortTimeFourierData ShortUpArrow Show ShowAutoConvert ShowAutoSpellCheck ShowAutoStyles ShowCellBracket ShowCellLabel ShowCellTags ShowClosedCellArea ShowCodeAssist ShowContents ShowControls ShowCursorTracker ShowGroupOpenCloseIcon ShowGroupOpener ShowInvisibleCharacters ShowPageBreaks ShowPredictiveInterface ShowSelection ShowShortBoxForm ShowSpecialCharacters ShowStringCharacters ShowSyntaxStyles ShrinkingDelay ShrinkWrapBoundingBox SiderealTime SiegelTheta SiegelTukeyTest SierpinskiCurve SierpinskiMesh Sign Signature SignedRankTest SignedRegionDistance SignificanceLevel SignPadding SignTest SimilarityRules SimpleGraph SimpleGraphQ SimplePolygonQ SimplePolyhedronQ Simplex Simplify Sin Sinc SinghMaddalaDistribution SingleEvaluation SingleLetterItalics SingleLetterStyle SingularValueDecomposition SingularValueList SingularValuePlot SingularValues Sinh SinhIntegral SinIntegral SixJSymbol Skeleton SkeletonTransform SkellamDistribution Skewness SkewNormalDistribution SkinStyle Skip SliceContourPlot3D SliceDensityPlot3D SliceDistribution SliceVectorPlot3D Slider Slider2D Slider2DBox Slider2DBoxOptions SliderBox SliderBoxOptions SlideView Slot SlotSequence Small SmallCircle Smaller SmithDecomposition SmithDelayCompensator SmithWatermanSimilarity SmoothDensityHistogram SmoothHistogram SmoothHistogram3D SmoothKernelDistribution SnDispersion Snippet SnubPolyhedron SocialMediaData Socket SocketConnect SocketListen SocketListener SocketObject SocketOpen SocketReadMessage SocketReadyQ Sockets SocketWaitAll SocketWaitNext SoftmaxLayer SokalSneathDissimilarity SolarEclipse SolarSystemFeatureData SolidAngle SolidData SolidRegionQ Solve SolveAlways SolveDelayed Sort SortBy SortedBy SortedEntityClass Sound SoundAndGraphics SoundNote SoundVolume SourceLink Sow Space SpaceCurveData SpaceForm Spacer Spacings Span SpanAdjustments SpanCharacterRounding SpanFromAbove SpanFromBoth SpanFromLeft SpanLineThickness SpanMaxSize SpanMinSize SpanningCharacters SpanSymmetric SparseArray SpatialGraphDistribution SpatialMedian SpatialTransformationLayer Speak SpeakTextPacket SpearmanRankTest SpearmanRho SpeciesData SpecificityGoal SpectralLineData Spectrogram SpectrogramArray Specularity SpeechRecognize SpeechSynthesize SpellingCorrection SpellingCorrectionList SpellingDictionaries SpellingDictionariesPath SpellingOptions SpellingSuggestionsPacket Sphere SphereBox SpherePoints SphericalBesselJ SphericalBesselY SphericalHankelH1 SphericalHankelH2 SphericalHarmonicY SphericalPlot3D SphericalRegion SphericalShell SpheroidalEigenvalue SpheroidalJoiningFactor SpheroidalPS SpheroidalPSPrime SpheroidalQS SpheroidalQSPrime SpheroidalRadialFactor SpheroidalS1 SpheroidalS1Prime SpheroidalS2 SpheroidalS2Prime Splice SplicedDistribution SplineClosed SplineDegree SplineKnots SplineWeights Split SplitBy SpokenString Sqrt SqrtBox SqrtBoxOptions Square SquaredEuclideanDistance SquareFreeQ SquareIntersection SquareMatrixQ SquareRepeatingElement SquaresR SquareSubset SquareSubsetEqual SquareSuperset SquareSupersetEqual SquareUnion SquareWave SSSTriangle StabilityMargins StabilityMarginsStyle StableDistribution Stack StackBegin StackComplete StackedDateListPlot StackedListPlot StackInhibit StadiumShape StandardAtmosphereData StandardDeviation StandardDeviationFilter StandardForm Standardize Standardized StandardOceanData StandbyDistribution Star StarClusterData StarData StarGraph StartAsynchronousTask StartExternalSession StartingStepSize StartOfLine StartOfString StartProcess StartScheduledTask StartupSound StartWebSession StateDimensions StateFeedbackGains StateOutputEstimator StateResponse StateSpaceModel StateSpaceRealization StateSpaceTransform StateTransformationLinearize StationaryDistribution StationaryWaveletPacketTransform StationaryWaveletTransform StatusArea StatusCentrality StepMonitor StereochemistryElements StieltjesGamma StirlingS1 StirlingS2 StopAsynchronousTask StoppingPowerData StopScheduledTask StrataVariables StratonovichProcess StreamColorFunction StreamColorFunctionScaling StreamDensityPlot StreamMarkers StreamPlot StreamPoints StreamPosition Streams StreamScale StreamStyle String StringBreak StringByteCount StringCases StringContainsQ StringCount StringDelete StringDrop StringEndsQ StringExpression StringExtract StringForm StringFormat StringFreeQ StringInsert StringJoin StringLength StringMatchQ StringPadLeft StringPadRight StringPart StringPartition StringPosition StringQ StringRepeat StringReplace StringReplaceList StringReplacePart StringReverse StringRiffle StringRotateLeft StringRotateRight StringSkeleton StringSplit StringStartsQ StringTake StringTemplate StringToByteArray StringToStream StringTrim StripBoxes StripOnInput StripWrapperBoxes StrokeForm StructuralImportance StructuredArray StructuredSelection StruveH StruveL Stub StudentTDistribution Style StyleBox StyleBoxAutoDelete StyleData StyleDefinitions StyleForm StyleHints StyleKeyMapping StyleMenuListing StyleNameDialogSettings StyleNames StylePrint StyleSheetPath Subdivide Subfactorial Subgraph SubMinus SubPlus SubresultantPolynomialRemainders SubresultantPolynomials Subresultants Subscript SubscriptBox SubscriptBoxOptions Subscripted Subsequences Subset SubsetEqual SubsetMap SubsetQ Subsets SubStar SubstitutionSystem Subsuperscript SubsuperscriptBox SubsuperscriptBoxOptions Subtract SubtractFrom SubtractSides SubValues Succeeds SucceedsEqual SucceedsSlantEqual SucceedsTilde Success SuchThat Sum SumConvergence SummationLayer Sunday SunPosition Sunrise Sunset SuperDagger SuperMinus SupernovaData SuperPlus Superscript SuperscriptBox SuperscriptBoxOptions Superset SupersetEqual SuperStar Surd SurdForm SurfaceArea SurfaceColor SurfaceData SurfaceGraphics SurvivalDistribution SurvivalFunction SurvivalModel SurvivalModelFit SuspendPacket SuzukiDistribution SuzukiGroupSuz SwatchLegend Switch Symbol SymbolName SymletWavelet Symmetric SymmetricGroup SymmetricKey SymmetricMatrixQ SymmetricPolynomial SymmetricReduction Symmetrize SymmetrizedArray SymmetrizedArrayRules SymmetrizedDependentComponents SymmetrizedIndependentComponents SymmetrizedReplacePart SynchronousInitialization SynchronousUpdating Synonyms Syntax SyntaxForm SyntaxInformation SyntaxLength SyntaxPacket SyntaxQ SynthesizeMissingValues SystemDialogInput SystemException SystemGet SystemHelpPath SystemInformation SystemInformationData SystemInstall SystemModel SystemModeler SystemModelExamples SystemModelLinearize SystemModelParametricSimulate SystemModelPlot SystemModelProgressReporting SystemModelReliability SystemModels SystemModelSimulate SystemModelSimulateSensitivity SystemModelSimulationData SystemOpen SystemOptions SystemProcessData SystemProcesses SystemsConnectionsModel SystemsModelDelay SystemsModelDelayApproximate SystemsModelDelete SystemsModelDimensions SystemsModelExtract SystemsModelFeedbackConnect SystemsModelLabels SystemsModelLinearity SystemsModelMerge SystemsModelOrder SystemsModelParallelConnect SystemsModelSeriesConnect SystemsModelStateFeedbackConnect SystemsModelVectorRelativeOrders SystemStub SystemTestTab TabFilling Table TableAlignments TableDepth TableDirections TableForm TableHeadings TableSpacing TableView TableViewBox TableViewBoxBackground TableViewBoxOptions TabSpacings TabView TabViewBox TabViewBoxOptions TagBox TagBoxNote TagBoxOptions TaggingRules TagSet TagSetDelayed TagStyle TagUnset Take TakeDrop TakeLargest TakeLargestBy TakeList TakeSmallest TakeSmallestBy TakeWhile Tally Tan Tanh TargetDevice TargetFunctions TargetSystem TargetUnits TaskAbort TaskExecute TaskObject TaskRemove TaskResume Tasks TaskSuspend TaskWait TautologyQ TelegraphProcess TemplateApply TemplateArgBox TemplateBox TemplateBoxOptions TemplateEvaluate TemplateExpression TemplateIf TemplateObject TemplateSequence TemplateSlot TemplateSlotSequence TemplateUnevaluated TemplateVerbatim TemplateWith TemporalData TemporalRegularity Temporary TemporaryVariable TensorContract TensorDimensions TensorExpand TensorProduct TensorQ TensorRank TensorReduce TensorSymmetry TensorTranspose TensorWedge TestID TestReport TestReportObject TestResultObject Tetrahedron TetrahedronBox TetrahedronBoxOptions TeXForm TeXSave Text Text3DBox Text3DBoxOptions TextAlignment TextBand TextBoundingBox TextBox TextCases TextCell TextClipboardType TextContents TextData TextElement TextForm TextGrid TextJustification TextLine TextPacket TextParagraph TextPosition TextRecognize TextSearch TextSearchReport TextSentences TextString TextStructure TextStyle TextTranslation Texture TextureCoordinateFunction TextureCoordinateScaling TextWords Therefore ThermodynamicData ThermometerGauge Thick Thickness Thin Thinning ThisLink ThompsonGroupTh Thread ThreadingLayer ThreeJSymbol Threshold Through Throw ThueMorse Thumbnail Thursday Ticks TicksStyle TideData Tilde TildeEqual TildeFullEqual TildeTilde TimeConstrained TimeConstraint TimeDirection TimeFormat TimeGoal TimelinePlot TimeObject TimeObjectQ Times TimesBy TimeSeries TimeSeriesAggregate TimeSeriesForecast TimeSeriesInsert TimeSeriesInvertibility TimeSeriesMap TimeSeriesMapThread TimeSeriesModel TimeSeriesModelFit TimeSeriesResample TimeSeriesRescale TimeSeriesShift TimeSeriesThread TimeSeriesWindow TimeUsed TimeValue TimeWarpingCorrespondence TimeWarpingDistance TimeZone TimeZoneConvert TimeZoneOffset Timing Tiny TitleGrouping TitsGroupT ToBoxes ToCharacterCode ToColor ToContinuousTimeModel ToDate Today ToDiscreteTimeModel ToEntity ToeplitzMatrix ToExpression ToFileName Together Toggle ToggleFalse Toggler TogglerBar TogglerBox TogglerBoxOptions ToHeldExpression ToInvertibleTimeSeries TokenWords Tolerance ToLowerCase Tomorrow ToNumberField TooBig Tooltip TooltipBox TooltipBoxOptions TooltipDelay TooltipStyle Top TopHatTransform ToPolarCoordinates TopologicalSort ToRadicals ToRules ToSphericalCoordinates ToString Total TotalHeight TotalLayer TotalVariationFilter TotalWidth TouchPosition TouchscreenAutoZoom TouchscreenControlPlacement ToUpperCase Tr Trace TraceAbove TraceAction TraceBackward TraceDepth TraceDialog TraceForward TraceInternal TraceLevel TraceOff TraceOn TraceOriginal TracePrint TraceScan TrackedSymbols TrackingFunction TracyWidomDistribution TradingChart TraditionalForm TraditionalFunctionNotation TraditionalNotation TraditionalOrder TrainingProgressCheckpointing TrainingProgressFunction TrainingProgressMeasurements TrainingProgressReporting TrainingStoppingCriterion TransferFunctionCancel TransferFunctionExpand TransferFunctionFactor TransferFunctionModel TransferFunctionPoles TransferFunctionTransform TransferFunctionZeros TransformationClass TransformationFunction TransformationFunctions TransformationMatrix TransformedDistribution TransformedField TransformedProcess TransformedRegion TransitionDirection TransitionDuration TransitionEffect TransitiveClosureGraph TransitiveReductionGraph Translate TranslationOptions TranslationTransform Transliterate Transparent TransparentColor Transpose TransposeLayer TrapSelection TravelDirections TravelDirectionsData TravelDistance TravelDistanceList TravelMethod TravelTime TreeForm TreeGraph TreeGraphQ TreePlot TrendStyle Triangle TriangleCenter TriangleConstruct TriangleMeasurement TriangleWave TriangularDistribution TriangulateMesh Trig TrigExpand TrigFactor TrigFactorList Trigger TrigReduce TrigToExp TrimmedMean TrimmedVariance TropicalStormData True TrueQ TruncatedDistribution TruncatedPolyhedron TsallisQExponentialDistribution TsallisQGaussianDistribution TTest Tube TubeBezierCurveBox TubeBezierCurveBoxOptions TubeBox TubeBoxOptions TubeBSplineCurveBox TubeBSplineCurveBoxOptions Tuesday TukeyLambdaDistribution TukeyWindow TunnelData Tuples TuranGraph TuringMachine TuttePolynomial TwoWayRule Typed TypeSpecifierUnateQ Uncompress UnconstrainedParameters Undefined UnderBar Underflow Underlined Underoverscript UnderoverscriptBox UnderoverscriptBoxOptions Underscript UnderscriptBox UnderscriptBoxOptions UnderseaFeatureData UndirectedEdge UndirectedGraph UndirectedGraphQ UndoOptions UndoTrackedVariables Unequal UnequalTo Unevaluated UniformDistribution UniformGraphDistribution UniformPolyhedron UniformSumDistribution Uninstall Union UnionPlus Unique UnitaryMatrixQ UnitBox UnitConvert UnitDimensions Unitize UnitRootTest UnitSimplify UnitStep UnitSystem UnitTriangle UnitVector UnitVectorLayer UnityDimensions UniverseModelData UniversityData UnixTime Unprotect UnregisterExternalEvaluator UnsameQ UnsavedVariables Unset UnsetShared UntrackedVariables Up UpArrow UpArrowBar UpArrowDownArrow Update UpdateDynamicObjects UpdateDynamicObjectsSynchronous UpdateInterval UpdateSearchIndex UpDownArrow UpEquilibrium UpperCaseQ UpperLeftArrow UpperRightArrow UpperTriangularize UpperTriangularMatrixQ Upsample UpSet UpSetDelayed UpTee UpTeeArrow UpTo UpValues URL URLBuild URLDecode URLDispatcher URLDownload URLDownloadSubmit URLEncode URLExecute URLExpand URLFetch URLFetchAsynchronous URLParse URLQueryDecode URLQueryEncode URLRead URLResponseTime URLSave URLSaveAsynchronous URLShorten URLSubmit UseGraphicsRange UserDefinedWavelet Using UsingFrontEnd UtilityFunctionV2Get ValenceErrorHandling ValidationLength ValidationSet Value ValueBox ValueBoxOptions ValueDimensions ValueForm ValuePreprocessingFunction ValueQ Values ValuesData Variables Variance VarianceEquivalenceTest VarianceEstimatorFunction VarianceGammaDistribution VarianceTest VectorAngle VectorAround VectorColorFunction VectorColorFunctionScaling VectorDensityPlot VectorGlyphData VectorGreater VectorGreaterEqual VectorLess VectorLessEqual VectorMarkers VectorPlot VectorPlot3D VectorPoints VectorQ Vectors VectorScale VectorStyle Vee Verbatim Verbose VerboseConvertToPostScriptPacket VerificationTest VerifyConvergence VerifyDerivedKey VerifyDigitalSignature VerifyInterpretation VerifySecurityCertificates VerifySolutions VerifyTestAssumptions Version VersionNumber VertexAdd VertexCapacity VertexColors VertexComponent VertexConnectivity VertexContract VertexCoordinateRules VertexCoordinates VertexCorrelationSimilarity VertexCosineSimilarity VertexCount VertexCoverQ VertexDataCoordinates VertexDegree VertexDelete VertexDiceSimilarity VertexEccentricity VertexInComponent VertexInDegree VertexIndex VertexJaccardSimilarity VertexLabeling VertexLabels VertexLabelStyle VertexList VertexNormals VertexOutComponent VertexOutDegree VertexQ VertexRenderingFunction VertexReplace VertexShape VertexShapeFunction VertexSize VertexStyle VertexTextureCoordinates VertexWeight VertexWeightedGraphQ Vertical VerticalBar VerticalForm VerticalGauge VerticalSeparator VerticalSlider VerticalTilde ViewAngle ViewCenter ViewMatrix ViewPoint ViewPointSelectorSettings ViewPort ViewProjection ViewRange ViewVector ViewVertical VirtualGroupData Visible VisibleCell VoiceStyleData VoigtDistribution VolcanoData Volume VonMisesDistribution VoronoiMeshWaitAll WaitAsynchronousTask WaitNext WaitUntil WakebyDistribution WalleniusHypergeometricDistribution WaringYuleDistribution WarpingCorrespondence WarpingDistance WatershedComponents WatsonUSquareTest WattsStrogatzGraphDistribution WaveletBestBasis WaveletFilterCoefficients WaveletImagePlot WaveletListPlot WaveletMapIndexed WaveletMatrixPlot WaveletPhi WaveletPsi WaveletScale WaveletScalogram WaveletThreshold WeaklyConnectedComponents WeaklyConnectedGraphComponents WeaklyConnectedGraphQ WeakStationarity WeatherData WeatherForecastData WebAudioSearch WebElementObject WeberE WebExecute WebImage WebImageSearch WebSearch WebSessionObject WebSessions WebWindowObject Wedge Wednesday WeibullDistribution WeierstrassE1 WeierstrassE2 WeierstrassE3 WeierstrassEta1 WeierstrassEta2 WeierstrassEta3 WeierstrassHalfPeriods WeierstrassHalfPeriodW1 WeierstrassHalfPeriodW2 WeierstrassHalfPeriodW3 WeierstrassInvariantG2 WeierstrassInvariantG3 WeierstrassInvariants WeierstrassP WeierstrassPPrime WeierstrassSigma WeierstrassZeta WeightedAdjacencyGraph WeightedAdjacencyMatrix WeightedData WeightedGraphQ Weights WelchWindow WheelGraph WhenEvent Which While White WhiteNoiseProcess WhitePoint Whitespace WhitespaceCharacter WhittakerM WhittakerW WienerFilter WienerProcess WignerD WignerSemicircleDistribution WikipediaData WikipediaSearch WilksW WilksWTest WindDirectionData WindingCount WindingPolygon WindowClickSelect WindowElements WindowFloating WindowFrame WindowFrameElements WindowMargins WindowMovable WindowOpacity WindowPersistentStyles WindowSelected WindowSize WindowStatusArea WindowTitle WindowToolbars WindowWidth WindSpeedData WindVectorData WinsorizedMean WinsorizedVariance WishartMatrixDistribution With WolframAlpha WolframAlphaDate WolframAlphaQuantity WolframAlphaResult WolframLanguageData Word WordBoundary WordCharacter WordCloud WordCount WordCounts WordData WordDefinition WordFrequency WordFrequencyData WordList WordOrientation WordSearch WordSelectionFunction WordSeparators WordSpacings WordStem WordTranslation WorkingPrecision WrapAround Write WriteLine WriteString WronskianXMLElement XMLObject XMLTemplate Xnor Xor XYZColorYellow Yesterday YuleDissimilarityZernikeR ZeroSymmetric ZeroTest ZeroWidthTimes Zeta ZetaZero ZIPCodeData ZipfDistribution ZoomCenter ZoomFactor ZTest ZTransform$Aborted $ActivationGroupID $ActivationKey $ActivationUserRegistered $AddOnsDirectory $AllowExternalChannelFunctions $AssertFunction $Assumptions $AsynchronousTask $AudioInputDevices $AudioOutputDevices $BaseDirectory $BatchInput $BatchOutput $BlockchainBase $BoxForms $ByteOrdering $CacheBaseDirectory $Canceled $ChannelBase $CharacterEncoding $CharacterEncodings $CloudBase $CloudConnected $CloudCreditsAvailable $CloudEvaluation $CloudExpressionBase $CloudObjectNameFormat $CloudObjectURLType $CloudRootDirectory $CloudSymbolBase $CloudUserID $CloudUserUUID $CloudVersion $CloudVersionNumber $CloudWolframEngineVersionNumber $CommandLine $CompilationTarget $ConditionHold $ConfiguredKernels $Context $ContextPath $ControlActiveSetting $Cookies $CookieStore $CreationDate $CurrentLink $CurrentTask $CurrentWebSession $DateStringFormat $DefaultAudioInputDevice $DefaultAudioOutputDevice $DefaultFont $DefaultFrontEnd $DefaultImagingDevice $DefaultLocalBase $DefaultMailbox $DefaultNetworkInterface $DefaultPath $Display $DisplayFunction $DistributedContexts $DynamicEvaluation $Echo $EmbedCodeEnvironments $EmbeddableServices $EntityStores $Epilog $EvaluationCloudBase $EvaluationCloudObject $EvaluationEnvironment $ExportFormats $Failed $FinancialDataSource $FontFamilies $FormatType $FrontEnd $FrontEndSession $GeoEntityTypes $GeoLocation $GeoLocationCity $GeoLocationCountry $GeoLocationPrecision $GeoLocationSource $HistoryLength $HomeDirectory $HTMLExportRules $HTTPCookies $HTTPRequest $IgnoreEOF $ImageFormattingWidth $ImagingDevice $ImagingDevices $ImportFormats $IncomingMailSettings $InitialDirectory $Initialization $InitializationContexts $Input $InputFileName $InputStreamMethods $Inspector $InstallationDate $InstallationDirectory $InterfaceEnvironment $InterpreterTypes $IterationLimit $KernelCount $KernelID $Language $LaunchDirectory $LibraryPath $LicenseExpirationDate $LicenseID $LicenseProcesses $LicenseServer $LicenseSubprocesses $LicenseType $Line $Linked $LinkSupported $LoadedFiles $LocalBase $LocalSymbolBase $MachineAddresses $MachineDomain $MachineDomains $MachineEpsilon $MachineID $MachineName $MachinePrecision $MachineType $MaxExtraPrecision $MaxLicenseProcesses $MaxLicenseSubprocesses $MaxMachineNumber $MaxNumber $MaxPiecewiseCases $MaxPrecision $MaxRootDegree $MessageGroups $MessageList $MessagePrePrint $Messages $MinMachineNumber $MinNumber $MinorReleaseNumber $MinPrecision $MobilePhone $ModuleNumber $NetworkConnected $NetworkInterfaces $NetworkLicense $NewMessage $NewSymbol $Notebooks $NoValue $NumberMarks $Off $OperatingSystem $Output $OutputForms $OutputSizeLimit $OutputStreamMethods $Packages $ParentLink $ParentProcessID $PasswordFile $PatchLevelID $Path $PathnameSeparator $PerformanceGoal $Permissions $PermissionsGroupBase $PersistenceBase $PersistencePath $PipeSupported $PlotTheme $Post $Pre $PreferencesDirectory $PreInitialization $PrePrint $PreRead $PrintForms $PrintLiteral $Printout3DPreviewer $ProcessID $ProcessorCount $ProcessorType $ProductInformation $ProgramName $PublisherID $RandomState $RecursionLimit $RegisteredDeviceClasses $RegisteredUserName $ReleaseNumber $RequesterAddress $RequesterWolframID $RequesterWolframUUID $ResourceSystemBase $RootDirectory $ScheduledTask $ScriptCommandLine $ScriptInputString $SecuredAuthenticationKeyTokens $ServiceCreditsAvailable $Services $SessionID $SetParentLink $SharedFunctions $SharedVariables $SoundDisplay $SoundDisplayFunction $SourceLink $SSHAuthentication $SummaryBoxDataSizeLimit $SuppressInputFormHeads $SynchronousEvaluation $SyntaxHandler $System $SystemCharacterEncoding $SystemID $SystemMemory $SystemShell $SystemTimeZone $SystemWordLength $TemplatePath $TemporaryDirectory $TemporaryPrefix $TestFileName $TextStyle $TimedOut $TimeUnit $TimeZone $TimeZoneEntity $TopDirectory $TraceOff $TraceOn $TracePattern $TracePostAction $TracePreAction $UnitSystem $Urgent $UserAddOnsDirectory $UserAgentLanguages $UserAgentMachine $UserAgentName $UserAgentOperatingSystem $UserAgentString $UserAgentVersion $UserBaseDirectory $UserDocumentsDirectory $Username $UserName $UserURLBase $Version $VersionNumber $VoiceStyles $WolframID $WolframUUID",c:[e.C("\\(\\*","\\*\\)",{c:["self"]}),e.QSM,e.CNM]}});hljs.registerLanguage("tcl",function(e){return{aliases:["tk"],k:"after append apply array auto_execok auto_import auto_load auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd chan clock close concat continue dde dict encoding eof error eval exec exit expr fblocked fconfigure fcopy file fileevent filename flush for foreach format gets glob global history http if incr info interp join lappend|10 lassign|10 lindex|10 linsert|10 list llength|10 load lrange|10 lrepeat|10 lreplace|10 lreverse|10 lsearch|10 lset|10 lsort|10 mathfunc mathop memory msgcat namespace open package parray pid pkg::create pkg_mkIndex platform platform::shell proc puts pwd read refchan regexp registry regsub|10 rename return safe scan seek set socket source split string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord tcl_startOfPreviousWord tcl_wordBreakAfter tcl_wordBreakBefore tcltest tclvars tell time tm trace unknown unload unset update uplevel upvar variable vwait while",c:[e.C(";[ \\t]*#","$"),e.C("^[ \\t]*#","$"),{bK:"proc",e:"[\\{]",eE:!0,c:[{cN:"title",b:"[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",e:"[ \\t\\n\\r]",eW:!0,eE:!0}]},{eE:!0,v:[{b:"\\$(\\{)?(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*\\(([a-zA-Z0-9_])*\\)",e:"[^a-zA-Z0-9_\\}\\$]"},{b:"\\$(\\{)?(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",e:"(\\))?[^a-zA-Z0-9_\\}\\$]"}]},{cN:"string",c:[e.BE],v:[e.inherit(e.QSM,{i:null})]},{cN:"number",v:[e.BNM,e.CNM]}]}});hljs.registerLanguage("prolog",function(e){var c={b:/\(/,e:/\)/,relevance:0},b={b:/\[/,e:/\]/},n={cN:"comment",b:/%/,e:/$/,c:[e.PWM]},r={cN:"string",b:/`/,e:/`/,c:[e.BE]},a=[{b:/[a-z][A-Za-z0-9_]*/,relevance:0},{cN:"symbol",v:[{b:/[A-Z][a-zA-Z0-9_]*/},{b:/_[A-Za-z0-9_]*/}],relevance:0},c,{b:/:-/},b,n,e.CBCM,e.QSM,e.ASM,r,{cN:"string",b:/0\'(\\\'|.)/},{cN:"string",b:/0\'\\s/},e.CNM];return c.c=a,{c:(b.c=a).concat([{b:/\.$/}])}});hljs.registerLanguage("makefile",function(e){var i={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%<?\^\+\*]/}]},r={cN:"string",b:/"/,e:/"/,c:[e.BE,i]},a={cN:"variable",b:/\$\([\w-]+\s/,e:/\)/,k:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},c:[i]},n={b:"^"+e.UIR+"\\s*(?=[:+?]?=)"},t={cN:"section",b:/^[^\s]+:/,e:/$/,c:[i]};return{aliases:["mk","mak"],k:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath",l:/[\w-]+/,c:[e.HCM,i,r,a,n,{cN:"meta",b:/^\.PHONY:/,e:/$/,k:{"meta-keyword":".PHONY"},l:/[\.\w]+/},t]}});hljs.registerLanguage("objectivec",function(e){var t=/[a-zA-Z@][a-zA-Z0-9_]*/,i="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:{keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},l:t,i:"</",c:[{cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},e.CLCM,e.CBCM,e.CNM,e.QSM,e.ASM,{cN:"string",v:[{b:'@"',e:'"',i:"\\n",c:[e.BE]}]},{cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,relevance:0},e.inherit(e.QSM,{cN:"meta-string"}),{cN:"meta-string",b:/<.*?>/,e:/$/,i:"\\n"},e.CLCM,e.CBCM]},{cN:"class",b:"("+i.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:i,l:t,c:[e.UTM]},{b:"\\."+e.UIR,relevance:0}]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[/\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("powershell",function(e){var t={keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter"},n={b:"`[\\s\\S]",relevance:0},c={cN:"variable",v:[{b:/\$\B/},{cN:"keyword",b:/\$this/},{b:/\$[\w\d][\w\d_:]*/}]},i={cN:"string",v:[{b:/"/,e:/"/},{b:/@"/,e:/^"@/}],c:[n,c,{cN:"variable",b:/\$[A-z]/,e:/[^A-z]/}]},a={cN:"string",v:[{b:/'/,e:/'/},{b:/@'/,e:/^'@/}]},r=e.inherit(e.C(null,null),{v:[{b:/#/,e:/$/},{b:/<#/,e:/#>/}],c:[{cN:"doctag",v:[{b:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{b:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),o={cN:"built_in",v:[{b:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|New|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Complete|Confirm|Deny|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},l={cN:"class",bK:"class enum",e:/\s*[{]/,eE:!0,relevance:0,c:[e.TM]},s={cN:"function",b:/function\s+/,e:/\s*\{|$/,eE:!0,rB:!0,relevance:0,c:[{b:"function",relevance:0,cN:"keyword"},{cN:"title",b:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{b:/\(/,e:/\)/,cN:"params",relevance:0,c:[c]}]},p={b:/using\s/,e:/$/,rB:!0,c:[i,a,{cN:"keyword",b:/(using|assembly|command|module|namespace|type)/}]},b={v:[{cN:"operator",b:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{cN:"literal",b:/(-)[\w\d]+/,relevance:0}]},d={cN:"function",b:/\[.*\]\s*[\w]+[ ]??\(/,e:/$/,rB:!0,relevance:0,c:[{cN:"keyword",b:"(".concat(t.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},e.inherit(e.TM,{endsParent:!0})]},u=[d,r,n,e.NM,i,a,o,c,{cN:"literal",b:/\$(null|true|false)\b/},{cN:"selector-tag",b:/\@\B/,relevance:0}],m={b:/\[/,e:/\]/,eB:!0,eE:!0,relevance:0,c:[].concat("self",u,{b:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",cN:"built_in",relevance:0},{cN:"type",b:/[\.\w\d]+/,relevance:0})};return d.c.unshift(m),{aliases:["ps","ps1"],l:/-?[A-z\.\-]+/,cI:!0,k:t,c:u.concat(l,s,p,b,m)}});hljs.registerLanguage("qml",function(e){var r="[a-zA-Z_][a-zA-Z0-9\\._]*",t={cN:"attribute",b:"\\bid\\s*:",starts:{cN:"string",e:r,rE:!1}},a={b:r+"\\s*:",rB:!0,c:[{cN:"attribute",b:r,e:"\\s*:",eE:!0,relevance:0}],relevance:0},n={b:r+"\\s*{",e:"{",rB:!0,relevance:0,c:[e.inherit(e.TM,{b:r})]};return{aliases:["qt"],cI:!1,k:{keyword:"in of on if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await import",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Behavior bool color coordinate date double enumeration font geocircle georectangle geoshape int list matrix4x4 parent point quaternion real rect size string url variant vector2d vector3d vector4dPromise"},c:[{cN:"meta",b:/^\s*['"]use (strict|asm)['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],relevance:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/</,e:/>\s*[);\]]/,relevance:0,sL:"xml"}],relevance:0},{cN:"keyword",b:"\\bsignal\\b",starts:{cN:"string",e:"(\\(|:|=|;|,|//|/\\*|$)",rE:!0}},{cN:"keyword",b:"\\bproperty\\b",starts:{cN:"string",e:"(:|=|;|,|//|/\\*|$)",rE:!0}},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:"\\."+e.IR,relevance:0},t,a,n],i:/#/}});hljs.registerLanguage("vbscript-html",function(r){return{sL:"xml",c:[{b:"<%",e:"%>",sL:"vbscript"}]}});hljs.registerLanguage("typescript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",t={keyword:"in if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const class public private protected get set super static implements enum export import declare type namespace abstract as from extends async await",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document any number boolean string void Promise"},n={cN:"meta",b:"@"+r},a={b:"\\(",e:/\)/,k:t,c:["self",e.QSM,e.ASM,e.NM]},c={cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:[e.CLCM,e.CBCM,n,a]},s={cN:"number",v:[{b:"\\b(0[bB][01]+)n?"},{b:"\\b(0[oO][0-7]+)n?"},{b:e.CNR+"n?"}],relevance:0},o={cN:"subst",b:"\\$\\{",e:"\\}",k:t,c:[]},i={b:"html`",e:"",starts:{e:"`",rE:!1,c:[e.BE,o],sL:"xml"}},l={b:"css`",e:"",starts:{e:"`",rE:!1,c:[e.BE,o],sL:"css"}},b={cN:"string",b:"`",e:"`",c:[e.BE,o]};return o.c=[e.ASM,e.QSM,i,l,b,s,e.RM],{aliases:["ts"],k:t,c:[{cN:"meta",b:/^\s*['"]use strict['"]/},e.ASM,e.QSM,i,l,b,e.CLCM,e.CBCM,s,{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+e.IR+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:e.IR},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:["self",e.CLCM,e.CBCM]}]}]}],relevance:0},{cN:"function",bK:"function",e:/[\{;]/,eE:!0,k:t,c:["self",e.inherit(e.TM,{b:r}),c],i:/%/,relevance:0},{bK:"constructor",e:/[\{;]/,eE:!0,c:["self",c]},{b:/module\./,k:{built_in:"module"},relevance:0},{bK:"module",e:/\{/,eE:!0},{bK:"interface",e:/\{/,eE:!0,k:"interface extends"},{b:/\$[(.]/},{b:"\\."+e.IR,relevance:0},n,a]}});hljs.registerLanguage("fortran",function(e){return{cI:!0,aliases:["f90","f95"],k:{literal:".False. .True.",keyword:"kind do while private call intrinsic where elsewhere type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then block endblock public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. goto save else use module select case access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit continue format pause cycle exit c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg synchronous nopass non_overridable pass protected volatile abstract extends import non_intrinsic value deferred generic final enumerator class associate bind enum c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure integer real character complex logical dimension allocatable|10 parameter external implicit|10 none double precision assign intent optional pointer target in out common equivalence data",built_in:"alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_ofacosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr num_images parity popcnt poppar shifta shiftl shiftr this_image"},i:/\/\*/,c:[e.inherit(e.ASM,{cN:"string",relevance:0}),e.inherit(e.QSM,{cN:"string",relevance:0}),{cN:"function",bK:"subroutine function program",i:"[${=\\n]",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)"}]},e.C("!","$",{relevance:0}),{cN:"number",b:"(?=\\b|\\+|\\-|\\.)(?=\\.\\d|\\d)(?:\\d+)?(?:\\.?\\d*)(?:[de][+-]?\\d+)?\\b\\.?",relevance:0}]}});hljs.registerLanguage("gherkin",function(e){return{aliases:["feature"],k:"Feature Background Ability Business Need Scenario Scenarios Scenario Outline Scenario Template Examples Given And Then But When",c:[{cN:"symbol",b:"\\*",relevance:0},{cN:"meta",b:"@[^@\\s]+"},{b:"\\|",e:"\\|\\w*$",c:[{cN:"string",b:"[^|]+"}]},{cN:"variable",b:"<",e:">"},e.HCM,{cN:"string",b:'"""',e:'"""'},e.QSM]}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},i={cN:"meta",b:/<\?(php)?|\?>/},t={cN:"string",c:[e.BE,i],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},a={v:[e.BNM,e.CNM]};return{aliases:["php","php3","php4","php5","php6","php7"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[i]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},i,{cN:"keyword",b:/\$this\b/},c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,t,a]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},t,a]}});hljs.registerLanguage("haskell",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},a={cN:"meta",b:"{-#",e:"#-}"},l={cN:"meta",b:"^#",e:"$"},c={cN:"type",b:"\\b[A-Z][\\w']*",relevance:0},n={b:"\\(",e:"\\)",i:'"',c:[a,l,{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TM,{b:"[_a-z][\\w']*"}),i]};return{aliases:["hs"],k:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",c:[{bK:"module",e:"where",k:"module where",c:[n,i],i:"\\W\\.|;"},{b:"\\bimport\\b",e:"$",k:"import qualified as hiding",c:[n,i],i:"\\W\\.|;"},{cN:"class",b:"^(\\s*)?(class|instance)\\b",e:"where",k:"class family instance where",c:[c,n,i]},{cN:"class",b:"\\b(data|(new)?type)\\b",e:"$",k:"data family type newtype deriving",c:[a,c,n,{b:"{",e:"}",c:n.c},i]},{bK:"default",e:"$",c:[c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"\\bforeign\\b",e:"$",k:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",c:[c,e.QSM,i]},{cN:"meta",b:"#!\\/usr\\/bin\\/env runhaskell",e:"$"},a,l,e.QSM,e.CNM,c,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},i=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",relevance:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]{0,3}(?=\\W)",relevance:0},{b:/\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/}]},{b:"@"+n},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];r.c=i;var s=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",a={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(i)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:i.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[s,a]},{b:/[:\(,=]\s*/,relevance:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[a]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{b:n+":",e:":",rB:!0,rE:!0,relevance:0}])}});hljs.registerLanguage("r",function(e){var r="([a-zA-Z]|\\.[a-zA-Z.])[a-zA-Z0-9._]*";return{c:[e.HCM,{b:r,l:r,k:{keyword:"function if in break next repeat else for return switch while try tryCatch stop warning require library attach detach source setMethod setGeneric setGroupGeneric setClass ...",literal:"NULL NA TRUE FALSE T F Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10"},relevance:0},{cN:"number",b:"0[xX][0-9a-fA-F]+[Li]?\\b",relevance:0},{cN:"number",b:"\\d+(?:[eE][+\\-]?\\d*)?L\\b",relevance:0},{cN:"number",b:"\\d+\\.(?!\\d)(?:i\\b)?",relevance:0},{cN:"number",b:"\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b",relevance:0},{cN:"number",b:"\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b",relevance:0},{b:"`",e:"`",relevance:0},{cN:"string",c:[e.BE],v:[{b:'"',e:'"'},{b:"'",e:"'"}]}]}});hljs.registerLanguage("livescript",function(e){var t={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger case default function var with then unless until loop of by when and or is isnt not it that otherwise from to til fallthrough super case default function var void const let enum export import native list map __hasProp __extends __slice __bind __indexOf",literal:"true false null undefined yes no on off it that void",built_in:"npm require console print module global window document"},s="[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*",n=e.inherit(e.TM,{b:s}),i={cN:"subst",b:/#\{/,e:/}/,k:t},a={cN:"subst",b:/#[A-Za-z$_]/,e:/(?:\-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/,k:t},c=[e.BNM,{cN:"number",b:"(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)",relevance:0,starts:{e:"(\\s*/)?",relevance:0}},{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,i,a]},{b:/"/,e:/"/,c:[e.BE,i,a]},{b:/\\/,e:/(\s|$)/,eE:!0}]},{cN:"regexp",v:[{b:"//",e:"//[gim]*",c:[i,e.HCM]},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W)/}]},{b:"@"+s},{b:"``",e:"``",eB:!0,eE:!0,sL:"javascript"}];i.c=c;var r={cN:"params",b:"\\(",rB:!0,c:[{b:/\(/,e:/\)/,k:t,c:["self"].concat(c)}]};return{aliases:["ls"],k:t,i:/\/\*/,c:c.concat([e.C("\\/\\*","\\*\\/"),e.HCM,{b:"(#=>|=>|\\|>>|-?->|\\!->)"},{cN:"function",c:[n,r],rB:!0,v:[{b:"("+s+"\\s*(?:=|:=)\\s*)?(\\(.*\\))?\\s*\\B\\->\\*?",e:"\\->\\*?"},{b:"("+s+"\\s*(?:=|:=)\\s*)?!?(\\(.*\\))?\\s*\\B[-~]{1,2}>\\*?",e:"[-~]{1,2}>\\*?"},{b:"("+s+"\\s*(?:=|:=)\\s*)?(\\(.*\\))?\\s*\\B!?[-~]{1,2}>\\*?",e:"!?[-~]{1,2}>\\*?"}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[n]},n]},{b:s+":",e:":",rB:!0,rE:!0,relevance:0}])}});hljs.registerLanguage("erb",function(e){return{sL:"xml",c:[e.C("<%#","%>"),{b:"<%[%=-]?",e:"[%-]?%>",sL:"ruby",eB:!0,eE:!0}]}});hljs.registerLanguage("css",function(e){var c={b:/(?:[A-Z\_\.\-]+|--[a-zA-Z0-9_-]+)\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM,e.CSSNM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$",c:[e.ASM,e.QSM]},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(page|font-face)",l:"@[a-z-]+",k:"@page @font-face"},{b:"@",e:"[{;]",i:/:/,rB:!0,c:[{cN:"keyword",b:/@\-?\w[\w]*(\-\w+)*/},{b:/\s/,eW:!0,eE:!0,relevance:0,k:"and or not only",c:[{b:/[a-z-]+:/,cN:"attribute"},e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:"[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,c]}]}});hljs.registerLanguage("delphi",function(e){var r="exports register file shl array record property for mod while set ally label uses raise not stored class safecall var interface or private static exit index inherited to else stdcall override shr asm far resourcestring finalization packed virtual out and protected library do xorwrite goto near function end div overload object unit begin string on inline repeat until destructor write message program with read initialization except default nil if case cdecl in downto threadvar of try pascal const external constructor type public then implementation finally published procedure absolute reintroduce operator as is abstract alias assembler bitpacked break continue cppdecl cvar enumerator experimental platform deprecated unimplemented dynamic export far16 forward generic helper implements interrupt iochecks local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat specialize strict unaligned varargs ",t=[e.CLCM,e.C(/\{/,/\}/,{relevance:0}),e.C(/\(\*/,/\*\)/,{relevance:10})],a={cN:"meta",v:[{b:/\{\$/,e:/\}/},{b:/\(\*\$/,e:/\*\)/}]},c={cN:"string",b:/'/,e:/'/,c:[{b:/''/}]},i={cN:"string",b:/(#\d+)+/},n={b:e.IR+"\\s*=\\s*class\\s*\\(",rB:!0,c:[e.TM]},o={cN:"function",bK:"function constructor destructor procedure",e:/[:;]/,k:"function constructor|10 destructor|10 procedure|10",c:[e.TM,{cN:"params",b:/\(/,e:/\)/,k:r,c:[c,i,a].concat(t)},a].concat(t)};return{aliases:["dpr","dfm","pas","pascal","freepascal","lazarus","lpr","lfm"],cI:!0,k:r,i:/"|\$[G-Zg-z]|\/\*|<\/|\|/,c:[c,i,e.NM,n,o,a].concat(t)}});hljs.registerLanguage("dsconfig",function(e){return{k:"dsconfig",c:[{cN:"keyword",b:"^dsconfig",e:"\\s",eE:!0,relevance:10},{cN:"built_in",b:"(list|create|get|set|delete)-(\\w+)",e:"\\s",eE:!0,i:"!@#$%^&*()",relevance:10},{cN:"built_in",b:"--(\\w+)",e:"\\s",eE:!0},{cN:"string",b:/"/,e:/"/},{cN:"string",b:/'/,e:/'/},{cN:"string",b:"[\\w-?]+:\\w+",e:"\\W",relevance:0},{cN:"string",b:"\\w+-?\\w+",e:"\\W",relevance:0},e.HCM]}}); define("editor_atto/events",["exports","core/event_dispatcher"],(function(_exports,_event_dispatcher){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyButtonHighlightToggled=_exports.eventTypes=void 0; /** * Javascript events for the `editor_atto` plugin. * * @module editor_atto/events * @copyright 2021 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.10.5 */ const eventTypes={attoButtonHighlightToggled:"editor_atto/attoButtonHighlightToggled"};_exports.eventTypes=eventTypes;_exports.notifyButtonHighlightToggled=(attoButton,buttonName,highlight)=>(0,_event_dispatcher.dispatchEvent)(eventTypes.attoButtonHighlightToggled,{buttonName:buttonName,highlight:highlight},attoButton)})); define("editor_tiny/loader",["exports","core/config"],(function(_exports,Config){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)} /** * Tiny Loader for Moodle * * @module editor_tiny/loader * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ let tinyMCEPromise;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getTinyMCE=_exports.baseUrl=void 0,Config=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Config);const baseUrl="".concat(Config.wwwroot,"/lib/editor/tiny/loader.php/").concat(M.cfg.jsrev);_exports.baseUrl=baseUrl;_exports.getTinyMCE=()=>tinyMCEPromise||(tinyMCEPromise=new Promise(((resolve,reject)=>{const head=document.querySelector("head");let script=head.querySelector('script[data-tinymce="tinymce"]');script&&resolve(window.tinyMCE),script=document.createElement("script"),script.dataset.tinymce="tinymce",script.src="".concat(baseUrl,"/tinymce.js"),script.async=!0,script.addEventListener("load",(()=>{resolve(window.tinyMCE)}),!1),script.addEventListener("error",(err=>{reject(err)}),!1),head.append(script)})),tinyMCEPromise)})); define("editor_tiny/options",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.registerPlaceholderSelectors=_exports.register=_exports.getPluginOptionName=_exports.getPlaceholderSelectors=_exports.getNestedMenu=_exports.getMoodleLang=_exports.getInitialPluginConfiguration=_exports.getFilepickers=_exports.getFilePicker=_exports.getDraftItemId=_exports.getCurrentLanguage=_exports.getContextId=void 0;_exports.register=(editor,options)=>{const registerOption=editor.options.register,setOption=editor.options.set;registerOption("moodle:contextid",{processor:"number",default:0}),setOption("moodle:contextid",options.context),registerOption("moodle:filepickers",{processor:"object",default:{}}),setOption("moodle:filepickers",options.filepicker),registerOption("moodle:draftitemid",{processor:"number",default:0}),setOption("moodle:draftitemid",options.draftitemid),registerOption("moodle:currentLanguage",{processor:"string",default:"en"}),setOption("moodle:currentLanguage",options.currentLanguage),registerOption("moodle:language",{processor:"object",default:{}}),setOption("moodle:language",options.language),registerOption("moodle:placeholderSelectors",{processor:"array",default:[]}),setOption("moodle:placeholderSelectors",options.placeholderSelectors),registerOption("moodle:nestedmenu",{processor:"boolean",default:!1}),setOption("moodle:nestedmenu",options.nestedmenu)};_exports.getContextId=editor=>editor.options.get("moodle:contextid");_exports.getDraftItemId=editor=>editor.options.get("moodle:draftitemid");const getFilepickers=editor=>editor.options.get("moodle:filepickers");_exports.getFilepickers=getFilepickers;_exports.getFilePicker=(editor,type)=>getFilepickers(editor)[type];_exports.getMoodleLang=editor=>editor.options.get("moodle:language");_exports.getCurrentLanguage=editor=>editor.options.get("moodle:currentLanguage");_exports.getNestedMenu=editor=>editor.options.get("moodle:nestedmenu");_exports.getInitialPluginConfiguration=options=>{const config={};return Object.entries(options.plugins).forEach((_ref=>{var _pluginConfig$config;let[pluginName,pluginConfig]=_ref;Object.entries(null!==(_pluginConfig$config=pluginConfig.config)&&void 0!==_pluginConfig$config?_pluginConfig$config:{}).forEach((_ref2=>{let[optionName,value]=_ref2;config[getPluginOptionName(pluginName,optionName)]=value}))})),config};const getPluginOptionName=(pluginName,optionName)=>"".concat(pluginName,":").concat(optionName);_exports.getPluginOptionName=getPluginOptionName;const getPlaceholderSelectors=editor=>editor.options.get("moodle:placeholderSelectors");_exports.getPlaceholderSelectors=getPlaceholderSelectors;_exports.registerPlaceholderSelectors=(editor,selectors)=>{if(selectors.length){let existingData=getPlaceholderSelectors(editor);existingData=existingData.concat(selectors),editor.options.set("moodle:placeholderSelectors",existingData)}}})); define("editor_tiny/uploader",["exports","core_form/events","editor_tiny/options"],(function(_exports,_events,_options){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default=(editor,filePickerType,blob,fileName,progress)=>new Promise(((resolve,reject)=>{var _options$savepath;(0,_events.notifyUploadStarted)(editor.targetElm.id);const xhr=new XMLHttpRequest;xhr.upload.addEventListener("progress",(e=>{progress(e.loaded/e.total*100)})),xhr.addEventListener("load",(()=>{if(403===xhr.status)return void reject({message:"HTTP error: ".concat(xhr.status),remove:!0});if(xhr.status<200||xhr.status>=300)return void reject("HTTP Error: ".concat(xhr.status));const response=JSON.parse(xhr.responseText);if(!response)return void reject("Invalid JSON: ".concat(xhr.responseText));let location;(0,_events.notifyUploadCompleted)(editor.targetElm.id),response.url?location=response.url:response.event&&"fileexists"===response.event&&response.newfile&&(location=response.newfile.url),location&&"string"==typeof location?resolve(location):reject("Unable to handle file result: ".concat(xhr.responseText))})),xhr.addEventListener("error",(()=>{reject({message:"Upload failed due to an XHR transport error. Code: ".concat(xhr.status),remove:!0})}));const formData=new FormData,options=(0,_options.getFilePicker)(editor,filePickerType);formData.append("repo_upload_file",blob,fileName),formData.append("itemid",options.itemid),Object.values(options.repositories).some((repository=>"upload"===repository.type&&(formData.append("repo_id",repository.id),!0))),formData.append("env",options.env),formData.append("sesskey",M.cfg.sesskey),formData.append("client_id",options.client_id),formData.append("savepath",null!==(_options$savepath=options.savepath)&&void 0!==_options$savepath?_options$savepath:"/"),formData.append("ctx_id",options.context.id),xhr.open("POST","".concat(M.cfg.wwwroot,"/repository/repository_ajax.php?action=upload"),!0),xhr.send(formData)})),_exports.default})); define("editor_tiny/defaults",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getDefaultToolbar=_exports.getDefaultQuickbarsSelectionToolbar=_exports.getDefaultQuickbarsInsertToolbar=_exports.getDefaultQuickbarsImageToolbar=_exports.getDefaultMenu=_exports.getDefaultConfiguration=void 0; /** * TinyMCE Editor Upstream defaults. * * @module editor_tiny/editor * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const getDefaultMenu=()=>({file:{title:"File",items:"newdocument restoredraft | preview | export print | deleteallconversations"},edit:{title:"Edit",items:"undo redo | cut copy paste pastetext | selectall | searchreplace"},view:{title:"View",items:"code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments"},insert:{title:"Insert",items:"image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime"},format:{title:"Format",items:"bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat"},tools:{title:"Tools",items:"spellchecker spellcheckerlanguage | a11ycheck code wordcount"},table:{title:"Table",items:"inserttable | cell row column | advtablesort | tableprops deletetable"},help:{title:"Help",items:"help"}});_exports.getDefaultMenu=getDefaultMenu;const getDefaultToolbar=()=>[{name:"history",items:["undo","redo"]},{name:"formatting",items:["bold","italic"]},{name:"alignment",items:["alignleft","aligncenter","alignright","alignjustify"]},{name:"indentation",items:["outdent","indent"]},{name:"lists",items:["bullist","numlist"]},{name:"comments",items:["addcomment"]}];_exports.getDefaultToolbar=getDefaultToolbar;const getDefaultQuickbarsSelectionToolbar=()=>"bold italic | quicklink h2 h3 blockquote";_exports.getDefaultQuickbarsSelectionToolbar=getDefaultQuickbarsSelectionToolbar;const getDefaultQuickbarsInsertToolbar=()=>"quickimage quicktable";_exports.getDefaultQuickbarsInsertToolbar=getDefaultQuickbarsInsertToolbar;const getDefaultQuickbarsImageToolbar=()=>"alignleft aligncenter alignright";_exports.getDefaultQuickbarsImageToolbar=getDefaultQuickbarsImageToolbar;_exports.getDefaultConfiguration=()=>({toolbar_mode:"sliding",toolbar:[{name:"history",items:["undo","redo"]},{name:"formatting",items:["bold","italic"]},{name:"alignment",items:["alignleft","aligncenter","alignright","alignjustify"]},{name:"indentation",items:["outdent","indent"]},{name:"lists",items:["bullist","numlist"]},{name:"comments",items:["addcomment"]}],quickbars_selection_toolbar:"bold italic | quicklink h2 h3 blockquote",quickbars_insert_toolbar:"quickimage quicktable",quickbars_image_toolbar:"alignleft aligncenter alignright",menu:{file:{title:"File",items:"newdocument restoredraft | preview | export print | deleteallconversations"},edit:{title:"Edit",items:"undo redo | cut copy paste pastetext | selectall | searchreplace"},view:{title:"View",items:"code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments"},insert:{title:"Insert",items:"image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime"},format:{title:"Format",items:"bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat"},tools:{title:"Tools",items:"spellchecker spellcheckerlanguage | a11ycheck code wordcount"},table:{title:"Table",items:"inserttable | cell row column | advtablesort | tableprops deletetable"},help:{title:"Help",items:"help"}},skin:"oxide"})})); define("editor_tiny/editor",["exports","jquery","core/pending","./defaults","./loader","./options","./utils"],(function(_exports,_jquery,_pending,_defaults,_loader,Options,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setupForTarget=_exports.setupForElementId=_exports.getInstanceForElementId=_exports.getInstanceForElement=_exports.getAllInstances=_exports.configureDefaultEditor=void 0,_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending),Options=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Options);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const instanceMap=new Map;let defaultOptions={};const importPluginList=async pluginList=>{const pluginHandlers=await Promise.all(pluginList.map((pluginPath=>-1===pluginPath.indexOf("/")?Promise.resolve(pluginPath):"function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require([pluginPath],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require(pluginPath)):Promise.resolve(_systemImportTransformerGlobalIdentifier[pluginPath])))),pluginNames=pluginHandlers.map((pluginConfig=>"string"==typeof pluginConfig?pluginConfig:Array.isArray(pluginConfig)?pluginConfig[0]:null)).filter((value=>value));return{pluginNames:pluginNames,pluginConfig:pluginHandlers.map((pluginConfig=>Array.isArray(pluginConfig)?pluginConfig[1]:null)).filter((value=>value))}};_exports.getAllInstances=()=>new Map(instanceMap.entries());_exports.getInstanceForElementId=elementId=>getInstanceForElement(document.getElementById(elementId));const getInstanceForElement=element=>{const instance=instanceMap.get(element);if(!instance||!instance.removed)return instance;instanceMap.remove(element)};_exports.getInstanceForElement=getInstanceForElement;_exports.setupForElementId=_ref=>{let{elementId:elementId,options:options}=_ref;const target=document.getElementById(elementId);return setupForTarget(target,options)};(async()=>{const lang=document.querySelector("html").lang,[tinyMCE,langData]=await Promise.all([(0,_loader.getTinyMCE)(),(language=lang,fetch("".concat(M.cfg.wwwroot,"/lib/editor/tiny/lang.php/").concat(M.cfg.langrev,"/").concat(language)).then((response=>response.json())))]);var language;tinyMCE.addI18n(lang,langData)})();const getPlugins=function(){let{plugins:plugins=null}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return plugins||(defaultOptions.plugins?defaultOptions.plugins:{})},getStandardConfig=(target,tinyMCE,options,plugins)=>{const lang=document.querySelector("html").lang,config=Object.assign({},(0,_defaults.getDefaultConfiguration)(),{base_url:_loader.baseUrl,target:target,min_height:175,height:target.clientHeight||"calc(".concat(target.rows," * ").concat(window.getComputedStyle(target).lineHeight||"22px",")"),language:lang,content_css:[options.css],convert_urls:!1,a11y_advanced_options:!0,extended_valid_elements:"script[*]",xss_sanitization:!1,quickbars_insert_toolbar:"",block_formats:"Paragraph=p; Heading 3=h3; Heading 4=h4; Heading 5=h5; Heading 6=h6;",plugins:[...plugins],skin:"oxide",promotion:!1,branding:options.branding,table_header_type:"sectionCells",entity_encoding:"raw",setup:editor=>{Options.register(editor,options),editor.on("PreInit",(function(){this.contentWindow=this.iframeElement.contentWindow})),editor.on("init",(function(){(0,_utils.removeSubmenuItem)(editor,"align","tiny:justify")})),editor.on("PostRender",(function(){options.nestedmenu&&(editor=>{const container=editor.getContainer(),menuContainer=document.querySelector("body > .tox.tox-tinymce-aux");container.parentNode.appendChild(menuContainer)})(editor)})),editor.on("FullscreenStateChanged",(function(e){(params=>{params.open&&(document.querySelector(".tox-fullscreen").style.overflow="unset");const pageWithDrawers=document.querySelector("#page.drawers");pageWithDrawers&&(pageWithDrawers.style.overflow=params.open?"unset":"")})({open:e.state})})),editor.on("OpenWindow CloseWindow",(function(e){(params=>{if(params.browser.isSafari()&&!params.fsplugin.isFullscreen()){const pageWithDrawers=document.querySelector("#page.drawers");pageWithDrawers&&(pageWithDrawers.style.overflow=params.open?"unset":"")}})({browser:tinyMCE.Env.browser,fsplugin:editor.plugins.fullscreen,open:"openwindow"==e.type})}))}});return config.toolbar=(0,_utils.addToolbarSection)(config.toolbar,"content","formatting",!0),config.toolbar=(0,_utils.addToolbarButton)(config.toolbar,"content","link"),config.toolbar=(0,_utils.addToolbarSection)(config.toolbar,"directionality","alignment",!0),config.toolbar=(0,_utils.addToolbarButtons)(config.toolbar,"directionality",["ltr","rtl"]),config.toolbar=(0,_utils.removeToolbarButton)(config.toolbar,"alignment","alignjustify"),config},getEditorConfiguration=(target,tinyMCE,options,pluginValues)=>{const{pluginNames:pluginNames,pluginConfig:pluginConfig}=pluginValues,instanceConfig=getStandardConfig(target,tinyMCE,options,pluginNames);return instanceConfig.menu.file&&(instanceConfig.menu.file.items=""),instanceConfig.menu.format&&(instanceConfig.menu.format.items=instanceConfig.menu.format.items.replace(/forecolor ?/,"").replace(/backcolor ?/,"").replace(/fontfamily ?/,"").replace(/fontsize ?/,"").replace(/styles ?/,"").replaceAll(/\| *\|/g,"|")),instanceConfig.quickbars_selection_toolbar=instanceConfig.quickbars_selection_toolbar.replace("h2 h3","h3 h4 h5 h6"),pluginConfig.filter((pluginConfig=>"function"==typeof pluginConfig.configure)).forEach((pluginConfig=>{const pluginInstanceOverride=pluginConfig.configure(instanceConfig,options);Object.assign(instanceConfig,pluginInstanceOverride)})),Object.assign(instanceConfig,Options.getInitialPluginConfiguration(options)),instanceConfig},setupForTarget=async function(target){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const instance=getInstanceForElement(target);if(instance)return Promise.resolve(instance);const pendingPromise=new _pending.default("editor_tiny/editor:setupForTarget"),plugins=getPlugins(options),[tinyMCE,pluginValues]=await Promise.all([(0,_loader.getTinyMCE)(),importPluginList(Object.keys(plugins))]);tinyMCE.get().filter((editor=>!editor.getElement().isConnected)).forEach((editor=>{editor.remove()}));const existingEditor=tinyMCE.EditorManager.get(target.id);if(existingEditor){if(existingEditor.getElement()===target)return pendingPromise.resolve(),Promise.resolve(existingEditor);throw pendingPromise.resolve(),new Error("TinyMCE instance already exists for different target with same ID")}const instanceConfig=getEditorConfiguration(target,tinyMCE,options,pluginValues),[editor]=await tinyMCE.init(instanceConfig);return target.dataset.fieldtype="editor",instanceMap.set(target,editor),editor.on("remove",(_ref2=>{let{target:target}=_ref2;instanceMap.delete(target.targetElm),target.targetElm.dataset.fieldtype=null})),target.form&&(0,_jquery.default)(target.form).on("submit",(()=>{editor.save()})),editor.on("blur",(()=>{editor.save()})),pendingPromise.resolve(),editor};_exports.setupForTarget=setupForTarget;_exports.configureDefaultEditor=function(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};defaultOptions=options}})); define("editor_tiny/utils",["exports","core/templates","./options","core/str"],(function(_exports,_templates,_options,_str){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.removeToolbarButtons=_exports.removeToolbarButton=_exports.removeSubmenuItem=_exports.removeMenubarItems=_exports.removeMenubarItem=_exports.getPluginMetadata=_exports.getImagePath=_exports.getDocumentationLink=_exports.getButtonImage=_exports.ensureEditorIsValid=_exports.displayFilepicker=_exports.addToolbarSection=_exports.addToolbarButtons=_exports.addToolbarButton=_exports.addQuickbarsToolbarItem=_exports.addMenubarItem=_exports.addContextmenuItem=void 0;const getImagePath=function(identifier){let component=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"editor_tiny";return Promise.resolve(M.util.image_url(identifier,component))};_exports.getImagePath=getImagePath;_exports.getButtonImage=async function(identifier){let component=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"editor_tiny";return(0,_templates.renderForPromise)("editor_tiny/toolbar_button",{image:await getImagePath(identifier,component)})};_exports.displayFilepicker=(editor,filetype)=>new Promise(((resolve,reject)=>{const configuration=(0,_options.getFilePicker)(editor,filetype);if(configuration){const options={...configuration,formcallback:resolve};M.core_filepicker.show(Y,options)}else reject("Unknown filetype ".concat(filetype))}));_exports.addToolbarButton=(toolbar,section,button)=>{if(!toolbar)return[{name:section,items:[button]}];return JSON.parse(JSON.stringify(toolbar)).map((item=>(item.name===section&&item.items.push(button),item)))};_exports.addToolbarButtons=(toolbar,section,buttons)=>{if(!toolbar)return[{name:section,items:buttons}];return JSON.parse(JSON.stringify(toolbar)).map((item=>(item.name===section&&buttons.forEach((button=>item.items.push(button))),item)))};_exports.addToolbarSection=function(toolbar,name,relativeTo){let append=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const newSection={name:name,items:[]},sectionInserted=toolbar.some(((section,index)=>section.name===relativeTo&&(append?toolbar.splice(index+1,0,newSection):toolbar.splice(index,0,newSection),!0)));return sectionInserted||(append?toolbar.push(newSection):toolbar.unshift(newSection)),toolbar};_exports.addMenubarItem=(menubar,section,menuitem)=>{if(!menubar){({})[section]={title:section,items:menuitem}}const mutatedMenubar=JSON.parse(JSON.stringify(menubar));return Array.from(Object.entries(mutatedMenubar)).forEach((_ref=>{let[name,menu]=_ref;name===section&&(menu.items="".concat(menu.items," ").concat(menuitem))})),mutatedMenubar};_exports.addContextmenuItem=function(contextmenu){const contextmenuItems=(null!=contextmenu?contextmenu:"").split(" ");for(var _len=arguments.length,menuitems=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)menuitems[_key-1]=arguments[_key];return contextmenuItems.concat(menuitems).filter((item=>""!==item)).join(" ")};_exports.addQuickbarsToolbarItem=function(toolbar){return toolbar};const getDocumentationLink=pluginName=>"https://docs.moodle.org/en/editor_tiny/".concat(pluginName);_exports.getDocumentationLink=getDocumentationLink;_exports.getPluginMetadata=async function(component,pluginName){let url=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const name=await(0,_str.get_string)("helplinktext",component);return{getMetadata:()=>({name:name,url:null!=url?url:getDocumentationLink(pluginName)})}};_exports.ensureEditorIsValid=editor=>editor.getElement().isConnected?editor:null;_exports.removeToolbarButton=(toolbar,section,button)=>{if(!toolbar)return[{name:section,items:[button]}];return JSON.parse(JSON.stringify(toolbar)).map((item=>(item.name===section&&item.items.splice(item.items.indexOf(button),1),item)))};_exports.removeToolbarButtons=(toolbar,section,buttons)=>{if(!toolbar)return[{name:section,items:buttons}];return JSON.parse(JSON.stringify(toolbar)).map((item=>(item.name===section&&buttons.forEach((button=>item.items.splice(item.items.indexOf(button),1))),item)))};_exports.removeSubmenuItem=async(editor,section,submenuitem)=>{const menuItems=editor.ui.registry.getAll().menuItems[section],submenuitemtitle=await(0,_str.get_string)(submenuitem,"editor_tiny");menuItems&&editor.ui.registry.addNestedMenuItem(section,{text:menuItems.text,getSubmenuItems:()=>{let newSubmenu=[];return menuItems.getSubmenuItems().forEach((item=>{item.text.trim()!=submenuitemtitle&&newSubmenu.push(item)})),newSubmenu}})};_exports.removeMenubarItem=(menubar,section,menuitem)=>(menubar[section].items=menubar[section].items.replace(menuitem,""),menubar);_exports.removeMenubarItems=(menubar,section,menuitems)=>{const regexPattern=new RegExp(menuitems.join("|"),"ig");return menubar[section].items=menubar[section].items.replace(regexPattern,""),menubar}})); /** * Module to enable inline editing of a comptency grade. * * @module report_competency/grading_popup * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("report_competency/grading_popup",["jquery","core/notification","core/str","core/ajax","core/log","core/templates","tool_lp/dialogue"],(function($,notification,str,ajax,log,templates,Dialogue){var GradingPopup=function(regionSelector,userCompetencySelector){this._regionSelector=regionSelector,this._userCompetencySelector=userCompetencySelector,$(this._regionSelector).on("click",this._userCompetencySelector,this._handleClick.bind(this))};return GradingPopup.prototype._handleClick=function(e){var cell=$(e.target).closest(this._userCompetencySelector),competencyId=$(cell).data("competencyid"),courseId=$(cell).data("courseid"),userId=$(cell).data("userid");log.debug("Clicked on cell: competencyId="+competencyId+", courseId="+courseId+", userId="+userId);var requests=ajax.call([{methodname:"tool_lp_data_for_user_competency_summary_in_course",args:{userid:userId,competencyid:competencyId,courseid:courseId}},{methodname:"core_competency_user_competency_viewed_in_course",args:{userid:userId,competencyid:competencyId,courseid:courseId}}]);$.when(requests[0],requests[1]).then(this._contextLoaded.bind(this)).catch(notification.exception)},GradingPopup.prototype._contextLoaded=function(context){return context.displayuser=!0,M.util.js_pending("report_competency/grading_popup:_contextLoaded"),$.when(str.get_string("usercompetencysummary","report_competency"),templates.render("tool_lp/user_competency_summary_in_course",context)).then(function(title,templateData){return new Dialogue(title,templateData[0],(function(){templates.runTemplateJS(templateData[1]),M.util.js_complete("report_competency/grading_popup:_contextLoaded")}),this._refresh.bind(this),!0)}.bind(this))},GradingPopup.prototype._refresh=function(){var region=$(this._regionSelector),courseId=region.data("courseid"),moduleId=region.data("moduleid"),userId=region.data("userid");return""===moduleId&&(moduleId=0),ajax.call([{methodname:"report_competency_data_for_report",args:{courseid:courseId,userid:userId,moduleid:moduleId},done:this._pageContextLoaded.bind(this),fail:notification.exception}])},GradingPopup.prototype._pageContextLoaded=function(context){templates.render("report_competency/report",context).then(function(html,js){templates.replaceNode(this._regionSelector,html,js)}.bind(this)).catch(notification.exception)},GradingPopup.prototype._regionSelector=null,GradingPopup.prototype._userCompetencySelector=null,GradingPopup})); /** * Module to navigation between users in a course. * * @module report_competency/user_course_navigation * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("report_competency/user_course_navigation",["jquery"],(function($){var UserCourseNavigation=function(userSelector,moduleSelector,baseUrl,userId,courseId,moduleId){this._baseUrl=baseUrl,this._userId=userId+"",this._courseId=courseId,this._moduleId=moduleId,$(userSelector).on("change",this._userChanged.bind(this)),$(moduleSelector).on("change",this._moduleChanged.bind(this))};return UserCourseNavigation.prototype._userChanged=function(e){M.util.js_pending("report_competency/user_course_navigation:_userChanged");var queryStr="?user="+$(e.target).val()+"&id="+this._courseId+"&mod="+this._moduleId;document.location=this._baseUrl+queryStr},UserCourseNavigation.prototype._moduleChanged=function(e){M.util.js_pending("report_competency/user_course_navigation:_moduleChanged");var queryStr="?mod="+$(e.target).val()+"&id="+this._courseId+"&user="+this._userId;document.location=this._baseUrl+queryStr},UserCourseNavigation.prototype._userId=null,UserCourseNavigation.prototype._moduleId=null,UserCourseNavigation.prototype._courseId=null,UserCourseNavigation.prototype._baseUrl=null,UserCourseNavigation})); /* * JavaScript to expand/collapse sections. * * @package report_customsql * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("report_customsql/reportcategories",["jquery"],(function($){var t={init:function(){$("body").on("click",".csql_category h2 .categoryname, .csql_category h2 .reportcounts",t.expandCollapse),$(".csql_expandcollapseall").on("click",t.expandCollapseAll),t.updateExpandCollapseAll()},expandCollapse:function(e){var catwrapper=$(e.target).closest(".csql_category");catwrapper.length&&(catwrapper.hasClass("csql_categoryhidden")?catwrapper.removeClass("csql_categoryhidden").addClass("csql_categoryshown"):catwrapper.removeClass("csql_categoryshown").addClass("csql_categoryhidden"),e.preventDefault(),t.updateExpandCollapseAll())},expandCollapseAll:function(e){0===$(".csql_categoryshown").length?($(".csql_category").removeClass("csql_categoryhidden"),$(".csql_category").addClass("csql_categoryshown")):($(".csql_category").removeClass("csql_categoryshown"),$(".csql_category").addClass("csql_categoryhidden")),e.preventDefault(),t.updateExpandCollapseAll()},updateExpandCollapseAll:function(){var link=$(".csql_expandcollapseall");0===$(".csql_categoryshown").length?link.text(link.data("expandalltext")):link.text(link.data("collapsealltext"))}};return t})); define("report_customsql/userselector",["exports","core/ajax","core/templates"],(function(_exports,_ajax,_templates){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * JavaScript module to work with the auto-complete of users. * * @module report_customsql/userselector * @copyright 2020 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.processResults=function(selector,results){return results.map((function(user){return{value:user.id,label:user._label}}))},_exports.transport=function(selector,query,success,failure){_ajax.default.call([{methodname:"report_customsql_get_users",args:{query:query,capability:document.getElementById("id_capability").value}}])[0].then((function(results){return Promise.all(results.map((function(user){return _templates.default.render("report_customsql/form-user-selector-suggestion",user).then((function(html){return user._label=html,user}))})))})).then(success).catch(failure)},_ajax=_interopRequireDefault(_ajax),_templates=_interopRequireDefault(_templates)})); /** * Module to manage report insights actions that are executed using AJAX. * * @copyright 2017 David Monllao {@link http://www.davidmonllao.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("report_insights/actions",["jquery","core/str","core/ajax","core/notification","core/url","core/modal_factory","core/modal_events"],(function($,Str,Ajax,Notification,Url,ModalFactory,ModalEvents){return{initBulk:function(rootNode){$(rootNode+" [data-bulk-actionname]").on("click",(function(e){e.preventDefault();var action=$(e.currentTarget),actionName=action.data("bulk-actionname"),actionVisibleName=action.text().trim(),predictionIds=[],predictionContainers=[];if($('.insights-list input[data-togglegroup^="insight-bulk-action-"][data-toggle="slave"]:checked').each((function(){var container=$(this).closest("tr[data-prediction-id]");predictionContainers.push(container),predictionIds.push(container.data("prediction-id"))})),0===predictionIds.length)return this;var strings=[];return Str.get_strings([{key:"confirmbulkaction",component:"report_insights",param:{action:actionVisibleName,nitems:predictionIds.length}},{key:"confirm",component:"moodle"}]).then((function(strs){return strings=strs,ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:actionVisibleName,body:strings[0]})})).then((function(modal){return modal.setSaveButtonText(strings[1]),modal.show(),modal.getRoot().on(ModalEvents.save,(function(){return function(predictionIds,predictionContainers,actionName){return Ajax.call([{methodname:"report_insights_action_executed",args:{predictionids:predictionIds,actionname:actionName}}])[0].then((function(){var tableNode=!1;if(predictionContainers.forEach((function(el){!1===tableNode&&(tableNode=el.closest("table")),el.remove()})),0===tableNode.find("tbody > tr").length){let params={contextid:tableNode.closest("div.insight-container").data("context-id"),modelid:tableNode.closest("div.insight-container").data("model-id")};window.location.assign(Url.relativeUrl("report/insights/insights.php",params,!1))}})).catch(Notification.exception)}(predictionIds,predictionContainers,actionName)})),modal})).catch(Notification.exception),this}))}}})); /** * Message users. * * @module report_insights/message_users * @copyright 2019 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("report_insights/message_users",["jquery","core/str","core/log","core/modal_factory","core/modal_events","core/templates","core/notification","core/ajax"],(function($,Str,Log,ModalFactory,ModalEvents,Templates,Notification,Ajax){var SELECTORS_BULKACTIONSELECT="#formactionid",MessageUsers=function(rootNode,actionName){this.actionName=actionName,this.attachEventListeners(rootNode)};return MessageUsers.prototype.actionName=null,MessageUsers.prototype.modal=null,MessageUsers.prototype.attachEventListeners=function(rootNode){$(rootNode+" button[data-bulk-sendmessage]").on("click",function(e){e.preventDefault();var cTarget=$(e.currentTarget),users={},predictionToUserMapping=cTarget.data("prediction-to-user-id");return $('.insights-list input[data-togglegroup^="insight-bulk-action"][data-toggle="slave"]:checked').each((function(index,value){var predictionId=$(value).closest("tr[data-prediction-id]").data("prediction-id");if(void 0!==predictionToUserMapping[predictionId]){var userId=predictionToUserMapping[predictionId];users[predictionId]=userId}else Log.error("Unknown user for prediction "+predictionId)})),0===Object.keys(users).length||this.showSendMessage(users),this}.bind(this))},MessageUsers.prototype.showSendMessage=function(users){var userIds=new Set(Object.values(users));if(0==userIds.length)return $.Deferred().resolve().promise();var titlePromise=null;return titlePromise=1==userIds.size?Str.get_string("sendbulkmessagesingle","core_message"):Str.get_string("sendbulkmessage","core_message",userIds.size),$.when(ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,body:Templates.render("core_user/send_bulk_message",{})}),titlePromise).then(function(modal,title){return this.modal=modal,this.modal.setTitle(title),this.modal.setSaveButtonText(title),this.modal.getRoot().on(ModalEvents.hidden,function(){$(SELECTORS_BULKACTIONSELECT).focus(),this.modal.getRoot().remove()}.bind(this)),this.modal.getRoot().on(ModalEvents.save,this.submitSendMessage.bind(this,users)),this.modal.show(),this.modal}.bind(this))},MessageUsers.prototype.submitSendMessage=function(users){var messageText=this.modal.getRoot().find("form textarea").val(),messages=[];new Set(Object.values(users)).forEach((function(userId){messages.push({touserid:userId,text:messageText})}));var actionName=this.actionName,message=null;return Ajax.call([{methodname:"core_message_send_instant_messages",args:{messages:messages}}])[0].then((function(messageIds){return 1==messageIds.length?Str.get_string("sendbulkmessagesentsingle","core_message"):Str.get_string("sendbulkmessagesent","core_message",messageIds.length)})).then((function(msg){return message=msg,Ajax.call([{methodname:"report_insights_action_executed",args:{actionname:actionName,predictionids:Object.keys(users)}}])[0]})).then((function(){return Notification.addNotification({message:message,type:"success"}),!0})).catch(Notification.exception)},{init:function(rootNode,actionName){return new MessageUsers(rootNode,actionName)}}})); define("report_participation/participants",["exports","jquery","core/custom_interaction_events","core/modal_events","core/notification","core_user/local/participants/bulkactions"],(function(_exports,_jquery,_custom_interaction_events,_modal_events,_notification,_bulkactions){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Some UI stuff for participants page. * This is also used by the report/participants/index.php because it has the same functionality. * * @module core_user/participants * @copyright 2017 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_modal_events=_interopRequireDefault(_modal_events),_notification=_interopRequireDefault(_notification);const Selectors_bulkActionSelect="#formactionid",Selectors_bulkUserSelectedCheckBoxes="input[data-togglegroup^='participants-table'][data-toggle='slave']:checked",Selectors_participantsForm="#participantsform";_exports.init=()=>{const root=document.querySelector(Selectors_participantsForm),resetBulkAction=bulkActionSelect=>{bulkActionSelect.value=""};_custom_interaction_events.default.define(Selectors_bulkActionSelect,[_custom_interaction_events.default.events.accessibleChange]),(0,_jquery.default)(Selectors_bulkActionSelect).on(_custom_interaction_events.default.events.accessibleChange,(e=>{const action=e.target.value,checkboxes=root.querySelectorAll(Selectors_bulkUserSelectedCheckBoxes);if(-1!==action.indexOf("#")){e.preventDefault();const ids=[];checkboxes.forEach((checkbox=>{ids.push(checkbox.getAttribute("name").replace("user",""))})),"#messageselect"===action&&(0,_bulkactions.showSendMessage)(ids).then((modal=>(modal.getRoot().on(_modal_events.default.hidden,(()=>{const bulkActionSelector=root.querySelector(Selectors_bulkActionSelect);resetBulkAction(bulkActionSelector),bulkActionSelector.focus()})),modal))).catch(_notification.default.exception)}else""!==action&&checkboxes.length&&e.target.form().submit();resetBulkAction(e.target)}))}})); /** * AMD module to handle overriding activity completion status. * * @module report_progress/completion_override * @copyright 2016 onwards Eiz Eddin Al Katrib <eiz@barasoft.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 3.1 */ define("report_progress/completion_override",["jquery","core/ajax","core/str","core/modal_factory","core/modal_events","core/notification","core/custom_interaction_events","core/templates","core/pending"],(function($,Ajax,Str,ModalFactory,ModalEvents,Notification,CustomEvents,Templates,Pending){var userFullName,triggerElement,userConfirm=function(e,data){data.originalEvent.preventDefault(),data.originalEvent.stopPropagation(),e.preventDefault(),e.stopPropagation();var elemData=(triggerElement=$(e.currentTarget)).data("changecompl").split("-"),override={userid:elemData[0],cmid:elemData[1],newstate:elemData[2]},newStateStr=1==override.newstate?"completion-y":"completion-n";Str.get_strings([{key:newStateStr,component:"completion"}]).then((function(strings){return Str.get_strings([{key:"confirm",component:"moodle"},{key:"areyousureoverridecompletion",component:"completion",param:strings[0]}])})).then((function(strings){return ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:strings[0],body:strings[1]})})).then((function(modal){modal.getRoot().on(ModalEvents.save,(function(){!function(override){const pendingPromise=new Pending("report_progress/compeletion_override/setOverride");Templates.render("core/loading",{}).then((function(html){return triggerElement.append(html),Ajax.call([{methodname:"core_completion_override_activity_completion_status",args:override}])[0]})).then((function(results){var completionState=results.state>0?1:0,tooltipKey=completionState?"completion-y-override":"completion-n-override";Str.get_string(tooltipKey,"completion",userFullName).then((function(stateString){var params={state:stateString,date:"",user:triggerElement.attr("data-userfullname"),activity:triggerElement.attr("data-activityname")};return Str.get_string("progress-title","completion",params)})).then((function(titleString){var tracking,completionTracking=triggerElement.attr("data-completiontracking");return Templates.renderPix((tracking=completionTracking,completionState>0?"i/completion-"+tracking+"-y-override":"i/completion-"+tracking+"-n-override"),"core",titleString)})).then((function(html){var oppositeState=completionState>0?0:1;triggerElement.find(".loading-icon").remove(),triggerElement.data("changecompl",override.userid+"-"+override.cmid+"-"+oppositeState),triggerElement.attr("data-changecompl",override.userid+"-"+override.cmid+"-"+oppositeState),triggerElement.children("img").replaceWith(html)})).catch(Notification.exception)})).then((()=>{pendingPromise.resolve()})).catch(Notification.exception)}(override)})),modal.getRoot().on(ModalEvents.hidden,(function(){triggerElement.focus(),modal.destroy()})),modal.show()})).catch(Notification.exception)};return{init:function(fullName){userFullName=fullName,$("#completion-progress a.changecompl").each((function(index,element){CustomEvents.define(element,[CustomEvents.events.activate])})),$("#completion-progress").on(CustomEvents.events.activate,"a.changecompl",(function(e,data){userConfirm(e,data)}))}}})); define("gradereport_grader/stickycolspan",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Javascript module for fixing the position of sticky headers with multiple colspans * * @module gradereport_grader/stickycolspan * @copyright 2022 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS_GRADEPARENT=".gradeparent",SELECTORS_STUDENTHEADER="#studentheader",SELECTORS_TABLEHEADER="th.header",SELECTORS_BEHAT="body.behat-site";_exports.init=()=>{if(document.querySelector(SELECTORS_BEHAT))return;const grader=document.querySelector(SELECTORS_GRADEPARENT),studentHeader=grader.querySelector(SELECTORS_STUDENTHEADER),leftOffset=getComputedStyle(studentHeader).getPropertyValue("left"),rightOffset=getComputedStyle(studentHeader).getPropertyValue("right");grader.querySelectorAll(SELECTORS_TABLEHEADER).forEach((tableHeader=>{if(tableHeader.colSpan>1){const addOffset=tableHeader.offsetWidth-studentHeader.offsetWidth;window.right_to_left()?tableHeader.style.right="calc("+rightOffset+" - "+addOffset+"px )":tableHeader.style.left="calc("+leftOffset+" - "+addOffset+"px )"}}))}})); define("gradereport_singleview/bulkactions",["exports","core/pending","core/custom_interaction_events","core/modal_factory","core/templates","core/modal_events","core/str","core/notification","gradereport_singleview/selectors"],(function(_exports,_pending,_custom_interaction_events,_modal_factory,_templates,_modal_events,Str,_notification,_selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for bulk actions. * * @module gradereport_singleview/bulkactions * @copyright 2022 Ilya Tregubov <ilya@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=_interopRequireDefault(_pending),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_modal_factory=_interopRequireDefault(_modal_factory),_templates=_interopRequireDefault(_templates),_modal_events=_interopRequireDefault(_modal_events),Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_notification=_interopRequireDefault(_notification),_selectors=_interopRequireDefault(_selectors);_exports.init=()=>{const pendingPromise=new _pending.default;registerListenerEvents(),pendingPromise.resolve()};const registerListenerEvents=()=>{const events=["click",_custom_interaction_events.default.events.activate,_custom_interaction_events.default.events.keyboardActivate];_custom_interaction_events.default.define(document,events),events.forEach((event=>{document.addEventListener(event,(async e=>{const trigger=e.target.closest(_selectors.default.actions.bulkaction);if(trigger)if("overrideallgrades"===trigger.dataset.action||"overridenonegrades"===trigger.dataset.action){const override=document.querySelectorAll(_selectors.default.elements.override);"overridenonegrades"===trigger.dataset.action?Str.get_strings([{key:"removeoverride",component:"gradereport_singleview"},{key:"overridenoneconfirm",component:"gradereport_singleview"},{key:"removeoverridesave",component:"gradereport_singleview"},{key:"cancel",component:"moodle"}]).done((strings=>{_notification.default.confirm(strings[0],strings[1],strings[2],strings[3],(()=>{override.forEach((el=>{el.checked&&el.click()}))}))})).fail(_notification.default.exception):override.forEach((el=>{el.checked||el.click()}))}else if("excludeallgrades"===trigger.dataset.action||"excludenonegrades"===trigger.dataset.action){const exclude=document.querySelectorAll(_selectors.default.elements.exclude),checked="excludeallgrades"===trigger.dataset.action;exclude.forEach((el=>{el.checked=checked}))}else"bulklegend"===trigger.dataset.action&&Str.get_strings([{key:"bulklegend",component:"gradereport_singleview"},{key:"save",component:"moodle"}]).done((strings=>{_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,body:_templates.default.render("gradereport_singleview/bulkinsert",{id:"bulkinsertmodal",name:"bulkinsertmodal"}),title:strings[0]}).then((modal=>(modal.setSaveButtonText(strings[1]),modal.getFooter().find(_selectors.default.elements.modalsave).attr("disabled",!0),modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.getRoot().remove()})),modal.getRoot().on("change",_selectors.default.elements.warningcheckbox,(e=>{if(e.preventDefault(),e.target.checked){modal.getRoot().find(_selectors.default.elements.modalformdata).removeClass("dimmed_text"),modal.getRoot().find(_selectors.default.elements.modalradio).removeAttr("disabled"),modal.getRoot().find(_selectors.default.elements.modalinput).removeAttr("disabled");modal.getRoot().find(_selectors.default.elements.modalradiochecked).val()&&modal.getFooter().find(_selectors.default.elements.modalsave).removeAttr("disabled")}else modal.getRoot().find(_selectors.default.elements.modalformdata).addClass("dimmed_text"),modal.getRoot().find(_selectors.default.elements.modalradio).attr("disabled",!0),modal.getRoot().find(_selectors.default.elements.modalinput).attr("disabled",!0),modal.getFooter().find(_selectors.default.elements.modalsave).attr("disabled",!0)})),modal.getRoot().on("change",_selectors.default.elements.modalradio,(e=>{e.preventDefault(),modal.getFooter().find(_selectors.default.elements.modalsave).removeAttr("disabled")})),modal.getRoot().on(_modal_events.default.save,(()=>{document.querySelector(_selectors.default.elements.enablebulkinsert).checked=!0;const formRadioData=modal.getRoot().find(_selectors.default.elements.modalradiochecked).val();document.querySelector(_selectors.default.elements.formradio).value=formRadioData;const formData=modal.getRoot().find(_selectors.default.elements.modalgrade).val();document.querySelector(_selectors.default.elements.formgrade).value=formData,document.querySelector(_selectors.default.elements.formsave).click()})),modal.show(),modal))).fail(_notification.default.exception)})).fail(_notification.default.exception)}))}))}})); define("gradereport_singleview/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var name,value,_default={actions:{bulkaction:(name="role",value="bulkaction","[data-".concat(name,'="').concat(value,'"]'))},elements:{override:"input[type=checkbox][name^=override]",exclude:"input[type=checkbox][name^=exclude]",modalsave:'[data-action="save"]',warningcheckbox:'input[type="checkbox"]',modalformdata:".formdata",modalradio:'input[type="radio"]',modalinput:'input[type="text"]',modalradiochecked:'input[type="radio"]:checked',enablebulkinsert:'input[type="checkbox"][name^=bulk]',formradio:"select[name^=bulk]",modalgrade:".form-control",formgrade:'input[type="text"][name^=bulk]',formsave:'input[type="submit"]'}};return _exports.default=_default,_exports.default})); define("gradereport_singleview/grade",["exports","core/pending","core/templates","core_grades/searchwidget/repository","core_grades/searchwidget/basewidget","jquery","core_grades/searchwidget/selectors"],(function(_exports,_pending,Templates,Repository,WidgetBase,_jquery,Selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A small modal to search grade items within the gradebook. * * @module gradereport_singleview * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=_interopRequireDefault(_pending),Templates=_interopRequireWildcard(Templates),Repository=_interopRequireWildcard(Repository),WidgetBase=_interopRequireWildcard(WidgetBase),_jquery=_interopRequireDefault(_jquery),Selectors=_interopRequireWildcard(Selectors);_exports.init=()=>{const pendingPromise=new _pending.default;registerListenerEvents(),pendingPromise.resolve()};const registerListenerEvents=()=>{let{bodyPromiseResolver:bodyPromiseResolver,bodyPromise:bodyPromise}=WidgetBase.promisesAndResolvers();const dropdownMenuContainer=document.querySelector(Selectors.elements.getSearchWidgetDropdownSelector("grade"));(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("grade")).on("show.bs.dropdown",(async e=>{const courseID=e.relatedTarget.dataset.courseid;await WidgetBase.showLoader(dropdownMenuContainer);const data=await Repository.gradeitemFetch(courseID).catch((async e=>{const errorTemplateData={errormessage:e.message};bodyPromiseResolver(await Templates.render("core_grades/searchwidget/error",errorTemplateData))}));data!==[]&&(await WidgetBase.init(dropdownMenuContainer,bodyPromise,data.gradeitems,searchGradeitems()),bodyPromiseResolver(Templates.render("gradereport_singleview/gradesearch_body",[])))})),(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("grade")).on("hide.bs.dropdown",(()=>{dropdownMenuContainer.innerHTML=""}))},searchGradeitems=()=>()=>(modules,searchTerm)=>{if(""===searchTerm)return modules;searchTerm=searchTerm.toLowerCase();const searchResults=[];return modules.forEach((module=>{module.name.toLowerCase().includes(searchTerm)&&searchResults.push(module)})),searchResults}})); define("gradereport_singleview/user",["exports","core/pending","core/templates","core_grades/searchwidget/repository","core_grades/searchwidget/basewidget","core/url","jquery","core_grades/searchwidget/selectors"],(function(_exports,_pending,Templates,Repository,WidgetBase,_url,_jquery,Selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A small modal to search users within the gradebook. * * @module gradereport_singleview/user * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=_interopRequireDefault(_pending),Templates=_interopRequireWildcard(Templates),Repository=_interopRequireWildcard(Repository),WidgetBase=_interopRequireWildcard(WidgetBase),_url=_interopRequireDefault(_url),_jquery=_interopRequireDefault(_jquery),Selectors=_interopRequireWildcard(Selectors);_exports.init=()=>{const pendingPromise=new _pending.default;registerListenerEvents(),pendingPromise.resolve()};const registerListenerEvents=()=>{let{bodyPromiseResolver:bodyPromiseResolver,bodyPromise:bodyPromise}=WidgetBase.promisesAndResolvers();const dropdownMenuContainer=document.querySelector(Selectors.elements.getSearchWidgetDropdownSelector("user"));(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("user")).on("show.bs.dropdown",(async e=>{const courseID=e.relatedTarget.dataset.courseid,groupId=e.relatedTarget.dataset.groupid,actionBaseUrl=_url.default.relativeUrl("/grade/report/singleview/index.php",{item:"user"},!1);await WidgetBase.showLoader(dropdownMenuContainer);const data=await Repository.userFetch(courseID,actionBaseUrl,groupId).catch((async e=>{const errorTemplateData={errormessage:e.message};bodyPromiseResolver(await Templates.render("core_grades/searchwidget/error",errorTemplateData))}));data!==[]&&(await WidgetBase.init(dropdownMenuContainer,bodyPromise,data.users,searchUsers()),bodyPromiseResolver(Templates.render("core_grades/searchwidget/user/usersearch_body",[])))})),(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("user")).on("hide.bs.dropdown",(()=>{dropdownMenuContainer.innerHTML=""}))},searchUsers=()=>()=>(users,searchTerm)=>{if(""===searchTerm)return users;searchTerm=searchTerm.toLowerCase();const searchResults=[];return users.forEach((user=>{user.fullname.toLowerCase().includes(searchTerm)&&searchResults.push(user)})),searchResults}})); define("gradereport_user/gradecategorytoggle",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0; /** * Javascript module for toggling the visibility of the grade categories in the user report. * * @module gradereport_user/gradecategorytoggle * @copyright 2022 Mihail Geshoski <mihail@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const SELECTORS_CATEGORY_TOGGLE=".toggle-category",SELECTORS_USER_REPORT_TABLE=".user-grade",toggleCategory=toggleElement=>{const target=toggleElement.dataset.target,categoryId=toggleElement.dataset.categoryid,isCollapsing="true"===toggleElement.getAttribute("aria-expanded"),targetRows=toggleElement.closest(SELECTORS_USER_REPORT_TABLE).querySelectorAll(target);isCollapsing?(toggleElement.setAttribute("aria-expanded","false"),toggleElement.dataset.target="[data-hidden-by='".concat(categoryId,"']")):(toggleElement.setAttribute("aria-expanded","true"),toggleElement.dataset.target=".cat_".concat(categoryId,"[data-hidden='false']")),targetRows.forEach((row=>{isCollapsing?(row.dataset.hidden="true",row.dataset.hiddenBy=categoryId):(row.dataset.hidden="false",row.dataset.hiddenBy="")})),updateParentCategoryRowspans(toggleElement,targetRows.length)},updateParentCategoryRowspans=(toggleElement,num)=>{const userReport=toggleElement.closest(SELECTORS_USER_REPORT_TABLE);toggleElement.closest("tr").classList.forEach((className=>{const parentCategoryToggleElement=userReport.querySelector('[data-target=".'.concat(className,"[data-hidden='false']\""));if(parentCategoryToggleElement){const categoryRowSpanElement=parentCategoryToggleElement.closest("tr").nextElementSibling.querySelector("[rowspan]");"true"===toggleElement.getAttribute("aria-expanded")?categoryRowSpanElement.rowSpan=categoryRowSpanElement.rowSpan+num:categoryRowSpanElement.rowSpan=categoryRowSpanElement.rowSpan-num}}))};_exports.init=userReportId=>{(userReportId=>{document.querySelector("#"+userReportId).querySelector(SELECTORS_USER_REPORT_TABLE).addEventListener("click",(e=>{const toggle=e.target.closest(SELECTORS_CATEGORY_TOGGLE);toggle&&toggleCategory(toggle)}))})(userReportId)}})); define("gradereport_user/user",["exports","core/pending","core/templates","core_grades/searchwidget/repository","core_grades/searchwidget/basewidget","core/str","core/url","jquery","core_grades/searchwidget/selectors"],(function(_exports,_pending,Templates,Repository,WidgetBase,_str,_url,_jquery,Selectors){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * A widget to search users within the gradebook. * * @module gradereport_user/user * @copyright 2022 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=_interopRequireDefault(_pending),Templates=_interopRequireWildcard(Templates),Repository=_interopRequireWildcard(Repository),WidgetBase=_interopRequireWildcard(WidgetBase),_url=_interopRequireDefault(_url),_jquery=_interopRequireDefault(_jquery),Selectors=_interopRequireWildcard(Selectors);_exports.init=()=>{const pendingPromise=new _pending.default;registerListenerEvents(),pendingPromise.resolve()};const registerListenerEvents=()=>{let{bodyPromiseResolver:bodyPromiseResolver,bodyPromise:bodyPromise}=WidgetBase.promisesAndResolvers();const dropdownMenuContainer=document.querySelector(Selectors.elements.getSearchWidgetDropdownSelector("user"));(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("user")).on("show.bs.dropdown",(async e=>{const courseID=e.relatedTarget.dataset.courseid,groupId=e.relatedTarget.dataset.groupid,actionBaseUrl=_url.default.relativeUrl("/grade/report/user/index.php",{},!1);await WidgetBase.showLoader(dropdownMenuContainer);const data=await Repository.userFetch(courseID,actionBaseUrl,groupId).catch((async e=>{const errorTemplateData={errormessage:e.message};bodyPromiseResolver(await Templates.render("core_grades/searchwidget/error",errorTemplateData))}));if(data===[])return;const allUsersOptionName=await(0,_str.get_string)("allusersnum","gradereport_user",data.users.length),allUsersOption=await Templates.render("gradereport_user/all_users_item",{id:0,name:allUsersOptionName,url:_url.default.relativeUrl("/grade/report/user/index.php",{id:courseID,userid:0},!1)});await WidgetBase.init(dropdownMenuContainer,bodyPromise,data.users,searchUsers(),allUsersOption),bodyPromiseResolver(Templates.render("core_grades/searchwidget/user/usersearch_body",{displayunsearchablecontent:!0}))})),(0,_jquery.default)(Selectors.elements.getSearchWidgetSelector("user")).on("hide.bs.dropdown",(()=>{dropdownMenuContainer.innerHTML=""}))},searchUsers=()=>()=>(users,searchTerm)=>{if(""===searchTerm)return users;searchTerm=searchTerm.toLowerCase();const searchResults=[];return users.forEach((user=>{user.fullname.toLowerCase().includes(searchTerm)&&searchResults.push(user)})),searchResults}})); /** * AMD code for the frequently used comments chooser for the marking guide grading form. * * @module gradingform_guide/comment_chooser * @copyright 2015 Jun Pataleta <jun@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("gradingform_guide/comment_chooser",["jquery","core/templates","core/notification","core/yui"],(function($,templates,notification){return{initialise:function(criterionId,buttonId,remarkId,commentOptions){function generateCommentsChooser(){var context={criterionId:criterionId,comments:commentOptions};templates.render("gradingform_guide/comment_chooser",context).done((function(compiledSource){!function(compiledSource,comments){var titleLabel="<label>"+M.util.get_string("insertcomment","gradingform_guide")+"</label>",cancelButtonId="comment-chooser-"+criterionId+"-cancel",cancelButton='<button id="'+cancelButtonId+'">'+M.util.get_string("cancel","moodle")+"</button>",chooserDialog=new M.core.dialogue({modal:!0,headerContent:titleLabel,bodyContent:compiledSource,footerContent:cancelButton,focusAfterHide:"#"+remarkId,id:"comments-chooser-dialog-"+criterionId});$("#"+cancelButtonId).click((function(){chooserDialog.hide()})),$.each(comments,(function(index,comment){var commentOptionId="#comment-option-"+criterionId+"-"+comment.id;$(commentOptionId).click((function(){var remarkTextArea=$("#"+remarkId),remarkText=remarkTextArea.val();""!==remarkText.trim()&&(remarkText+="\n"),remarkText+=comment.description,remarkTextArea.val(remarkText),chooserDialog.hide()})),$(document).off("keypress",commentOptionId).on("keypress",commentOptionId,(function(){var keyCode=event.which||event.keyCode;13!=keyCode&&32!=keyCode||$(commentOptionId).click()}))})),chooserDialog.after("visibleChange",(function(e){e.prevVal&&!e.newVal&&this.destroy()}),chooserDialog),chooserDialog.show()}(compiledSource,commentOptions)})).fail(notification.exception)}$("#"+buttonId).click((function(e){e.preventDefault(),generateCommentsChooser()}))}}})); define("gradingform_guide/grades/grader/gradingpanel",["exports","core/ajax","core_grades/grades/grader/gradingpanel/normalise","core_grades/grades/grader/gradingpanel/comparison","jquery"],(function(_exports,_ajax,_normalise,_comparison,_jquery){var obj; /** * Grading panel for gradingform_guide. * * @module gradingform_guide/grades/grader/gradingpanel * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.storeCurrentGrade=_exports.fetchCurrentGrade=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.fetchCurrentGrade=(component,contextid,itemname,gradeduserid)=>(0,_ajax.call)([{methodname:"gradingform_guide_grader_gradingpanel_fetch",args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid}}])[0];_exports.storeCurrentGrade=async(component,contextid,itemname,gradeduserid,notifyUser,rootNode)=>{const form=rootNode.querySelector("form");return!0===(0,_comparison.compareData)(form)?(0,_normalise.normaliseResult)(await(0,_ajax.call)([{methodname:"gradingform_guide_grader_gradingpanel_store",args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid,notifyuser:notifyUser,formdata:(0,_jquery.default)(form).serialize()}}])[0]):""}})); define("gradingform_guide/grades/grader/gradingpanel/comments",["exports","./comments/selectors"],(function(_exports,_selectors){var obj; /** * Grading panel frequently used comments selector. * * @module gradingform_guide/grades/grader/gradingpanel/comments * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_selectors=(obj=_selectors)&&obj.__esModule?obj:{default:obj};_exports.init=rootId=>{document.querySelector("#".concat(rootId)).addEventListener("click",(e=>{if(!e.target.matches(_selectors.default.frequentComment))return;e.preventDefault();const clicked=e.target.closest(_selectors.default.frequentComment),remark=clicked.closest(_selectors.default.criterion).querySelector(_selectors.default.remark);remark&&(remark.value.trim()?remark.value+="\n".concat(clicked.innerHTML):remark.value+=clicked.innerHTML)}))}})); define("gradingform_guide/grades/grader/gradingpanel/comments/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={frequentComment:'[data-gradingform_guide-role="frequent-comment"]',criterion:'[data-gradingform-guide-role="criterion"]',remark:'[data-gradingform-guide-role="remark"]'},_exports.default})); define("gradingform_rubric/grades/grader/gradingpanel",["exports","core/ajax","core_grades/grades/grader/gradingpanel/normalise","core_grades/grades/grader/gradingpanel/comparison","jquery"],(function(_exports,_ajax,_normalise,_comparison,_jquery){var obj; /** * Grading panel for gradingform_rubric. * * @module gradingform_rubric/grades/grader/gradingpanel * @copyright 2019 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.storeCurrentGrade=_exports.fetchCurrentGrade=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.fetchCurrentGrade=(component,contextid,itemname,gradeduserid)=>(0,_ajax.call)([{methodname:"gradingform_rubric_grader_gradingpanel_fetch",args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid}}])[0];_exports.storeCurrentGrade=async(component,contextid,itemname,gradeduserid,notifyUser,rootNode)=>{const form=rootNode.querySelector("form");return!0===(0,_comparison.compareData)(form)?(0,_normalise.normaliseResult)(await(0,_ajax.call)([{methodname:"gradingform_rubric_grader_gradingpanel_store",args:{component:component,contextid:contextid,itemname:itemname,gradeduserid:gradeduserid,notifyuser:notifyUser,formdata:(0,_jquery.default)(form).serialize()}}])[0]):""}})); define("qbank_columnsortorder/sort_columns",["exports","core/ajax","core/notification","core/sortable_list","jquery"],(function(_exports,_ajax,_notification,_sortable_list,_jquery){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript for sorting columns in question bank view. * * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Ghaly Marc-Alexandre <marc-alexandreghaly@catalyst-ca.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_sortable_list=_interopRequireDefault(_sortable_list),_jquery=_interopRequireDefault(_jquery);const setOrder=columns=>(0,_ajax.call)([{methodname:"qbank_columnsortorder_set_columnbank_order",args:{columns:columns}}])[0],getColumnOrder=listRoot=>{const columns=Array.from(listRoot.querySelectorAll("[data-pluginname]")).map((column=>column.dataset.pluginname));return columns.filter(((value,index)=>columns.indexOf(value)===index))};_exports.init=id=>{(listRoot=>{new _sortable_list.default(".list",{moveHandlerSelector:".item"}),(0,_jquery.default)(".item").on(_sortable_list.default.EVENTS.DROP,(()=>{const columns=getColumnOrder(listRoot);setOrder(columns).catch(_notification.exception),listRoot.querySelectorAll(".item").forEach((item=>item.classList.remove("active")))})),(0,_jquery.default)(".item").on(_sortable_list.default.EVENTS.DRAGSTART,(event=>{event.currentTarget.classList.add("active")}))})(document.querySelector("#".concat(id)))}})); define("qbank_comment/comment",["exports","core/fragment","core/str","core/modal_events","core/modal_factory","core/notification"],(function(_exports,_fragment,Str,_modal_events,_modal_factory,_notification){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Column selector js. * * @module qbank_comment/comment * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Safat Shahin <safatshahin@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_fragment=_interopRequireDefault(_fragment),Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification);_exports.init=questionSelector=>{const target=document.querySelector(questionSelector);target.addEventListener("click",(()=>{((questionId,courseID,contextId)=>{let args={questionid:questionId,courseid:courseID};_modal_factory.default.create({type:_modal_factory.default.types.SAVE_CANCEL,title:Str.get_string("commentheader","qbank_comment"),body:_fragment.default.loadFragment("qbank_comment","question_comment",contextId,args),large:!0}).then((modal=>{let root=modal.getRoot();return root.on(_modal_events.default.bodyRendered,(function(){document.querySelectorAll("div.comment-area a")[0].style.display="none"})),root.on("change","#question_comment_version_dropdown",(function(e){args.questionid=e.target.value,modal.setBody(_fragment.default.loadFragment("qbank_comment","question_comment",contextId,args))})),Str.get_strings([{key:"addcomment",component:"qbank_comment"},{key:"close",component:"qbank_comment"}]).then((strings=>{modal.setButtonText("save",strings[0]),modal.setButtonText("cancel",strings[1])})).fail(_notification.default.exception),root.on(_modal_events.default.cancel,(function(){location.reload(),modal.hide()})),root.on(_modal_events.default.save,(function(e){e.preventDefault();const submitlink=document.querySelectorAll("div.comment-area a")[0],textarea=document.querySelectorAll("div.comment-area textarea")[0];textarea.value!=textarea.getAttribute("aria-label")&&""!=textarea.value&&submitlink.click()})),root.on("click",'button[data-action="hide"]',(()=>{location.reload(),modal.hide()})),modal.show(),modal})).fail(_notification.default.exception)})(target.dataset.questionid,target.dataset.courseid,target.dataset.contextid)}))}})); define("qbank_editquestion/question_status",["exports","core/ajax","core/notification"],(function(_exports,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Status column selector js. * * @module qbank_editquestion/question_status * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Safat Shahin <safatshahin@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);_exports.init=questionId=>{document.querySelector("#question_status_dropdown-"+questionId).addEventListener("change",(e=>{const questionStatus=e.target.value;((questionId,status)=>_ajax.default.call([{methodname:"qbank_editquestion_set_status",args:{questionid:questionId,status:status}}])[0])(questionId,questionStatus).then((response=>{response.error&&_notification.default.addNotification({type:"error",message:response.error})})).catch()}))}})); define("qbank_previewquestion/preview",["exports","jquery"],(function(_exports,_jquery){var obj; /** * Javascript for preview. * * @module qbank_preview/preview * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Safat Shahin <safatshahin@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};_exports.init=(redirect,url)=>{if(!redirect){document.getElementById("close-previewquestion-page").onclick=()=>{null===window.opener?location.href=url:window.close()}}setupQuestionForm("responseform")};const setupQuestionForm=formElement=>{let form=document.getElementById(formElement);form&&(autocompleteOff(form),preventRepeatSubmission(form),removeClass(".questionflagsavebutton",form),scrollToSavedPos(form))},autocompleteOff=form=>{form.setAttribute("autocomplete","off")},preventRepeatSubmission=form=>{form.addEventListener("submit",(function(){return(0,_jquery.default)(this).submit((function(){return!1})),!0}))},removeClass=(classname,form)=>{form.querySelectorAll(classname).forEach((e=>e.remove()))},scrollToSavedPos=form=>{let matches=window.location.href.match(/^.*[?&]scrollpos=(\d*)(?:&|$|#).*$/,"$1");matches&&(window.scrollTo(0,matches[1]),form.addEventListener("DOMContentLoaded",(()=>{window.scrollTo(0,matches[1])})))}})); /** * A javascript module to handle question tags editing. * * @module qbank_tagquestion/edit_tags * @copyright 2018 Simey Lameze <simey@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qbank_tagquestion/edit_tags",["jquery","core/fragment","core/str","core/modal_events","core/modal_factory","core/notification","core/custom_interaction_events","qbank_tagquestion/repository","qbank_tagquestion/selectors"],(function($,Fragment,Str,ModalEvents,ModalFactory,Notification,CustomEvents,Repository,QuestionSelectors){var enableSaveButton=function(root){root.find(QuestionSelectors.actions.save).prop("disabled",!1)},disableSaveButton=function(root){root.find(QuestionSelectors.actions.save).prop("disabled",!0)},startLoading=function(root){root.find(QuestionSelectors.containers.loadingIcon).removeClass("hidden")},stopLoading=function(root){root.find(QuestionSelectors.containers.loadingIcon).addClass("hidden")},save=function(modal,root){disableSaveButton(root),startLoading(root);var formData=function(modal){return modal.getBody().find("form").serialize()}(modal),questionId=function(modal){return modal.getBody().data("questionid")}(modal),contextId=function(modal){return modal.getBody().data("contextid")}(modal);return Repository.submitTagCreateUpdateForm(questionId,contextId,formData).always((function(){stopLoading(root),enableSaveButton(root)})).fail(Notification.exception)};return{init:function(root){!function(root){var modalPromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,large:!1},[root,QuestionSelectors.actions.edittags]).then((function(modal){return Str.get_string("questiontags","question").then((function(string){return modal.setTitle(string),string})).fail(Notification.exception),modal.getRoot().on(ModalEvents.save,(function(e){modal.getBody().find("form").submit(),e.preventDefault()})),modal.getRoot().on("submit","form",(function(e){save(modal,root).then((function(){modal.hide(),location.reload()})).fail(Notification.exception),e.preventDefault(),e.stopPropagation()})),modal}));root.on(CustomEvents.events.activate,QuestionSelectors.actions.edittags,(function(e){var currentTarget=$(e.currentTarget),questionId=currentTarget.data("questionid"),canTag=!!currentTarget.data("cantag"),contextId=currentTarget.data("contextid");modalPromise.then((function(modal){disableSaveButton(root),startLoading(root);var args={id:questionId},tagsFragment=Fragment.loadFragment("qbank_tagquestion","tags_form",contextId,args);return modal.setBody(tagsFragment),tagsFragment.then((function(){enableSaveButton(root)})).always((function(){stopLoading(root)})).fail(Notification.exception),canTag?modal.getRoot().find(QuestionSelectors.actions.save).show():modal.getRoot().find(QuestionSelectors.actions.save).hide(),function(modal,questionId){modal.getBody().attr("data-questionid",questionId)}(modal,questionId),function(modal,contextId){modal.getBody().attr("data-contextid",contextId)}(modal,contextId),modal})).fail(Notification.exception),e.preventDefault()}))}(root=$(root))}}})); /** * A javascript module to handle question ajax actions. * * @module qbank_tagquestion/repository * @class repository * @copyright 2017 Simey Lameze <lameze@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qbank_tagquestion/repository",["jquery","core/ajax"],(function($,Ajax){return{submitTagCreateUpdateForm:function(questionId,contextId,formdata){var request={methodname:"qbank_tagquestion_submit_tags_form",args:{questionid:questionId,contextid:contextId,formdata:formdata}};return Ajax.call([request])[0]}}})); /** * The purpose of this module is to centralize selectors related to question. * * @module qbank_tagquestion/question_selectors * @copyright 2018 Simey Lameze <lameze@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("qbank_tagquestion/selectors",[],(function(){return{actions:{save:'[data-action="save"]',edittags:'[data-action="edittags"]'},containers:{loadingIcon:'[data-region="overlay-icon-container"]'}}})); define("qbank_usage/usage",["exports","core/fragment","core/modal_factory","core/notification","core/str"],(function(_exports,_fragment,_modal_factory,_notification,Str){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Usage column selector js. * * @module qbank_usage/usage * @copyright 2021 Catalyst IT Australia Pty Ltd * @author Safat Shahin <safatshahin@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_fragment=_interopRequireDefault(_fragment),_modal_factory=_interopRequireDefault(_modal_factory),_notification=_interopRequireDefault(_notification),Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str);_exports.init=(questionSelector,contextId)=>{let target=document.querySelector(questionSelector),questionId=target.getAttribute("data-questionid");target.addEventListener("click",(()=>{((questionId,contextId)=>{let args={questionid:questionId};_modal_factory.default.create({type:_modal_factory.default.types.CANCEL,title:Str.get_string("usageheader","qbank_usage"),body:_fragment.default.loadFragment("qbank_usage","question_usage",contextId,args),large:!0}).then((modal=>(modal.show(),modal.getRoot().on("click","a[href].page-link",(function(e){e.preventDefault();let attr=e.target.getAttribute("href");"#"!==attr&&(args.querystring=attr,modal.setBody(_fragment.default.loadFragment("qbank_usage","question_usage",contextId,args)))})),modal.getRoot().on("change","#question_usage_version_dropdown",(function(e){args.questionid=e.target.value,modal.setBody(_fragment.default.loadFragment("qbank_usage","question_usage",contextId,args))})),modal))).fail(_notification.default.exception)})(questionId,contextId)}))}})); define("plagiarism_turnitin/open_viewer",["jquery"],(function($){return{origreport_open:function(){var that=this;$(document).on("click",".pp_origreport_open",(function(){for(var classList=$(this).attr("class").replace(/\s+/," ").split(" "),i=0;i<classList.length;i++)if(-1!==classList[i].indexOf("origreport_")&&"pp_origreport_open"!=classList[i]){var classStr=classList[i].split("_");that.openDV("origreport",classStr[1],classStr[2])}}))},grademark_open:function(){var that=this;$(document).on("click",".pp_grademark_open",(function(){for(var classList=$(this).attr("class").replace(/\s+/," ").split(" "),i=0;i<classList.length;i++)if(-1!==classList[i].indexOf("grademark_")&&"pp_grademark_open"!=classList[i]){var classStr=classList[i].split("_");that.openDV("grademark",classStr[1],classStr[2])}}))},openDV:function(dvtype,submissionid,coursemoduleid){var that=this,dvWindow=window.open("","turnitin_viewer"),loading='<div class="tii_dv_loading" style="text-align:center;">';loading+='<img src="'+M.cfg.wwwroot+'/plagiarism/turnitin/pix/turnitin-icon.png" style="width:100px; height: 100px">',loading+='<p style="font-family: Arial, Helvetica, sans-serif;">'+M.str.plagiarism_turnitin.loadingdv+"</p>",loading+="</div>",$(dvWindow.document.body).html(loading),$.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"get_dv_html",submissionid:submissionid,dvtype:dvtype,cmid:coursemoduleid,sesskey:M.cfg.sesskey},success:function(data){$(dvWindow.document.body).html(loading+data),dvWindow.document.forms[0].submit(),dvWindow.document.close(),that.checkDVClosed(submissionid,coursemoduleid,dvWindow)}})},checkDVClosed:function(submissionid,coursemoduleid,dvWindow){var that=this;dvWindow.closed?that.refreshScores(submissionid,coursemoduleid):setTimeout((function(){that.checkDVClosed(submissionid,coursemoduleid,dvWindow)}),500)},refreshScores:function(submission_id,coursemoduleid){var refreshStartTime=(new Date).getTime();$.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"update_grade",submission:submission_id,cmid:coursemoduleid,sesskey:M.cfg.sesskey},success:function(){(new Date).getTime()-refreshStartTime<3e3||!$(".turnitin_score_refresh_alert").length?window.location=window.location+"":$(".turnitin_score_refresh_alert").show()}})}}})); define("plagiarism_turnitin/eula",["jquery","core/templates","core/modal_factory","core/modal_events","plagiarism_turnitin/modal_eula_launch"],(function($,Templates,ModalFactory,ModalEvents,ModalEulaLaunch){return{eulaLaunch:function(){var turnitinEulaClass=$(".pp_turnitin_eula");turnitinEulaClass.show(),$(document).on("mod_forum-post-created",".forum-post-container",(function(event,newid){$("#post-content-"+newid+" .pp_turnitin_eula").show()})),$(document).on("click",".pp_turnitin_eula_link",(function(){ModalFactory.create({type:ModalEulaLaunch.TYPE,templateContext:{cmid:$('input[name="coursemodule"]').val(),wwwroot:M.cfg.wwwroot},large:!0}).then((function(modal){modal.show(),modal.getRoot().find(".modal").addClass("tii_pp_modal_eula"),modal.getRoot().find(".modal-content").addClass("tii_pp_modal_eula_content")}))})),$(".pp_turnitin_eula_ignored").length>0&&($(".editsubmissionform").length>0&&$(".editsubmissionform").hide(),turnitinEulaClass.siblings(".mform").length>0&&turnitinEulaClass.siblings(".mform").hide())}}})); define("plagiarism_turnitin/peermark",["jquery","core/templates","core/modal_factory","core/modal_events","plagiarism_turnitin/modal_peermark_manager_launch","plagiarism_turnitin/modal_peermark_reviews_launch"],(function($,Templates,ModalFactory,ModalEvents,ModalPeermarkManagerLaunch,ModalPeermarkReviewsLaunch){return{peermarkLaunch:function(){var that=this;$(".peermark_manager_launch").on("click",(function(event){event.preventDefault(),that.peermarkCreateModal(ModalPeermarkManagerLaunch.TYPE)})),$(document).on("click",".peermark_reviews_pp_launch",(function(){that.peermarkCreateModal(ModalPeermarkReviewsLaunch.TYPE)}))},peermarkCreateModal:function(modalType){if($('input[name="coursemodule"]').val())var cmid=$('input[name="coursemodule"]').val();else cmid=new URLSearchParams(window.location.search).get("id");ModalFactory.create({type:modalType,templateContext:{cmid:cmid,wwwroot:M.cfg.wwwroot},large:!0}).then((function(modal){modal.show()}))}}})); define("plagiarism_turnitin/modal_peermark_manager_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',SELECTORS_MODAL='[data-region="modal"]',ModalPeermarkManagerLaunch=function(root){Modal.call(this,root)};function refreshPeermarkAssignments(){$.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"refresh_peermark_assignments",cmid:$('input[name="coursemodule"]').val(),sesskey:M.cfg.sesskey}})}return ModalPeermarkManagerLaunch.TYPE="plagiarism_turnitin-modal_peermark_manager_launch",(ModalPeermarkManagerLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalPeermarkManagerLaunch,ModalPeermarkManagerLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault(),refreshPeermarkAssignments())}.bind(this)),this.getRoot().click(function(e){$(e.target).closest(SELECTORS_MODAL).length||refreshPeermarkAssignments()}.bind(this))},registered||(ModalRegistry.register(ModalPeermarkManagerLaunch.TYPE,ModalPeermarkManagerLaunch,"plagiarism_turnitin/modal_peermark_manager_launch"),registered=!0),ModalPeermarkManagerLaunch})); define("plagiarism_turnitin/rubric",["jquery","core/templates","core/modal_factory","core/modal_events","plagiarism_turnitin/modal_rubric_manager_launch","plagiarism_turnitin/modal_rubric_view_launch"],(function($,Templates,ModalFactory,ModalEvents,ModalRubricManagerLaunch,ModalRubricViewLaunch){return{rubric:function(){var that=this;$(".rubric_manager_launch").on("click",(function(){var courseid=$(this).data("courseid"),cmid=$(this).data("cmid");that.rubricCreateModal(ModalRubricManagerLaunch.TYPE,courseid,cmid)})),$(document).on("click",".rubric_view",(function(){var courseid=$(this).data("courseid"),cmid=$(this).data("cmid");that.rubricCreateModal(ModalRubricViewLaunch.TYPE,courseid,cmid)})),$("#id_plagiarism_rubric").mousedown((function(){""!=$('input[name="instance"]').val()&&"Y"!=$('input[name="rubric_warning_seen"]').val()&&confirm(M.str.plagiarism_turnitin.changerubricwarning)&&$('input[name="rubric_warning_seen"]').val("Y")}))},rubricCreateModal:function(modalType,courseid,cmid){ModalFactory.create({type:modalType,templateContext:{courseid:courseid,cmid:cmid,wwwroot:M.cfg.wwwroot},large:!0}).then((function(modal){modal.show(),modal.getRoot().find(".modal").addClass("tii_pp_modal_rubric"),modal.getRoot().find(".modal-dialog").addClass("tii_pp_modal_rubric_content")}))}}})); define("plagiarism_turnitin/modal_rubric_view_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',ModalRubricViewLaunch=function(root){Modal.call(this,root)};return ModalRubricViewLaunch.TYPE="plagiarism_turnitin-modal_rubric_view_launch",(ModalRubricViewLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalRubricViewLaunch,ModalRubricViewLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalRubricViewLaunch.TYPE,ModalRubricViewLaunch,"plagiarism_turnitin/modal_rubric_view_launch"),registered=!0),ModalRubricViewLaunch})); define("plagiarism_turnitin/modal_rubric_manager_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',SELECTORS_MODAL='[data-region="modal"]',ModalRubricManagerLaunch=function(root){Modal.call(this,root)};function refreshRubricSelect(){var currentRubric=$("#id_plagiarism_rubric").val();$.ajax({dataType:"json",type:"POST",url:"../plagiarism/turnitin/ajax.php",data:{action:"refresh_rubric_select",assignment:$('input[name="instance"]').val(),modulename:$('input[name="modulename"]').val(),course:$('input[name="course"]').val()},success:function(data){$($("#id_plagiarism_rubric")).empty();var options=data;$.each(options,(function(i,val){if($.isNumeric(i)||""===i)$($("#id_plagiarism_rubric")).append($("<option>",{value:i,text:val}));else{var optgroup=$("<optgroup>");optgroup.attr("label",i),$.each(val,(function(j,rubric){var option=$("<option></option>");option.val(j),option.text(rubric),optgroup.append(option)})),$("#id_plagiarism_rubric").append(optgroup)}})),$('#id_plagiarism_rubric option[value="'+currentRubric+'"]').attr("selected","selected")}})}return ModalRubricManagerLaunch.TYPE="plagiarism_turnitin-modal_rubric_manager_launch",(ModalRubricManagerLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalRubricManagerLaunch,ModalRubricManagerLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault(),refreshRubricSelect())}.bind(this)),this.getRoot().click(function(e){$(e.target).closest(SELECTORS_MODAL).length||refreshRubricSelect()}.bind(this))},registered||(ModalRegistry.register(ModalRubricManagerLaunch.TYPE,ModalRubricManagerLaunch,"plagiarism_turnitin/modal_rubric_manager_launch"),registered=!0),ModalRubricManagerLaunch})); define("plagiarism_turnitin/modal_eula_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',ModalEulaLaunch=function(root){Modal.call(this,root)};return ModalEulaLaunch.TYPE="plagiarism_turnitin-modal_eula_launch",(ModalEulaLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalEulaLaunch,ModalEulaLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),$(window).on("message",(function(ev){var message=void 0===ev.data?ev.originalEvent.data:ev.data;"turnitin_eula_declined"!==message&&"turnitin_eula_accepted"!==message||$.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"actionuseragreement",message:message,sesskey:M.cfg.sesskey},success:function(){window.location.reload()},error:function(){window.location.reload()}})})),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalEulaLaunch.TYPE,ModalEulaLaunch,"plagiarism_turnitin/modal_eula_launch"),registered=!0),ModalEulaLaunch})); define("plagiarism_turnitin/refresh_submissions",["jquery"],(function($){return{refreshSubmissions:function(){$(".plagiarism_turnitin_refresh_grades").on("click",(function(){$(".plagiarism_turnitin_refresh_grades").hide(),$(".plagiarism_turnitin_refreshing_grades").show(),$.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"update_grade",cmid:$('input[name="coursemodule"]').val(),sesskey:M.cfg.sesskey},success:function(){$(".plagiarism_turnitin_refresh_grades").show(),$(".plagiarism_turnitin_refreshing_grades").hide()}})}))}}})); define("plagiarism_turnitin/modal_peermark_reviews_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',ModalPeermarkReviewsLaunch=function(root){Modal.call(this,root)};return ModalPeermarkReviewsLaunch.TYPE="plagiarism_turnitin-modal_peermark_reviews_launch",(ModalPeermarkReviewsLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalPeermarkReviewsLaunch,ModalPeermarkReviewsLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalPeermarkReviewsLaunch.TYPE,ModalPeermarkReviewsLaunch,"plagiarism_turnitin/modal_peermark_reviews_launch"),registered=!0),ModalPeermarkReviewsLaunch})); define("plagiarism_turnitin/resend_submission",["jquery"],(function($){return{resendSubmission:function(){$(document).on("click",".plagiarism_turnitin_resubmit_link",(function(){$(this).hide(),$(this).siblings(".pp_resubmitting").removeClass("hidden");var that=$(this),submissionid=$(this).prop("id").split("_")[2],forumpost=$("#content_"+submissionid).html(),forumdata=$("#forumdata_"+submissionid).html();return $.ajax({type:"POST",url:M.cfg.wwwroot+"/plagiarism/turnitin/ajax.php",dataType:"json",data:{action:"resubmit_event",submissionid:submissionid,forumpost:forumpost,forumdata:forumdata,sesskey:M.cfg.sesskey},success:function(){that.siblings(".turnitin_status").removeClass("hidden"),that.siblings(".pp_resubmitting").addClass("hidden")},error:function(){that.show(),that.siblings(".pp_resubmitting").addClass("hidden")}}),!1}))}}})); define("plagiarism_turnitin/quickmark",["jquery","core/templates","core/modal_factory","core/modal_events","plagiarism_turnitin/modal_quickmark_launch"],(function($,Templates,ModalFactory,ModalEvents,ModalQuickmarkLaunch){return{quickmarkLaunch:function(){$(".plagiarism_turnitin_quickmark_manager_launch").on("click",(function(event){event.preventDefault(),ModalFactory.create({type:ModalQuickmarkLaunch.TYPE,templateContext:{cmid:$('input[name="coursemodule"]').val(),wwwroot:M.cfg.wwwroot},large:!0}).then((function(modal){modal.show()}))}))}}})); define("plagiarism_turnitin/modal_quickmark_launch",["jquery","core/ajax","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","core/modal_events"],(function($,Ajax,Notification,CustomEvents,Modal,ModalRegistry,ModalEvents){var registered=!1,SELECTORS_HIDE_BUTTON='[data-action="hide"]',ModalQuickmarkLaunch=function(root){Modal.call(this,root)};return ModalQuickmarkLaunch.TYPE="plagiarism_turnitin-modal_quickmark_launch",(ModalQuickmarkLaunch.prototype=Object.create(Modal.prototype)).constructor=ModalQuickmarkLaunch,ModalQuickmarkLaunch.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_HIDE_BUTTON,function(e,data){var cancelEvent=$.Event(ModalEvents.cancel);this.getRoot().trigger(cancelEvent,this),cancelEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalQuickmarkLaunch.TYPE,ModalQuickmarkLaunch,"plagiarism_turnitin/modal_quickmark_launch"),registered=!0),ModalQuickmarkLaunch})); /** * Shows a dialogue with info about this logs. * * @module tool_analytics/log_info * @copyright 2017 David Monllao {@link http://www.davidmonllao.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_analytics/log_info",["jquery","core/str","core/modal_factory","core/notification"],(function($,str,ModalFactory,Notification){return{loadInfo:function(id,info){var link=$('[data-model-log-id="'+id+'"]');str.get_string("loginfo","tool_analytics").then((function(langString){var bodyInfo=$("<ul>");return info.forEach((function(item){bodyInfo.append("<li>"+item+"</li>")})),bodyInfo.append("</ul>"),ModalFactory.create({title:langString,body:bodyInfo.html(),large:!0},link)})).catch(Notification.exception)}}})); /** * AMD module for model actions confirmation. * * @module tool_analytics/model * @copyright 2017 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_analytics/model",["jquery","core/str","core/log","core/notification","core/modal_factory","core/modal_events","core/templates"],(function($,Str,log,Notification,ModalFactory,ModalEvents,Templates){var actionsList={clear:{title:{key:"clearpredictions",component:"tool_analytics"},body:{key:"clearmodelpredictions",component:"tool_analytics"}},delete:{title:{key:"delete",component:"tool_analytics"},body:{key:"deletemodelconfirmation",component:"tool_analytics"}}};return{confirmAction:function(actionId,actionType){$('[data-action-id="'+actionId+'"]').on("click",(function(ev){ev.preventDefault();var a=$(ev.currentTarget);if(void 0!==actionsList[actionType]){var wrap,reqStrings=[actionsList[actionType].title,actionsList[actionType].body];reqStrings[1].param=(wrap=$(a).closest("[data-model-name]")).length?wrap.attr("data-model-name"):(log.error("Unexpected DOM error - unable to obtain the model name"),"");var stringsPromise=Str.get_strings(reqStrings),modalPromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL});$.when(stringsPromise,modalPromise).then((function(strings,modal){return modal.setTitle(strings[0]),modal.setBody(strings[1]),modal.setSaveButtonText(strings[0]),modal.getRoot().on(ModalEvents.save,(function(){window.location.href=a.attr("href")})),modal.show(),modal})).fail(Notification.exception)}else log.error('Action "'+actionType+'" is not allowed.')}))},selectEvaluationOptions:function(actionId,trainedOnlyExternally){$('[data-action-id="'+actionId+'"]').on("click",(function(ev){ev.preventDefault();var a=$(ev.currentTarget),timeSplittingMethods=$(this).attr("data-timesplitting-methods"),stringsPromise=Str.get_strings([{key:"evaluatemodel",component:"tool_analytics"},{key:"evaluate",component:"tool_analytics"}]),modalPromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL}),bodyPromise=Templates.render("tool_analytics/evaluation_options",{trainedexternally:trainedOnlyExternally,timesplittingmethods:JSON.parse(timeSplittingMethods)});$.when(stringsPromise,modalPromise).then((function(strings,modal){return modal.getRoot().on(ModalEvents.hidden,modal.destroy.bind(modal)),modal.setTitle(strings[0]),modal.setSaveButtonText(strings[1]),modal.setBody(bodyPromise),modal.getRoot().on(ModalEvents.save,(function(){"trainedmodel"==$("input[name='evaluationmode']:checked").val()&&a.attr("href",a.attr("href")+"&mode=trainedmodel");var timeSplittingMethod=$("#id-evaluation-timesplitting").val();a.attr("href",a.attr("href")+"×plitting="+timeSplittingMethod),window.location.href=a.attr("href")})),modal.show(),modal})).fail(Notification.exception)}))},selectExportOptions:function(actionId,isTrained){$('[data-action-id="'+actionId+'"]').on("click",(function(ev){ev.preventDefault();var a=$(ev.currentTarget);if(!isTrained)return a.attr("href",a.attr("href")+"&action=exportmodel&includeweights=0"),void(window.location.href=a.attr("href"));var stringsPromise=Str.get_strings([{key:"export",component:"tool_analytics"}]),modalPromise=ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL}),bodyPromise=Templates.render("tool_analytics/export_options",{});$.when(stringsPromise,modalPromise).then((function(strings,modal){return modal.getRoot().on(ModalEvents.hidden,modal.destroy.bind(modal)),modal.setTitle(strings[0]),modal.setSaveButtonText(strings[0]),modal.setBody(bodyPromise),modal.getRoot().on(ModalEvents.save,(function(){"exportdata"==$("input[name='exportoption']:checked").val()?a.attr("href",a.attr("href")+"&action=exportdata"):(a.attr("href",a.attr("href")+"&action=exportmodel"),$("#id-includeweights").is(":checked")?a.attr("href",a.attr("href")+"&includeweights=1"):a.attr("href",a.attr("href")+"&includeweights=0")),window.location.href=a.attr("href")})),modal.show(),modal})).fail(Notification.exception)}))}}})); /** * Potential contexts selector module. * * @module tool_analytics/potential-contexts * @copyright 2019 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_analytics/potential-contexts",["jquery","core/ajax"],(function($,Ajax){return{processResults:function(selector,results){var contexts=[];return $.isArray(results)?($.each(results,(function(index,context){contexts.push({value:context.id,label:context.name})})),contexts):results},transport:function(selector,query,success,failure){let modelid=$(selector).attr("modelid")||null;Ajax.call([{methodname:"tool_analytics_potential_contexts",args:{query:query,modelid:modelid}}])[0].then(success).fail(failure)}}})); define("tool_behat/steps",["exports","core/ajax","core/templates","core/pending"],(function(_exports,_ajax,_templates,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Enhancements for the step definitions page. * * @module tool_behat/steps * @copyright 2022 Catalyst IT EU * @author Mark Johnson <mark.johnson@catalyst-eu.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_templates=_interopRequireDefault(_templates),_pending=_interopRequireDefault(_pending);_exports.init=()=>{document.addEventListener("change",(async e=>{const entityElement=e.target.closest(".entities"),stepElement=e.target.closest(".stepcontent");if(!entityElement||!stepElement)return;const pendingPromise=new _pending.default("tool_behat/steps:change"),entityData=await(entityType=e.target.value,_ajax.default.call([{methodname:"tool_behat_get_entity_generator",args:{entitytype:entityType}}])[0]);var entityType;const{html:html,js:js}=await(entityData=>{var _entityData$required;return null!==(_entityData$required=entityData.required)&&void 0!==_entityData$required&&_entityData$required.length?_templates.default.renderForPromise("tool_behat/steprequiredfields",{fields:entityData.required}):Promise.resolve({html:"",js:""})})(entityData),stepRequiredFields=stepElement.querySelector(".steprequiredfields");stepRequiredFields?await _templates.default.replaceNode(stepRequiredFields,html,js):await _templates.default.appendNodeContents(stepElement,html,js),pendingPromise.resolve()}))}})); define("tool_componentlibrary/clipboardwrapper",["exports","core/copy_to_clipboard","tool_componentlibrary/selectors","core/templates"],(function(_exports,_copy_to_clipboard,_selectors,_templates){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Wrapper to ensure that all Hugo example snippets have a "Copy to clipboard" button. * * @module tool_componentlibrary/clipboardwrapper * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.clipboardWrapper=void 0,_selectors=_interopRequireDefault(_selectors),_templates=_interopRequireDefault(_templates);let idCounter=0;_exports.clipboardWrapper=async()=>{document.querySelectorAll(_selectors.default.clipboardcontent).forEach((element=>{element.id||(element.id="tool_componentlibrary_content-".concat(idCounter++)),_templates.default.renderForPromise("tool_componentlibrary/clipboardbutton",{clipboardtarget:"#".concat(element.id," code")}).then((_ref=>{let{html:html,js:js}=_ref;_templates.default.prependNodeContents(element,html,js)})).catch()}))}})); define("tool_componentlibrary/jsrunner",["exports","tool_componentlibrary/selectors"],(function(_exports,_selectors){var obj; /** * Run the JS required for example code to work in the library. * * @module tool_componentlibrary/jsrunner * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.jsRunner=void 0,_selectors=(obj=_selectors)&&obj.__esModule?obj:{default:obj};_exports.jsRunner=()=>{document.querySelector(_selectors.default.componentlibrary).querySelectorAll(_selectors.default.jscode).forEach((runjs=>{const script=document.createElement("script");script.type="text/javascript",script.innerHTML=runjs.textContent,document.head.appendChild(script)}))}})); define("tool_componentlibrary/loader",["exports","./mustache","./jsrunner","./clipboardwrapper","./search"],(function(_exports,_mustache,_jsrunner,_clipboardwrapper,_search){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=jsonFile=>{(0,_mustache.mustache)(),(0,_jsrunner.jsRunner)(),(0,_clipboardwrapper.clipboardWrapper)(),(0,_search.search)(jsonFile)}})); /** * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9 * Copyright (C) 2020 Oliver Nightingale * @license MIT */ !function(){var global,step2list,step3list,v,C,re_mgr0,re_mgr1,re_meq1,re_s_v,re_1a,re2_1a,re_1b,re2_1b,re_1b_2,re2_1b_2,re3_1b_2,re4_1b_2,re_1c,re_2,re_3,re_4,re2_4,re_5,re_5_1,re3_5,porterStemmer,root,factory,lunr=function(config){var builder=new lunr.Builder;return builder.pipeline.add(lunr.trimmer,lunr.stopWordFilter,lunr.stemmer),builder.searchPipeline.add(lunr.stemmer),config.call(builder,builder),builder.build()};lunr.version="2.3.9",lunr.utils={},lunr.utils.warn=(global=this,function(message){global.console&&console.warn&&console.warn(message)}),lunr.utils.asString=function(obj){return null==obj?"":obj.toString()},lunr.utils.clone=function(obj){if(null==obj)return obj;for(var clone=Object.create(null),keys=Object.keys(obj),i=0;i<keys.length;i++){var key=keys[i],val=obj[key];if(Array.isArray(val))clone[key]=val.slice();else{if("string"!=typeof val&&"number"!=typeof val&&"boolean"!=typeof val)throw new TypeError("clone is not deep and does not support nested objects");clone[key]=val}}return clone},lunr.FieldRef=function(docRef,fieldName,stringValue){this.docRef=docRef,this.fieldName=fieldName,this._stringValue=stringValue},lunr.FieldRef.joiner="/",lunr.FieldRef.fromString=function(s){var n=s.indexOf(lunr.FieldRef.joiner);if(-1===n)throw"malformed field ref string";var fieldRef=s.slice(0,n),docRef=s.slice(n+1);return new lunr.FieldRef(docRef,fieldRef,s)},lunr.FieldRef.prototype.toString=function(){return null==this._stringValue&&(this._stringValue=this.fieldName+lunr.FieldRef.joiner+this.docRef),this._stringValue},lunr.Set=function(elements){if(this.elements=Object.create(null),elements){this.length=elements.length;for(var i=0;i<this.length;i++)this.elements[elements[i]]=!0}else this.length=0},lunr.Set.complete={intersect:function(other){return other},union:function(){return this},contains:function(){return!0}},lunr.Set.empty={intersect:function(){return this},union:function(other){return other},contains:function(){return!1}},lunr.Set.prototype.contains=function(object){return!!this.elements[object]},lunr.Set.prototype.intersect=function(other){var a,b,elements,intersection=[];if(other===lunr.Set.complete)return this;if(other===lunr.Set.empty)return other;this.length<other.length?(a=this,b=other):(a=other,b=this),elements=Object.keys(a.elements);for(var i=0;i<elements.length;i++){var element=elements[i];element in b.elements&&intersection.push(element)}return new lunr.Set(intersection)},lunr.Set.prototype.union=function(other){return other===lunr.Set.complete?lunr.Set.complete:other===lunr.Set.empty?this:new lunr.Set(Object.keys(this.elements).concat(Object.keys(other.elements)))},lunr.idf=function(posting,documentCount){var documentsWithTerm=0;for(var fieldName in posting)"_index"!=fieldName&&(documentsWithTerm+=Object.keys(posting[fieldName]).length);var x=(documentCount-documentsWithTerm+.5)/(documentsWithTerm+.5);return Math.log(1+Math.abs(x))},lunr.Token=function(str,metadata){this.str=str||"",this.metadata=metadata||{}},lunr.Token.prototype.toString=function(){return this.str},lunr.Token.prototype.update=function(fn){return this.str=fn(this.str,this.metadata),this},lunr.Token.prototype.clone=function(fn){return fn=fn||function(s){return s},new lunr.Token(fn(this.str,this.metadata),this.metadata)},lunr.tokenizer=function(obj,metadata){if(null==obj||null==obj)return[];if(Array.isArray(obj))return obj.map((function(t){return new lunr.Token(lunr.utils.asString(t).toLowerCase(),lunr.utils.clone(metadata))}));for(var str=obj.toString().toLowerCase(),len=str.length,tokens=[],sliceEnd=0,sliceStart=0;sliceEnd<=len;sliceEnd++){var sliceLength=sliceEnd-sliceStart;if(str.charAt(sliceEnd).match(lunr.tokenizer.separator)||sliceEnd==len){if(sliceLength>0){var tokenMetadata=lunr.utils.clone(metadata)||{};tokenMetadata.position=[sliceStart,sliceLength],tokenMetadata.index=tokens.length,tokens.push(new lunr.Token(str.slice(sliceStart,sliceEnd),tokenMetadata))}sliceStart=sliceEnd+1}}return tokens},lunr.tokenizer.separator=/[\s\-]+/,lunr.Pipeline=function(){this._stack=[]},lunr.Pipeline.registeredFunctions=Object.create(null),lunr.Pipeline.registerFunction=function(fn,label){label in this.registeredFunctions&&lunr.utils.warn("Overwriting existing registered function: "+label),fn.label=label,lunr.Pipeline.registeredFunctions[fn.label]=fn},lunr.Pipeline.warnIfFunctionNotRegistered=function(fn){fn.label&&fn.label in this.registeredFunctions||lunr.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",fn)},lunr.Pipeline.load=function(serialised){var pipeline=new lunr.Pipeline;return serialised.forEach((function(fnName){var fn=lunr.Pipeline.registeredFunctions[fnName];if(!fn)throw new Error("Cannot load unregistered function: "+fnName);pipeline.add(fn)})),pipeline},lunr.Pipeline.prototype.add=function(){var fns=Array.prototype.slice.call(arguments);fns.forEach((function(fn){lunr.Pipeline.warnIfFunctionNotRegistered(fn),this._stack.push(fn)}),this)},lunr.Pipeline.prototype.after=function(existingFn,newFn){lunr.Pipeline.warnIfFunctionNotRegistered(newFn);var pos=this._stack.indexOf(existingFn);if(-1==pos)throw new Error("Cannot find existingFn");pos+=1,this._stack.splice(pos,0,newFn)},lunr.Pipeline.prototype.before=function(existingFn,newFn){lunr.Pipeline.warnIfFunctionNotRegistered(newFn);var pos=this._stack.indexOf(existingFn);if(-1==pos)throw new Error("Cannot find existingFn");this._stack.splice(pos,0,newFn)},lunr.Pipeline.prototype.remove=function(fn){var pos=this._stack.indexOf(fn);-1!=pos&&this._stack.splice(pos,1)},lunr.Pipeline.prototype.run=function(tokens){for(var stackLength=this._stack.length,i=0;i<stackLength;i++){for(var fn=this._stack[i],memo=[],j=0;j<tokens.length;j++){var result=fn(tokens[j],j,tokens);if(null!=result&&""!==result)if(Array.isArray(result))for(var k=0;k<result.length;k++)memo.push(result[k]);else memo.push(result)}tokens=memo}return tokens},lunr.Pipeline.prototype.runString=function(str,metadata){var token=new lunr.Token(str,metadata);return this.run([token]).map((function(t){return t.toString()}))},lunr.Pipeline.prototype.reset=function(){this._stack=[]},lunr.Pipeline.prototype.toJSON=function(){return this._stack.map((function(fn){return lunr.Pipeline.warnIfFunctionNotRegistered(fn),fn.label}))},lunr.Vector=function(elements){this._magnitude=0,this.elements=elements||[]},lunr.Vector.prototype.positionForIndex=function(index){if(0==this.elements.length)return 0;for(var start=0,end=this.elements.length/2,sliceLength=end-start,pivotPoint=Math.floor(sliceLength/2),pivotIndex=this.elements[2*pivotPoint];sliceLength>1&&(pivotIndex<index&&(start=pivotPoint),pivotIndex>index&&(end=pivotPoint),pivotIndex!=index);)sliceLength=end-start,pivotPoint=start+Math.floor(sliceLength/2),pivotIndex=this.elements[2*pivotPoint];return pivotIndex==index||pivotIndex>index?2*pivotPoint:pivotIndex<index?2*(pivotPoint+1):void 0},lunr.Vector.prototype.insert=function(insertIdx,val){this.upsert(insertIdx,val,(function(){throw"duplicate index"}))},lunr.Vector.prototype.upsert=function(insertIdx,val,fn){this._magnitude=0;var position=this.positionForIndex(insertIdx);this.elements[position]==insertIdx?this.elements[position+1]=fn(this.elements[position+1],val):this.elements.splice(position,0,insertIdx,val)},lunr.Vector.prototype.magnitude=function(){if(this._magnitude)return this._magnitude;for(var sumOfSquares=0,elementsLength=this.elements.length,i=1;i<elementsLength;i+=2){var val=this.elements[i];sumOfSquares+=val*val}return this._magnitude=Math.sqrt(sumOfSquares)},lunr.Vector.prototype.dot=function(otherVector){for(var dotProduct=0,a=this.elements,b=otherVector.elements,aLen=a.length,bLen=b.length,aVal=0,bVal=0,i=0,j=0;i<aLen&&j<bLen;)(aVal=a[i])<(bVal=b[j])?i+=2:aVal>bVal?j+=2:aVal==bVal&&(dotProduct+=a[i+1]*b[j+1],i+=2,j+=2);return dotProduct},lunr.Vector.prototype.similarity=function(otherVector){return this.dot(otherVector)/this.magnitude()||0},lunr.Vector.prototype.toArray=function(){for(var output=new Array(this.elements.length/2),i=1,j=0;i<this.elements.length;i+=2,j++)output[j]=this.elements[i];return output},lunr.Vector.prototype.toJSON=function(){return this.elements},lunr.stemmer=(step2list={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},step3list={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},v="[aeiouy]",C="[^aeiou][^aeiouy]*",re_mgr0=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*"),re_mgr1=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*"),re_meq1=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$"),re_s_v=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy]"),re_1a=/^(.+?)(ss|i)es$/,re2_1a=/^(.+?)([^s])s$/,re_1b=/^(.+?)eed$/,re2_1b=/^(.+?)(ed|ing)$/,re_1b_2=/.$/,re2_1b_2=/(at|bl|iz)$/,re3_1b_2=new RegExp("([^aeiouylsz])\\1$"),re4_1b_2=new RegExp("^"+C+v+"[^aeiouwxy]$"),re_1c=/^(.+?[^aeiou])y$/,re_2=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,re_3=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,re_4=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,re2_4=/^(.+?)(s|t)(ion)$/,re_5=/^(.+?)e$/,re_5_1=/ll$/,re3_5=new RegExp("^"+C+v+"[^aeiouwxy]$"),porterStemmer=function(w){var stem,suffix,firstch,re,re2,re3,re4;if(w.length<3)return w;if("y"==(firstch=w.substr(0,1))&&(w=firstch.toUpperCase()+w.substr(1)),re2=re2_1a,(re=re_1a).test(w)?w=w.replace(re,"$1$2"):re2.test(w)&&(w=w.replace(re2,"$1$2")),re2=re2_1b,(re=re_1b).test(w)){var fp=re.exec(w);(re=re_mgr0).test(fp[1])&&(re=re_1b_2,w=w.replace(re,""))}else re2.test(w)&&(stem=(fp=re2.exec(w))[1],(re2=re_s_v).test(stem)&&(re3=re3_1b_2,re4=re4_1b_2,(re2=re2_1b_2).test(w=stem)?w+="e":re3.test(w)?(re=re_1b_2,w=w.replace(re,"")):re4.test(w)&&(w+="e")));return(re=re_1c).test(w)&&(w=(stem=(fp=re.exec(w))[1])+"i"),(re=re_2).test(w)&&(stem=(fp=re.exec(w))[1],suffix=fp[2],(re=re_mgr0).test(stem)&&(w=stem+step2list[suffix])),(re=re_3).test(w)&&(stem=(fp=re.exec(w))[1],suffix=fp[2],(re=re_mgr0).test(stem)&&(w=stem+step3list[suffix])),re2=re2_4,(re=re_4).test(w)?(stem=(fp=re.exec(w))[1],(re=re_mgr1).test(stem)&&(w=stem)):re2.test(w)&&(stem=(fp=re2.exec(w))[1]+fp[2],(re2=re_mgr1).test(stem)&&(w=stem)),(re=re_5).test(w)&&(stem=(fp=re.exec(w))[1],re2=re_meq1,re3=re3_5,((re=re_mgr1).test(stem)||re2.test(stem)&&!re3.test(stem))&&(w=stem)),re2=re_mgr1,(re=re_5_1).test(w)&&re2.test(w)&&(re=re_1b_2,w=w.replace(re,"")),"y"==firstch&&(w=firstch.toLowerCase()+w.substr(1)),w},function(token){return token.update(porterStemmer)}),lunr.Pipeline.registerFunction(lunr.stemmer,"stemmer"),lunr.generateStopWordFilter=function(stopWords){var words=stopWords.reduce((function(memo,stopWord){return memo[stopWord]=stopWord,memo}),{});return function(token){if(token&&words[token.toString()]!==token.toString())return token}},lunr.stopWordFilter=lunr.generateStopWordFilter(["a","able","about","across","after","all","almost","also","am","among","an","and","any","are","as","at","be","because","been","but","by","can","cannot","could","dear","did","do","does","either","else","ever","every","for","from","get","got","had","has","have","he","her","hers","him","his","how","however","i","if","in","into","is","it","its","just","least","let","like","likely","may","me","might","most","must","my","neither","no","nor","not","of","off","often","on","only","or","other","our","own","rather","said","say","says","she","should","since","so","some","than","that","the","their","them","then","there","these","they","this","tis","to","too","twas","us","wants","was","we","were","what","when","where","which","while","who","whom","why","will","with","would","yet","you","your"]),lunr.Pipeline.registerFunction(lunr.stopWordFilter,"stopWordFilter"),lunr.trimmer=function(token){return token.update((function(s){return s.replace(/^\W+/,"").replace(/\W+$/,"")}))},lunr.Pipeline.registerFunction(lunr.trimmer,"trimmer"),lunr.TokenSet=function(){this.final=!1,this.edges={},this.id=lunr.TokenSet._nextId,lunr.TokenSet._nextId+=1},lunr.TokenSet._nextId=1,lunr.TokenSet.fromArray=function(arr){for(var builder=new lunr.TokenSet.Builder,i=0,len=arr.length;i<len;i++)builder.insert(arr[i]);return builder.finish(),builder.root},lunr.TokenSet.fromClause=function(clause){return"editDistance"in clause?lunr.TokenSet.fromFuzzyString(clause.term,clause.editDistance):lunr.TokenSet.fromString(clause.term)},lunr.TokenSet.fromFuzzyString=function(str,editDistance){for(var root=new lunr.TokenSet,stack=[{node:root,editsRemaining:editDistance,str:str}];stack.length;){var frame=stack.pop();if(frame.str.length>0){var noEditNode,char=frame.str.charAt(0);char in frame.node.edges?noEditNode=frame.node.edges[char]:(noEditNode=new lunr.TokenSet,frame.node.edges[char]=noEditNode),1==frame.str.length&&(noEditNode.final=!0),stack.push({node:noEditNode,editsRemaining:frame.editsRemaining,str:frame.str.slice(1)})}if(0!=frame.editsRemaining){if("*"in frame.node.edges)var insertionNode=frame.node.edges["*"];else{insertionNode=new lunr.TokenSet;frame.node.edges["*"]=insertionNode}if(0==frame.str.length&&(insertionNode.final=!0),stack.push({node:insertionNode,editsRemaining:frame.editsRemaining-1,str:frame.str}),frame.str.length>1&&stack.push({node:frame.node,editsRemaining:frame.editsRemaining-1,str:frame.str.slice(1)}),1==frame.str.length&&(frame.node.final=!0),frame.str.length>=1){if("*"in frame.node.edges)var substitutionNode=frame.node.edges["*"];else{substitutionNode=new lunr.TokenSet;frame.node.edges["*"]=substitutionNode}1==frame.str.length&&(substitutionNode.final=!0),stack.push({node:substitutionNode,editsRemaining:frame.editsRemaining-1,str:frame.str.slice(1)})}if(frame.str.length>1){var transposeNode,charA=frame.str.charAt(0),charB=frame.str.charAt(1);charB in frame.node.edges?transposeNode=frame.node.edges[charB]:(transposeNode=new lunr.TokenSet,frame.node.edges[charB]=transposeNode),1==frame.str.length&&(transposeNode.final=!0),stack.push({node:transposeNode,editsRemaining:frame.editsRemaining-1,str:charA+frame.str.slice(2)})}}}return root},lunr.TokenSet.fromString=function(str){for(var node=new lunr.TokenSet,root=node,i=0,len=str.length;i<len;i++){var char=str[i],final=i==len-1;if("*"==char)node.edges[char]=node,node.final=final;else{var next=new lunr.TokenSet;next.final=final,node.edges[char]=next,node=next}}return root},lunr.TokenSet.prototype.toArray=function(){for(var words=[],stack=[{prefix:"",node:this}];stack.length;){var frame=stack.pop(),edges=Object.keys(frame.node.edges),len=edges.length;frame.node.final&&(frame.prefix.charAt(0),words.push(frame.prefix));for(var i=0;i<len;i++){var edge=edges[i];stack.push({prefix:frame.prefix.concat(edge),node:frame.node.edges[edge]})}}return words},lunr.TokenSet.prototype.toString=function(){if(this._str)return this._str;for(var str=this.final?"1":"0",labels=Object.keys(this.edges).sort(),len=labels.length,i=0;i<len;i++){var label=labels[i];str=str+label+this.edges[label].id}return str},lunr.TokenSet.prototype.intersect=function(b){for(var output=new lunr.TokenSet,frame=void 0,stack=[{qNode:b,output:output,node:this}];stack.length;){frame=stack.pop();for(var qEdges=Object.keys(frame.qNode.edges),qLen=qEdges.length,nEdges=Object.keys(frame.node.edges),nLen=nEdges.length,q=0;q<qLen;q++)for(var qEdge=qEdges[q],n=0;n<nLen;n++){var nEdge=nEdges[n];if(nEdge==qEdge||"*"==qEdge){var node=frame.node.edges[nEdge],qNode=frame.qNode.edges[qEdge],final=node.final&&qNode.final,next=void 0;nEdge in frame.output.edges?(next=frame.output.edges[nEdge]).final=next.final||final:((next=new lunr.TokenSet).final=final,frame.output.edges[nEdge]=next),stack.push({qNode:qNode,output:next,node:node})}}}return output},lunr.TokenSet.Builder=function(){this.previousWord="",this.root=new lunr.TokenSet,this.uncheckedNodes=[],this.minimizedNodes={}},lunr.TokenSet.Builder.prototype.insert=function(word){var node,commonPrefix=0;if(word<this.previousWord)throw new Error("Out of order word insertion");for(var i=0;i<word.length&&i<this.previousWord.length&&word[i]==this.previousWord[i];i++)commonPrefix++;this.minimize(commonPrefix),node=0==this.uncheckedNodes.length?this.root:this.uncheckedNodes[this.uncheckedNodes.length-1].child;for(i=commonPrefix;i<word.length;i++){var nextNode=new lunr.TokenSet,char=word[i];node.edges[char]=nextNode,this.uncheckedNodes.push({parent:node,char:char,child:nextNode}),node=nextNode}node.final=!0,this.previousWord=word},lunr.TokenSet.Builder.prototype.finish=function(){this.minimize(0)},lunr.TokenSet.Builder.prototype.minimize=function(downTo){for(var i=this.uncheckedNodes.length-1;i>=downTo;i--){var node=this.uncheckedNodes[i],childKey=node.child.toString();childKey in this.minimizedNodes?node.parent.edges[node.char]=this.minimizedNodes[childKey]:(node.child._str=childKey,this.minimizedNodes[childKey]=node.child),this.uncheckedNodes.pop()}},lunr.Index=function(attrs){this.invertedIndex=attrs.invertedIndex,this.fieldVectors=attrs.fieldVectors,this.tokenSet=attrs.tokenSet,this.fields=attrs.fields,this.pipeline=attrs.pipeline},lunr.Index.prototype.search=function(queryString){return this.query((function(query){new lunr.QueryParser(queryString,query).parse()}))},lunr.Index.prototype.query=function(fn){for(var query=new lunr.Query(this.fields),matchingFields=Object.create(null),queryVectors=Object.create(null),termFieldCache=Object.create(null),requiredMatches=Object.create(null),prohibitedMatches=Object.create(null),i=0;i<this.fields.length;i++)queryVectors[this.fields[i]]=new lunr.Vector;fn.call(query,query);for(i=0;i<query.clauses.length;i++){var clause=query.clauses[i],terms=null,clauseMatches=lunr.Set.empty;terms=clause.usePipeline?this.pipeline.runString(clause.term,{fields:clause.fields}):[clause.term];for(var m=0;m<terms.length;m++){var term=terms[m];clause.term=term;var termTokenSet=lunr.TokenSet.fromClause(clause),expandedTerms=this.tokenSet.intersect(termTokenSet).toArray();if(0===expandedTerms.length&&clause.presence===lunr.Query.presence.REQUIRED){for(var k=0;k<clause.fields.length;k++){requiredMatches[field=clause.fields[k]]=lunr.Set.empty}break}for(var j=0;j<expandedTerms.length;j++){var expandedTerm=expandedTerms[j],posting=this.invertedIndex[expandedTerm],termIndex=posting._index;for(k=0;k<clause.fields.length;k++){var fieldPosting=posting[field=clause.fields[k]],matchingDocumentRefs=Object.keys(fieldPosting),termField=expandedTerm+"/"+field,matchingDocumentsSet=new lunr.Set(matchingDocumentRefs);if(clause.presence==lunr.Query.presence.REQUIRED&&(clauseMatches=clauseMatches.union(matchingDocumentsSet),void 0===requiredMatches[field]&&(requiredMatches[field]=lunr.Set.complete)),clause.presence!=lunr.Query.presence.PROHIBITED){if(queryVectors[field].upsert(termIndex,clause.boost,(function(a,b){return a+b})),!termFieldCache[termField]){for(var l=0;l<matchingDocumentRefs.length;l++){var fieldMatch,matchingDocumentRef=matchingDocumentRefs[l],matchingFieldRef=new lunr.FieldRef(matchingDocumentRef,field),metadata=fieldPosting[matchingDocumentRef];void 0===(fieldMatch=matchingFields[matchingFieldRef])?matchingFields[matchingFieldRef]=new lunr.MatchData(expandedTerm,field,metadata):fieldMatch.add(expandedTerm,field,metadata)}termFieldCache[termField]=!0}}else void 0===prohibitedMatches[field]&&(prohibitedMatches[field]=lunr.Set.empty),prohibitedMatches[field]=prohibitedMatches[field].union(matchingDocumentsSet)}}}if(clause.presence===lunr.Query.presence.REQUIRED)for(k=0;k<clause.fields.length;k++){requiredMatches[field=clause.fields[k]]=requiredMatches[field].intersect(clauseMatches)}}var allRequiredMatches=lunr.Set.complete,allProhibitedMatches=lunr.Set.empty;for(i=0;i<this.fields.length;i++){var field;requiredMatches[field=this.fields[i]]&&(allRequiredMatches=allRequiredMatches.intersect(requiredMatches[field])),prohibitedMatches[field]&&(allProhibitedMatches=allProhibitedMatches.union(prohibitedMatches[field]))}var matchingFieldRefs=Object.keys(matchingFields),results=[],matches=Object.create(null);if(query.isNegated()){matchingFieldRefs=Object.keys(this.fieldVectors);for(i=0;i<matchingFieldRefs.length;i++){matchingFieldRef=matchingFieldRefs[i];var fieldRef=lunr.FieldRef.fromString(matchingFieldRef);matchingFields[matchingFieldRef]=new lunr.MatchData}}for(i=0;i<matchingFieldRefs.length;i++){var docRef=(fieldRef=lunr.FieldRef.fromString(matchingFieldRefs[i])).docRef;if(allRequiredMatches.contains(docRef)&&!allProhibitedMatches.contains(docRef)){var docMatch,fieldVector=this.fieldVectors[fieldRef],score=queryVectors[fieldRef.fieldName].similarity(fieldVector);if(void 0!==(docMatch=matches[docRef]))docMatch.score+=score,docMatch.matchData.combine(matchingFields[fieldRef]);else{var match={ref:docRef,score:score,matchData:matchingFields[fieldRef]};matches[docRef]=match,results.push(match)}}}return results.sort((function(a,b){return b.score-a.score}))},lunr.Index.prototype.toJSON=function(){var invertedIndex=Object.keys(this.invertedIndex).sort().map((function(term){return[term,this.invertedIndex[term]]}),this),fieldVectors=Object.keys(this.fieldVectors).map((function(ref){return[ref,this.fieldVectors[ref].toJSON()]}),this);return{version:lunr.version,fields:this.fields,fieldVectors:fieldVectors,invertedIndex:invertedIndex,pipeline:this.pipeline.toJSON()}},lunr.Index.load=function(serializedIndex){var attrs={},fieldVectors={},serializedVectors=serializedIndex.fieldVectors,invertedIndex=Object.create(null),serializedInvertedIndex=serializedIndex.invertedIndex,tokenSetBuilder=new lunr.TokenSet.Builder,pipeline=lunr.Pipeline.load(serializedIndex.pipeline);serializedIndex.version!=lunr.version&&lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '"+lunr.version+"' does not match serialized index '"+serializedIndex.version+"'");for(var i=0;i<serializedVectors.length;i++){var ref=(tuple=serializedVectors[i])[0],elements=tuple[1];fieldVectors[ref]=new lunr.Vector(elements)}for(i=0;i<serializedInvertedIndex.length;i++){var tuple,term=(tuple=serializedInvertedIndex[i])[0],posting=tuple[1];tokenSetBuilder.insert(term),invertedIndex[term]=posting}return tokenSetBuilder.finish(),attrs.fields=serializedIndex.fields,attrs.fieldVectors=fieldVectors,attrs.invertedIndex=invertedIndex,attrs.tokenSet=tokenSetBuilder.root,attrs.pipeline=pipeline,new lunr.Index(attrs)},lunr.Builder=function(){this._ref="id",this._fields=Object.create(null),this._documents=Object.create(null),this.invertedIndex=Object.create(null),this.fieldTermFrequencies={},this.fieldLengths={},this.tokenizer=lunr.tokenizer,this.pipeline=new lunr.Pipeline,this.searchPipeline=new lunr.Pipeline,this.documentCount=0,this._b=.75,this._k1=1.2,this.termIndex=0,this.metadataWhitelist=[]},lunr.Builder.prototype.ref=function(ref){this._ref=ref},lunr.Builder.prototype.field=function(fieldName,attributes){if(/\//.test(fieldName))throw new RangeError("Field '"+fieldName+"' contains illegal character '/'");this._fields[fieldName]=attributes||{}},lunr.Builder.prototype.b=function(number){this._b=number<0?0:number>1?1:number},lunr.Builder.prototype.k1=function(number){this._k1=number},lunr.Builder.prototype.add=function(doc,attributes){var docRef=doc[this._ref],fields=Object.keys(this._fields);this._documents[docRef]=attributes||{},this.documentCount+=1;for(var i=0;i<fields.length;i++){var fieldName=fields[i],extractor=this._fields[fieldName].extractor,field=extractor?extractor(doc):doc[fieldName],tokens=this.tokenizer(field,{fields:[fieldName]}),terms=this.pipeline.run(tokens),fieldRef=new lunr.FieldRef(docRef,fieldName),fieldTerms=Object.create(null);this.fieldTermFrequencies[fieldRef]=fieldTerms,this.fieldLengths[fieldRef]=0,this.fieldLengths[fieldRef]+=terms.length;for(var j=0;j<terms.length;j++){var term=terms[j];if(null==fieldTerms[term]&&(fieldTerms[term]=0),fieldTerms[term]+=1,null==this.invertedIndex[term]){var posting=Object.create(null);posting._index=this.termIndex,this.termIndex+=1;for(var k=0;k<fields.length;k++)posting[fields[k]]=Object.create(null);this.invertedIndex[term]=posting}null==this.invertedIndex[term][fieldName][docRef]&&(this.invertedIndex[term][fieldName][docRef]=Object.create(null));for(var l=0;l<this.metadataWhitelist.length;l++){var metadataKey=this.metadataWhitelist[l],metadata=term.metadata[metadataKey];null==this.invertedIndex[term][fieldName][docRef][metadataKey]&&(this.invertedIndex[term][fieldName][docRef][metadataKey]=[]),this.invertedIndex[term][fieldName][docRef][metadataKey].push(metadata)}}}},lunr.Builder.prototype.calculateAverageFieldLengths=function(){for(var fieldRefs=Object.keys(this.fieldLengths),numberOfFields=fieldRefs.length,accumulator={},documentsWithField={},i=0;i<numberOfFields;i++){var fieldRef=lunr.FieldRef.fromString(fieldRefs[i]),field=fieldRef.fieldName;documentsWithField[field]||(documentsWithField[field]=0),documentsWithField[field]+=1,accumulator[field]||(accumulator[field]=0),accumulator[field]+=this.fieldLengths[fieldRef]}var fields=Object.keys(this._fields);for(i=0;i<fields.length;i++){var fieldName=fields[i];accumulator[fieldName]=accumulator[fieldName]/documentsWithField[fieldName]}this.averageFieldLength=accumulator},lunr.Builder.prototype.createFieldVectors=function(){for(var fieldVectors={},fieldRefs=Object.keys(this.fieldTermFrequencies),fieldRefsLength=fieldRefs.length,termIdfCache=Object.create(null),i=0;i<fieldRefsLength;i++){for(var fieldRef=lunr.FieldRef.fromString(fieldRefs[i]),fieldName=fieldRef.fieldName,fieldLength=this.fieldLengths[fieldRef],fieldVector=new lunr.Vector,termFrequencies=this.fieldTermFrequencies[fieldRef],terms=Object.keys(termFrequencies),termsLength=terms.length,fieldBoost=this._fields[fieldName].boost||1,docBoost=this._documents[fieldRef.docRef].boost||1,j=0;j<termsLength;j++){var idf,score,scoreWithPrecision,term=terms[j],tf=termFrequencies[term],termIndex=this.invertedIndex[term]._index;void 0===termIdfCache[term]?(idf=lunr.idf(this.invertedIndex[term],this.documentCount),termIdfCache[term]=idf):idf=termIdfCache[term],score=idf*((this._k1+1)*tf)/(this._k1*(1-this._b+this._b*(fieldLength/this.averageFieldLength[fieldName]))+tf),score*=fieldBoost,score*=docBoost,scoreWithPrecision=Math.round(1e3*score)/1e3,fieldVector.insert(termIndex,scoreWithPrecision)}fieldVectors[fieldRef]=fieldVector}this.fieldVectors=fieldVectors},lunr.Builder.prototype.createTokenSet=function(){this.tokenSet=lunr.TokenSet.fromArray(Object.keys(this.invertedIndex).sort())},lunr.Builder.prototype.build=function(){return this.calculateAverageFieldLengths(),this.createFieldVectors(),this.createTokenSet(),new lunr.Index({invertedIndex:this.invertedIndex,fieldVectors:this.fieldVectors,tokenSet:this.tokenSet,fields:Object.keys(this._fields),pipeline:this.searchPipeline})},lunr.Builder.prototype.use=function(fn){var args=Array.prototype.slice.call(arguments,1);args.unshift(this),fn.apply(this,args)},lunr.MatchData=function(term,field,metadata){for(var clonedMetadata=Object.create(null),metadataKeys=Object.keys(metadata||{}),i=0;i<metadataKeys.length;i++){var key=metadataKeys[i];clonedMetadata[key]=metadata[key].slice()}this.metadata=Object.create(null),void 0!==term&&(this.metadata[term]=Object.create(null),this.metadata[term][field]=clonedMetadata)},lunr.MatchData.prototype.combine=function(otherMatchData){for(var terms=Object.keys(otherMatchData.metadata),i=0;i<terms.length;i++){var term=terms[i],fields=Object.keys(otherMatchData.metadata[term]);null==this.metadata[term]&&(this.metadata[term]=Object.create(null));for(var j=0;j<fields.length;j++){var field=fields[j],keys=Object.keys(otherMatchData.metadata[term][field]);null==this.metadata[term][field]&&(this.metadata[term][field]=Object.create(null));for(var k=0;k<keys.length;k++){var key=keys[k];null==this.metadata[term][field][key]?this.metadata[term][field][key]=otherMatchData.metadata[term][field][key]:this.metadata[term][field][key]=this.metadata[term][field][key].concat(otherMatchData.metadata[term][field][key])}}}},lunr.MatchData.prototype.add=function(term,field,metadata){if(!(term in this.metadata))return this.metadata[term]=Object.create(null),void(this.metadata[term][field]=metadata);if(field in this.metadata[term])for(var metadataKeys=Object.keys(metadata),i=0;i<metadataKeys.length;i++){var key=metadataKeys[i];key in this.metadata[term][field]?this.metadata[term][field][key]=this.metadata[term][field][key].concat(metadata[key]):this.metadata[term][field][key]=metadata[key]}else this.metadata[term][field]=metadata},lunr.Query=function(allFields){this.clauses=[],this.allFields=allFields},lunr.Query.wildcard=new String("*"),lunr.Query.wildcard.NONE=0,lunr.Query.wildcard.LEADING=1,lunr.Query.wildcard.TRAILING=2,lunr.Query.presence={OPTIONAL:1,REQUIRED:2,PROHIBITED:3},lunr.Query.prototype.clause=function(clause){return"fields"in clause||(clause.fields=this.allFields),"boost"in clause||(clause.boost=1),"usePipeline"in clause||(clause.usePipeline=!0),"wildcard"in clause||(clause.wildcard=lunr.Query.wildcard.NONE),clause.wildcard&lunr.Query.wildcard.LEADING&&clause.term.charAt(0)!=lunr.Query.wildcard&&(clause.term="*"+clause.term),clause.wildcard&lunr.Query.wildcard.TRAILING&&clause.term.slice(-1)!=lunr.Query.wildcard&&(clause.term=clause.term+"*"),"presence"in clause||(clause.presence=lunr.Query.presence.OPTIONAL),this.clauses.push(clause),this},lunr.Query.prototype.isNegated=function(){for(var i=0;i<this.clauses.length;i++)if(this.clauses[i].presence!=lunr.Query.presence.PROHIBITED)return!1;return!0},lunr.Query.prototype.term=function(term,options){if(Array.isArray(term))return term.forEach((function(t){this.term(t,lunr.utils.clone(options))}),this),this;var clause=options||{};return clause.term=term.toString(),this.clause(clause),this},lunr.QueryParseError=function(message,start,end){this.name="QueryParseError",this.message=message,this.start=start,this.end=end},lunr.QueryParseError.prototype=new Error,lunr.QueryLexer=function(str){this.lexemes=[],this.str=str,this.length=str.length,this.pos=0,this.start=0,this.escapeCharPositions=[]},lunr.QueryLexer.prototype.run=function(){for(var state=lunr.QueryLexer.lexText;state;)state=state(this)},lunr.QueryLexer.prototype.sliceString=function(){for(var subSlices=[],sliceStart=this.start,sliceEnd=this.pos,i=0;i<this.escapeCharPositions.length;i++)sliceEnd=this.escapeCharPositions[i],subSlices.push(this.str.slice(sliceStart,sliceEnd)),sliceStart=sliceEnd+1;return subSlices.push(this.str.slice(sliceStart,this.pos)),this.escapeCharPositions.length=0,subSlices.join("")},lunr.QueryLexer.prototype.emit=function(type){this.lexemes.push({type:type,str:this.sliceString(),start:this.start,end:this.pos}),this.start=this.pos},lunr.QueryLexer.prototype.escapeCharacter=function(){this.escapeCharPositions.push(this.pos-1),this.pos+=1},lunr.QueryLexer.prototype.next=function(){if(this.pos>=this.length)return lunr.QueryLexer.EOS;var char=this.str.charAt(this.pos);return this.pos+=1,char},lunr.QueryLexer.prototype.width=function(){return this.pos-this.start},lunr.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},lunr.QueryLexer.prototype.backup=function(){this.pos-=1},lunr.QueryLexer.prototype.acceptDigitRun=function(){var char,charCode;do{charCode=(char=this.next()).charCodeAt(0)}while(charCode>47&&charCode<58);char!=lunr.QueryLexer.EOS&&this.backup()},lunr.QueryLexer.prototype.more=function(){return this.pos<this.length},lunr.QueryLexer.EOS="EOS",lunr.QueryLexer.FIELD="FIELD",lunr.QueryLexer.TERM="TERM",lunr.QueryLexer.EDIT_DISTANCE="EDIT_DISTANCE",lunr.QueryLexer.BOOST="BOOST",lunr.QueryLexer.PRESENCE="PRESENCE",lunr.QueryLexer.lexField=function(lexer){return lexer.backup(),lexer.emit(lunr.QueryLexer.FIELD),lexer.ignore(),lunr.QueryLexer.lexText},lunr.QueryLexer.lexTerm=function(lexer){if(lexer.width()>1&&(lexer.backup(),lexer.emit(lunr.QueryLexer.TERM)),lexer.ignore(),lexer.more())return lunr.QueryLexer.lexText},lunr.QueryLexer.lexEditDistance=function(lexer){return lexer.ignore(),lexer.acceptDigitRun(),lexer.emit(lunr.QueryLexer.EDIT_DISTANCE),lunr.QueryLexer.lexText},lunr.QueryLexer.lexBoost=function(lexer){return lexer.ignore(),lexer.acceptDigitRun(),lexer.emit(lunr.QueryLexer.BOOST),lunr.QueryLexer.lexText},lunr.QueryLexer.lexEOS=function(lexer){lexer.width()>0&&lexer.emit(lunr.QueryLexer.TERM)},lunr.QueryLexer.termSeparator=lunr.tokenizer.separator,lunr.QueryLexer.lexText=function(lexer){for(;;){var char=lexer.next();if(char==lunr.QueryLexer.EOS)return lunr.QueryLexer.lexEOS;if(92!=char.charCodeAt(0)){if(":"==char)return lunr.QueryLexer.lexField;if("~"==char)return lexer.backup(),lexer.width()>0&&lexer.emit(lunr.QueryLexer.TERM),lunr.QueryLexer.lexEditDistance;if("^"==char)return lexer.backup(),lexer.width()>0&&lexer.emit(lunr.QueryLexer.TERM),lunr.QueryLexer.lexBoost;if("+"==char&&1===lexer.width())return lexer.emit(lunr.QueryLexer.PRESENCE),lunr.QueryLexer.lexText;if("-"==char&&1===lexer.width())return lexer.emit(lunr.QueryLexer.PRESENCE),lunr.QueryLexer.lexText;if(char.match(lunr.QueryLexer.termSeparator))return lunr.QueryLexer.lexTerm}else lexer.escapeCharacter()}},lunr.QueryParser=function(str,query){this.lexer=new lunr.QueryLexer(str),this.query=query,this.currentClause={},this.lexemeIdx=0},lunr.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var state=lunr.QueryParser.parseClause;state;)state=state(this);return this.query},lunr.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},lunr.QueryParser.prototype.consumeLexeme=function(){var lexeme=this.peekLexeme();return this.lexemeIdx+=1,lexeme},lunr.QueryParser.prototype.nextClause=function(){var completedClause=this.currentClause;this.query.clause(completedClause),this.currentClause={}},lunr.QueryParser.parseClause=function(parser){var lexeme=parser.peekLexeme();if(null!=lexeme)switch(lexeme.type){case lunr.QueryLexer.PRESENCE:return lunr.QueryParser.parsePresence;case lunr.QueryLexer.FIELD:return lunr.QueryParser.parseField;case lunr.QueryLexer.TERM:return lunr.QueryParser.parseTerm;default:var errorMessage="expected either a field or a term, found "+lexeme.type;throw lexeme.str.length>=1&&(errorMessage+=" with value '"+lexeme.str+"'"),new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}},lunr.QueryParser.parsePresence=function(parser){var lexeme=parser.consumeLexeme();if(null!=lexeme){switch(lexeme.str){case"-":parser.currentClause.presence=lunr.Query.presence.PROHIBITED;break;case"+":parser.currentClause.presence=lunr.Query.presence.REQUIRED;break;default:var errorMessage="unrecognised presence operator'"+lexeme.str+"'";throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}var nextLexeme=parser.peekLexeme();if(null==nextLexeme){errorMessage="expecting term or field, found nothing";throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}switch(nextLexeme.type){case lunr.QueryLexer.FIELD:return lunr.QueryParser.parseField;case lunr.QueryLexer.TERM:return lunr.QueryParser.parseTerm;default:errorMessage="expecting term or field, found '"+nextLexeme.type+"'";throw new lunr.QueryParseError(errorMessage,nextLexeme.start,nextLexeme.end)}}},lunr.QueryParser.parseField=function(parser){var lexeme=parser.consumeLexeme();if(null!=lexeme){if(-1==parser.query.allFields.indexOf(lexeme.str)){var possibleFields=parser.query.allFields.map((function(f){return"'"+f+"'"})).join(", "),errorMessage="unrecognised field '"+lexeme.str+"', possible fields: "+possibleFields;throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}parser.currentClause.fields=[lexeme.str];var nextLexeme=parser.peekLexeme();if(null==nextLexeme){errorMessage="expecting term, found nothing";throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}if(nextLexeme.type===lunr.QueryLexer.TERM)return lunr.QueryParser.parseTerm;errorMessage="expecting term, found '"+nextLexeme.type+"'";throw new lunr.QueryParseError(errorMessage,nextLexeme.start,nextLexeme.end)}},lunr.QueryParser.parseTerm=function(parser){var lexeme=parser.consumeLexeme();if(null!=lexeme){parser.currentClause.term=lexeme.str.toLowerCase(),-1!=lexeme.str.indexOf("*")&&(parser.currentClause.usePipeline=!1);var nextLexeme=parser.peekLexeme();if(null!=nextLexeme)switch(nextLexeme.type){case lunr.QueryLexer.TERM:return parser.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return parser.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return parser.nextClause(),lunr.QueryParser.parsePresence;default:var errorMessage="Unexpected lexeme type '"+nextLexeme.type+"'";throw new lunr.QueryParseError(errorMessage,nextLexeme.start,nextLexeme.end)}else parser.nextClause()}},lunr.QueryParser.parseEditDistance=function(parser){var lexeme=parser.consumeLexeme();if(null!=lexeme){var editDistance=parseInt(lexeme.str,10);if(isNaN(editDistance)){var errorMessage="edit distance must be numeric";throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}parser.currentClause.editDistance=editDistance;var nextLexeme=parser.peekLexeme();if(null!=nextLexeme)switch(nextLexeme.type){case lunr.QueryLexer.TERM:return parser.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return parser.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return parser.nextClause(),lunr.QueryParser.parsePresence;default:errorMessage="Unexpected lexeme type '"+nextLexeme.type+"'";throw new lunr.QueryParseError(errorMessage,nextLexeme.start,nextLexeme.end)}else parser.nextClause()}},lunr.QueryParser.parseBoost=function(parser){var lexeme=parser.consumeLexeme();if(null!=lexeme){var boost=parseInt(lexeme.str,10);if(isNaN(boost)){var errorMessage="boost must be numeric";throw new lunr.QueryParseError(errorMessage,lexeme.start,lexeme.end)}parser.currentClause.boost=boost;var nextLexeme=parser.peekLexeme();if(null!=nextLexeme)switch(nextLexeme.type){case lunr.QueryLexer.TERM:return parser.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return parser.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return parser.nextClause(),lunr.QueryParser.parsePresence;default:errorMessage="Unexpected lexeme type '"+nextLexeme.type+"'";throw new lunr.QueryParseError(errorMessage,nextLexeme.start,nextLexeme.end)}else parser.nextClause()}},root=this,factory=function(){return lunr},"function"==typeof define&&define.amd?define("tool_componentlibrary/lunr",factory):"object"==typeof exports?module.exports=factory():root.lunr=factory()}(); define("tool_componentlibrary/mustache",["exports","tool_componentlibrary/selectors","core/ajax","core/config","core/templates","core/log","core/notification"],(function(_exports,_selectors,_ajax,_config,_templates,_log,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Render mustache template examples within the component library. * * @module tool_componentlibrary/mustache * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.mustache=void 0,_selectors=_interopRequireDefault(_selectors),_ajax=_interopRequireDefault(_ajax),_config=_interopRequireDefault(_config),_templates=_interopRequireDefault(_templates),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification);const loadTemplate=container=>{const sourcecontainer=container.querySelector(_selectors.default.mustachesource),contextcontainer=container.querySelector(_selectors.default.mustachecontext),templateName=container.dataset.template;let context=container.querySelector(_selectors.default.mustacherawcontext).textContent;const parts=templateName.split("/"),request={methodname:"core_output_load_template",args:{component:parts.shift(),template:parts.join("/"),themename:_config.default.theme,includecomments:!0}};_ajax.default.call([request])[0].done((source=>{if(sourcecontainer.textContent=source,!context){const example=source.match(/Example context \(json\):([\s\S]+?)(}})/);context=example[1];const precontainer=document.createElement("pre");precontainer.innerHTML=JSON.stringify(JSON.parse(context),null,4),contextcontainer.parentNode.appendChild(precontainer),contextcontainer.classList.add("d-none")}(async(container,templateName,context)=>{try{context=JSON.parse(context)}catch(e){_log.default.debug("Could not parse json example context for template."),_log.default.debug(e)}const{html:html,js:js}=await _templates.default.renderForPromise(templateName,context),rendercontainer=container.querySelector(_selectors.default.mustacherendered);await _templates.default.replaceNodeContents(rendercontainer,html,js)})(container,templateName,context)})).fail(_notification.default.exception)};_exports.mustache=()=>{document.querySelectorAll(_selectors.default.mustachecode).forEach((container=>{loadTemplate(container)}))}})); define("tool_componentlibrary/search",["exports","tool_componentlibrary/lunr","tool_componentlibrary/selectors","core/log","core/notification","core/key_codes"],(function(_exports,_lunr,_selectors,_log,_notification,_key_codes){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Interface to the Lunr search engines. * * @module tool_componentlibrary/search * @copyright 2021 Bas Brands <bas@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.search=void 0,_lunr=_interopRequireDefault(_lunr),_selectors=_interopRequireDefault(_selectors),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification);let lunrIndex=null,pagesIndex=null;const initLunr=jsonFile=>{(async jsonFile=>{const response=await fetch(jsonFile);return response.ok||_log.default.debug("Error getting Hugo index file: ".concat(response.status)),await response.json()})(jsonFile).then((jsondata=>(pagesIndex=jsondata,lunrIndex=(0,_lunr.default)((function(){this.ref("uri"),this.field("title",{boost:10}),this.field("content"),this.field("tags",{boost:5}),jsondata.forEach((p=>{this.add(p)}))})),null))).catch(_notification.default.exception)},searchIndex=query=>lunrIndex.search(query+" "+query+"*").map((result=>pagesIndex.filter((page=>page.uri===result.ref))[0])),renderResults=results=>{const dropdownMenu=document.querySelector(_selectors.default.dropdownmenu);if(!results.length)return void dropdownMenu.classList.remove("show");dropdownMenu.innerHTML="";const baseUrl=M.cfg.wwwroot+"/admin/tool/componentlibrary/docspage.php";results.slice(0,10).forEach((function(result){const link=document.createElement("a"),chapter=result.uri.split("/")[1];link.appendChild(document.createTextNode("".concat(chapter," > ").concat(result.title))),link.classList.add("dropdown-item"),link.href=baseUrl+result.uri,dropdownMenu.appendChild(link)})),dropdownMenu.classList.add("show")};_exports.search=jsonFile=>{initLunr(jsonFile),(()=>{const searchInput=document.querySelector(_selectors.default.searchinput);searchInput.addEventListener("keyup",(e=>{const query=e.currentTarget.value;query.length<2?document.querySelector(_selectors.default.dropdownmenu).classList.remove("show"):renderResults(searchIndex(query))})),searchInput.addEventListener("keydown",(e=>{e.keyCode===_key_codes.enter&&e.preventDefault(),e.keyCode===_key_codes.escape&&(searchInput.value="")}))})()}})); define("tool_componentlibrary/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={clipboardbutton:".btn-clipboard",clipboardcontent:"figure.highlight, div.highlight",searchinput:'[data-region="docsearch"] input',searchsubmit:'[data-region="docsearch"] .btn-submit',dropdownmenu:'[data-region="docsearch"] .dropdown-menu',componentlibrary:'[data-region="componentlibrary"]',jscode:'[data-action="runjs"]',mustachecode:'[data-region="mustachecode"]',mustacherawcontext:'[data-region="rawcontext"]',mustacherendered:'[data-region="mustacherendered"]',mustachesource:'[data-region="mustachesource"]',mustachecontext:'[data-region="mustachecontext"]'},_exports.default})); /** * Module to add categories. * * @module tool_dataprivacy/add_category * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/add_category",["jquery","core/str","core/ajax","core/notification","core/modal_factory","core/modal_events","core/fragment","core_form/changechecker"],(function($,Str,Ajax,Notification,ModalFactory,ModalEvents,Fragment,FormChangeChecker){var SELECTORS_CATEGORY_LINK='[data-add-element="category"]',AddCategory=function(contextId){this.contextId=contextId;this.strings=Str.get_strings([{key:"addcategory",component:"tool_dataprivacy"},{key:"save",component:"admin"}]),this.registerEventListeners()};return AddCategory.prototype.contextId=0,AddCategory.prototype.strings=0,AddCategory.prototype.registerEventListeners=function(){var trigger=$(SELECTORS_CATEGORY_LINK);trigger.on("click",function(){return this.strings.then(function(strings){ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:strings[0],body:""},trigger).done(function(modal){this.setupFormModal(modal,strings[1])}.bind(this))}.bind(this)).fail(Notification.exception)}.bind(this))},AddCategory.prototype.getBody=function(formdata){var params=null;return void 0!==formdata&&(params={jsonformdata:JSON.stringify(formdata)}),Fragment.loadFragment("tool_dataprivacy","addcategory_form",this.contextId,params)},AddCategory.prototype.setupFormModal=function(modal,saveText){modal.setLarge(),modal.setSaveButtonText(saveText),modal.getRoot().on(ModalEvents.hidden,this.destroy.bind(this)),modal.setBody(this.getBody()),modal.getRoot().on(ModalEvents.save,this.submitForm.bind(this)),modal.getRoot().on("submit","form",this.submitFormAjax.bind(this)),this.modal=modal,modal.show()},AddCategory.prototype.submitForm=function(e){e.preventDefault(),this.modal.getRoot().find("form").submit()},AddCategory.prototype.submitFormAjax=function(e){e.preventDefault();var formData=this.modal.getRoot().find("form").serialize();Ajax.call([{methodname:"tool_dataprivacy_create_category_form",args:{jsonformdata:JSON.stringify(formData)},done:function(data){data.validationerrors?this.modal.setBody(this.getBody(formData)):this.close()}.bind(this),fail:Notification.exception}])},AddCategory.prototype.close=function(){this.destroy(),document.location.reload()},AddCategory.prototype.destroy=function(){FormChangeChecker.resetAllFormDirtyStates(),this.modal.destroy()},AddCategory.prototype.removeListeners=function(){$(SELECTORS_CATEGORY_LINK).off("click")},{getInstance:function(contextId){return new AddCategory(contextId)}}})); /** * Module to add purposes. * * @module tool_dataprivacy/add_purpose * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/add_purpose",["jquery","core/str","core/ajax","core/notification","core/modal_factory","core/modal_events","core/fragment","core_form/changechecker"],(function($,Str,Ajax,Notification,ModalFactory,ModalEvents,Fragment,FormChangeChecker){var SELECTORS_PURPOSE_LINK='[data-add-element="purpose"]',AddPurpose=function(contextId){this.contextId=contextId;this.strings=Str.get_strings([{key:"addpurpose",component:"tool_dataprivacy"},{key:"save",component:"admin"}]),this.registerEventListeners()};return AddPurpose.prototype.contextId=0,AddPurpose.prototype.strings=0,AddPurpose.prototype.registerEventListeners=function(){var trigger=$(SELECTORS_PURPOSE_LINK);trigger.on("click",function(){return this.strings.then(function(strings){ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:strings[0],body:""},trigger).done(function(modal){this.setupFormModal(modal,strings[1])}.bind(this))}.bind(this)).fail(Notification.exception)}.bind(this))},AddPurpose.prototype.getBody=function(formdata){var params=null;return void 0!==formdata&&(params={jsonformdata:JSON.stringify(formdata)}),Fragment.loadFragment("tool_dataprivacy","addpurpose_form",this.contextId,params)},AddPurpose.prototype.setupFormModal=function(modal,saveText){modal.setLarge(),modal.setSaveButtonText(saveText),modal.getRoot().on(ModalEvents.hidden,this.destroy.bind(this)),modal.setBody(this.getBody()),modal.getRoot().on(ModalEvents.save,this.submitForm.bind(this)),modal.getRoot().on("submit","form",this.submitFormAjax.bind(this)),this.modal=modal,modal.show()},AddPurpose.prototype.submitForm=function(e){e.preventDefault(),this.modal.getRoot().find("form").submit()},AddPurpose.prototype.submitFormAjax=function(e){e.preventDefault();var formData=this.modal.getRoot().find("form").serialize();Ajax.call([{methodname:"tool_dataprivacy_create_purpose_form",args:{jsonformdata:JSON.stringify(formData)},done:function(data){data.validationerrors?this.modal.setBody(this.getBody(formData)):this.close()}.bind(this),fail:Notification.exception}])},AddPurpose.prototype.close=function(){this.destroy(),document.location.reload()},AddPurpose.prototype.destroy=function(){FormChangeChecker.resetAllFormDirtyStates(),this.modal.destroy()},AddPurpose.prototype.removeListeners=function(){$(SELECTORS_PURPOSE_LINK).off("click")},{getInstance:function(contextId){return new AddPurpose(contextId)}}})); /** * AMD module for categories actions. * * @module tool_dataprivacy/categoriesactions * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/categoriesactions",["jquery","core/ajax","core/notification","core/str","core/modal_factory","core/modal_events"],(function($,Ajax,Notification,Str,ModalFactory,ModalEvents){var ACTIONS_DELETE='[data-action="deletecategory"]',CategoriesActions=function(){this.registerEvents()};return CategoriesActions.prototype.registerEvents=function(){$(ACTIONS_DELETE).click((function(e){e.preventDefault();var id=$(this).data("id"),stringkeys=[{key:"deletecategory",component:"tool_dataprivacy"},{key:"deletecategorytext",component:"tool_dataprivacy",param:$(this).data("name")},{key:"delete"}];Str.get_strings(stringkeys).then((function(langStrings){var title=langStrings[0],confirmMessage=langStrings[1],buttonText=langStrings[2];return ModalFactory.create({title:title,body:confirmMessage,type:ModalFactory.types.SAVE_CANCEL}).then((function(modal){return modal.setSaveButtonText(buttonText),modal.getRoot().on(ModalEvents.save,(function(){var request={methodname:"tool_dataprivacy_delete_category",args:{id:id}};Ajax.call([request])[0].done((function(data){data.result?$('tr[data-categoryid="'+id+'"]').remove():Notification.addNotification({message:data.warnings[0].message,type:"error"})})).fail(Notification.exception)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal}))})).done((function(modal){modal.show()})).fail(Notification.exception)}))},{init:function(){return new CategoriesActions}}})); /** * Request actions. * * @module tool_dataprivacy/data_deletion * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/data_deletion",["jquery","core/ajax","core/notification","core/str","core/modal_factory","core/modal_events"],(function($,Ajax,Notification,Str,ModalFactory,ModalEvents){var ACTIONS_MARK_FOR_DELETION='[data-action="markfordeletion"]',ACTIONS_SELECT_ALL='[data-action="selectall"]',SELECTORS_SELECTCONTEXT=".selectcontext",DataDeletionActions=function(){this.registerEvents()};return DataDeletionActions.prototype.registerEvents=function(){$(ACTIONS_MARK_FOR_DELETION).click((function(e){e.preventDefault();var ids,keys,wsfunction,modalTitle,selectedIds=[];$(SELECTORS_SELECTCONTEXT).each((function(){var checkbox=$(this);checkbox.is(":checked")&&selectedIds.push(checkbox.val())})),ids=selectedIds,keys=[{key:"confirm",component:"moodle"},{key:"confirmcontextdeletion",component:"tool_dataprivacy"}],wsfunction="tool_dataprivacy_confirm_contexts_for_deletion",modalTitle="",Str.get_strings(keys).then((function(langStrings){modalTitle=langStrings[0];var confirmMessage=langStrings[1];return ModalFactory.create({title:modalTitle,body:confirmMessage,type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){return modal.setSaveButtonText(modalTitle),modal.getRoot().on(ModalEvents.save,(function(){var request={methodname:wsfunction,args:{ids:ids}};Ajax.call([request])[0].done((function(data){data.result?window.location.reload():Notification.addNotification({message:data.warnings[0].message,type:"error"})})).fail(Notification.exception)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal})).done((function(modal){modal.show()})).fail(Notification.exception)})),$(ACTIONS_SELECT_ALL).change((function(e){e.preventDefault(),$(this).is(":checked")?$(SELECTORS_SELECTCONTEXT).attr("checked","checked"):$(SELECTORS_SELECTCONTEXT).removeAttr("checked")}))},DataDeletionActions})); /** * Request actions. * * @module tool_dataprivacy/data_registry * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/data_registry",["jquery","core/str","core/ajax","core/notification","core/templates","core/modal_factory","core/modal_events","core/fragment","tool_dataprivacy/add_purpose","tool_dataprivacy/add_category"],(function($,Str,Ajax,Notification,Templates,ModalFactory,ModalEvents,Fragment,AddPurpose,AddCategory){var SELECTORS_TREE_NODES="[data-context-tree-node=1]",SELECTORS_FORM_CONTAINER="#context-form-container",DataRegistry=function(systemContextId,initContextLevel,initContextId){this.systemContextId=systemContextId,this.currentContextLevel=initContextLevel,this.currentContextId=initContextId,this.init()};return DataRegistry.prototype.systemContextId=0,DataRegistry.prototype.currentContextLevel=0,DataRegistry.prototype.currentContextId=0,DataRegistry.prototype.addpurpose=null,DataRegistry.prototype.addcategory=null,DataRegistry.prototype.init=function(){this.addpurpose=AddPurpose.getInstance(this.systemContextId),this.addcategory=AddCategory.getInstance(this.systemContextId);this.strings=Str.get_strings([{key:"changessaved",component:"moodle"},{key:"contextpurposecategorysaved",component:"tool_dataprivacy"},{key:"noblockstoload",component:"tool_dataprivacy"},{key:"noactivitiestoload",component:"tool_dataprivacy"},{key:"nocoursestoload",component:"tool_dataprivacy"}]),this.registerEventListeners(),this.currentContextId?this.loadForm("context_form",[this.currentContextId],this.submitContextFormAjax.bind(this)):this.loadForm("contextlevel_form",[this.currentContextLevel],this.submitContextLevelFormAjax.bind(this))},DataRegistry.prototype.registerEventListeners=function(){$(SELECTORS_TREE_NODES).on("click",function(ev){ev.preventDefault();var trigger=$(ev.currentTarget);$(SELECTORS_TREE_NODES).removeClass("active"),trigger.addClass("active");var contextLevel=trigger.data("contextlevel"),contextId=trigger.data("contextid");if(contextLevel)window.history.pushState({},null,"?contextlevel="+contextLevel),this.addpurpose.removeListeners(),this.addcategory.removeListeners(),this.currentContextLevel=contextLevel,this.loadForm("contextlevel_form",[this.currentContextLevel],this.submitContextLevelFormAjax.bind(this));else if(contextId)window.history.pushState({},null,"?contextid="+contextId),this.addpurpose.removeListeners(),this.addcategory.removeListeners(),this.currentContextId=contextId,this.loadForm("context_form",[this.currentContextId],this.submitContextFormAjax.bind(this));else{var expandContextId=trigger.data("expandcontextid"),expandElement=trigger.data("expandelement"),expanded=trigger.data("expanded");expandElement&&(expanded?this.collapse(trigger):!trigger.data("loaded")&&expandContextId&&expandElement?(trigger.find("> i").removeClass("fa-plus"),trigger.find("> i").addClass("fa-circle-o-notch fa-spin"),this.loadExtra(trigger,expandContextId,expandElement)):this.expand(trigger))}}.bind(this))},DataRegistry.prototype.removeListeners=function(){$(SELECTORS_TREE_NODES).off("click")},DataRegistry.prototype.loadForm=function(fragmentName,fragmentArgs,formSubmitCallback){this.clearForm(),Fragment.loadFragment("tool_dataprivacy",fragmentName,this.systemContextId,fragmentArgs).done(function(html,js){$(SELECTORS_FORM_CONTAINER).html(html),Templates.runTemplateJS(js),this.addpurpose.registerEventListeners(),this.addcategory.registerEventListeners(),$(SELECTORS_FORM_CONTAINER).on("submit","form",formSubmitCallback)}.bind(this)).fail(Notification.exception)},DataRegistry.prototype.clearForm=function(){$(SELECTORS_FORM_CONTAINER).off("submit","form")},DataRegistry.prototype.submitForm=function(e){e.preventDefault(),$(SELECTORS_FORM_CONTAINER).find("form").submit()},DataRegistry.prototype.submitContextLevelFormAjax=function(e){this.submitFormAjax(e,"tool_dataprivacy_set_contextlevel_form")},DataRegistry.prototype.submitContextFormAjax=function(e){this.submitFormAjax(e,"tool_dataprivacy_set_context_form")},DataRegistry.prototype.submitFormAjax=function(e,saveMethodName){e.preventDefault();var formData=$(SELECTORS_FORM_CONTAINER).find("form").serialize();return this.strings.then((function(strings){Ajax.call([{methodname:saveMethodName,args:{jsonformdata:JSON.stringify(formData)},done:function(){Notification.alert(strings[0],strings[1])},fail:Notification.exception}])})).catch(Notification.exception)},DataRegistry.prototype.loadExtra=function(parentNode,expandContextId,expandElement){Ajax.call([{methodname:"tool_dataprivacy_tree_extra_branches",args:{contextid:expandContextId,element:expandElement},done:function(data){0!=data.branches.length?Templates.render("tool_dataprivacy/context_tree_branches",data).then(function(html){parentNode.after(html),this.removeListeners(),this.registerEventListeners(),this.expand(parentNode),parentNode.data("loaded",1)}.bind(this)).fail(Notification.exception):this.noElements(parentNode,expandElement)}.bind(this),fail:Notification.exception}])},DataRegistry.prototype.noElements=function(node,expandElement){node.data("expandcontextid",""),node.data("expandelement",""),this.strings.then((function(strings){var key=2;"module"==expandElement?key=3:"course"==expandElement&&(key=4),node.text(strings[key])})).fail(Notification.exception)},DataRegistry.prototype.collapse=function(node){node.data("expanded",0),node.siblings("nav").addClass("hidden"),node.find("> i").removeClass("fa-minus"),node.find("> i").addClass("fa-plus")},DataRegistry.prototype.expand=function(node){node.data("expanded",1),node.siblings("nav").removeClass("hidden"),node.find("> i").removeClass("fa-plus"),node.find("> i").removeClass("fa-circle-o-notch fa-spin"),node.find("> i").addClass("fa-minus")},{init:function(systemContextId,initContextLevel,initContextId){return new DataRegistry(systemContextId,initContextLevel,initContextId)}}})); /** * AMD module for data registry defaults actions. * * @module tool_dataprivacy/defaultsactions * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/defaultsactions",["jquery","core/ajax","core/notification","core/str","core/modal_factory","core/modal_events","core/templates"],(function($,Ajax,Notification,Str,ModalFactory,ModalEvents,Templates){var ACTIONS_EDIT_LEVEL_DEFAULTS='[data-action="edit-level-defaults"]',ACTIONS_NEW_ACTIVITY_DEFAULTS='[data-action="new-activity-defaults"]',ACTIONS_EDIT_ACTIVITY_DEFAULTS='[data-action="edit-activity-defaults"]',ACTIONS_DELETE_ACTIVITY_DEFAULTS='[data-action="delete-activity-defaults"]',DefaultsActions=function(){this.registerEvents()};function showDefaultsFormModal(title,contextLevel,category,purpose,activity,categoryOptions,purposeOptions,activityOptions){null!==category&&categoryOptions.forEach((function(currentValue){currentValue.id===category&&(currentValue.selected=!0)})),null!==purpose&&purposeOptions.forEach((function(currentValue){currentValue.id===purpose&&(currentValue.selected=!0)}));var templateContext={contextlevel:contextLevel,categoryoptions:categoryOptions,purposeoptions:purposeOptions};null!==activityOptions&&activityOptions.length&&(null===activity?templateContext.newactivitydefaults=!0:activityOptions.forEach((function(currentValue){activity===currentValue.name&&(currentValue.selected=!0)})),templateContext.modemodule=!0,templateContext.activityoptions=activityOptions),ModalFactory.create({title:title,body:Templates.render("tool_dataprivacy/category_purpose_form",templateContext),type:ModalFactory.types.SAVE_CANCEL,large:!0}).then((function(modal){return modal.getRoot().on(ModalEvents.save,(function(){var activity=$("#activity"),activityVal=void 0!==activity?activity.val():null,override=$("#override"),overrideVal=void 0!==override&&override.is(":checked");setContextDefaults($("#contextlevel").val(),$("#category").val(),$("#purpose").val(),activityVal,overrideVal)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show(),modal})).catch(Notification.exception)}function setContextDefaults(contextLevel,category,purpose,activity,override){var request={methodname:"tool_dataprivacy_set_context_defaults",args:{contextlevel:contextLevel,category:category,purpose:purpose,override:override,activity:activity}};Ajax.call([request])[0].done((function(data){data.result&&window.location.reload()}))}return DefaultsActions.prototype.registerEvents=function(){$(ACTIONS_EDIT_LEVEL_DEFAULTS).click((function(e){e.preventDefault();var button=$(this),contextLevel=button.data("contextlevel"),category=button.data("category"),purpose=button.data("purpose"),promises=Ajax.call([{methodname:"tool_dataprivacy_get_category_options",args:{}},{methodname:"tool_dataprivacy_get_purpose_options",args:{}}]),titlePromise=Str.get_string("editdefaults","tool_dataprivacy",$("#defaults-header").text());$.when(promises[0],promises[1],titlePromise).then((function(categoryResponse,purposeResponse,title){var categories=categoryResponse.options,purposes=purposeResponse.options;return showDefaultsFormModal(title,contextLevel,category,purpose,null,categories,purposes,null),!0})).catch(Notification.exception)})),$(ACTIONS_NEW_ACTIVITY_DEFAULTS).click((function(e){e.preventDefault();var contextLevel=$(this).data("contextlevel"),promises=Ajax.call([{methodname:"tool_dataprivacy_get_category_options",args:{}},{methodname:"tool_dataprivacy_get_purpose_options",args:{}},{methodname:"tool_dataprivacy_get_activity_options",args:{nodefaults:!0}}]),titlePromise=Str.get_string("addnewdefaults","tool_dataprivacy");$.when(promises[0],promises[1],promises[2],titlePromise).then((function(categoryResponse,purposeResponse,activityResponse,title){var categories=categoryResponse.options,purposes=purposeResponse.options,activities=activityResponse.options;return showDefaultsFormModal(title,contextLevel,null,null,null,categories,purposes,activities),!0})).catch(Notification.exception)})),$(ACTIONS_EDIT_ACTIVITY_DEFAULTS).click((function(e){e.preventDefault();var button=$(this),contextLevel=button.data("contextlevel"),category=button.data("category"),purpose=button.data("purpose"),activity=button.data("activityname"),promises=Ajax.call([{methodname:"tool_dataprivacy_get_category_options",args:{}},{methodname:"tool_dataprivacy_get_purpose_options",args:{}},{methodname:"tool_dataprivacy_get_activity_options",args:{}}]),titlePromise=Str.get_string("editmoduledefaults","tool_dataprivacy");$.when(promises[0],promises[1],promises[2],titlePromise).then((function(categoryResponse,purposeResponse,activityResponse,title){var categories=categoryResponse.options,purposes=purposeResponse.options,activities=activityResponse.options;return showDefaultsFormModal(title,contextLevel,category,purpose,activity,categories,purposes,activities),!0})).catch(Notification.exception)})),$(ACTIONS_DELETE_ACTIVITY_DEFAULTS).click((function(e){e.preventDefault();var button=$(this),contextLevel=button.data("contextlevel"),activity=button.data("activityname"),activityDisplayName=button.data("activitydisplayname");ModalFactory.create({title:Str.get_string("deletedefaults","tool_dataprivacy",activityDisplayName),body:Templates.render("tool_dataprivacy/delete_activity_defaults",{activityname:activityDisplayName}),type:ModalFactory.types.SAVE_CANCEL,large:!0}).then((function(modal){return modal.setSaveButtonText(Str.get_string("delete")),modal.getRoot().on(ModalEvents.save,(function(){setContextDefaults(contextLevel,-1,-1,activity,!1)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show(),!0})).catch(Notification.exception)}))},{init:function(){return new DefaultsActions}}})); /** * Module to update the displayed retention period. * * @module tool_dataprivacy/effective_retention_period * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/effective_retention_period",["jquery"],(function($){var SELECTORS_PURPOSE_SELECT="#id_purposeid",SELECTORS_RETENTION_FIELD="#fitem_id_retention_current [data-fieldtype=static]",EffectiveRetentionPeriod=function(purposeRetentionPeriods){this.purposeRetentionPeriods=purposeRetentionPeriods,this.registerEventListeners()};return EffectiveRetentionPeriod.prototype.purposeRetentionPeriods=[],EffectiveRetentionPeriod.prototype.registerEventListeners=function(){$(SELECTORS_PURPOSE_SELECT).on("change",function(ev){var selected=$(ev.currentTarget).val(),selectedPurpose=this.purposeRetentionPeriods[selected];$(SELECTORS_RETENTION_FIELD).text(selectedPurpose)}.bind(this))},{init:function(purposeRetentionPeriods){return $(SELECTORS_PURPOSE_SELECT).off("change"),new EffectiveRetentionPeriod(purposeRetentionPeriods)}}})); /** * Potential user selector module. * * @module tool_dataprivacy/expand_contract * @copyright 2018 Adrian Greeve * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/expand_contract",["jquery","core/url","core/str","core/notification"],(function($,url,str,Notification){var expandedImage=$('<img alt="" src="'+url.imageUrl("t/expanded")+'"/>'),collapsedImage=$('<img alt="" src="'+url.imageUrl("t/collapsed")+'"/>'),CLASSES_EXPAND="fa-caret-right",CLASSES_COLLAPSE="fa-caret-down";return{expandCollapse:function(targetnode,thisnode){targetnode.hasClass("hide")?(targetnode.removeClass("hide"),targetnode.addClass("visible"),targetnode.attr("aria-expanded",!0),thisnode.find(":header i.fa").removeClass(CLASSES_EXPAND),thisnode.find(":header i.fa").addClass(CLASSES_COLLAPSE),thisnode.find(":header img.icon").attr("src",expandedImage.attr("src"))):(targetnode.removeClass("visible"),targetnode.addClass("hide"),targetnode.attr("aria-expanded",!1),thisnode.find(":header i.fa").removeClass(CLASSES_COLLAPSE),thisnode.find(":header i.fa").addClass(CLASSES_EXPAND),thisnode.find(":header img.icon").attr("src",collapsedImage.attr("src")))},expandCollapseAll:function(nextstate){var currentstate="visible"==nextstate?"hide":"visible",ariaexpandedstate="visible"==nextstate,iconclassnow="visible"==nextstate?CLASSES_EXPAND:CLASSES_COLLAPSE,iconclassnext="visible"==nextstate?CLASSES_COLLAPSE:CLASSES_EXPAND,imagenow="visible"==nextstate?expandedImage.attr("src"):collapsedImage.attr("src");$("."+currentstate).each((function(){$(this).removeClass(currentstate),$(this).addClass(nextstate),$(this).attr("aria-expanded",ariaexpandedstate)})),$(".tool_dataprivacy-expand-all").data("visibilityState",currentstate),str.get_string(currentstate,"tool_dataprivacy").then((function(langString){$(".tool_dataprivacy-expand-all").html(langString)})).catch(Notification.exception),$(":header i.fa").each((function(){$(this).removeClass(iconclassnow),$(this).addClass(iconclassnext)})),$(":header img.icon").each((function(){$(this).attr("src",imagenow)}))}}})); /** * Potential user selector module. * * @module tool_dataprivacy/form-user-selector * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/form-user-selector",["jquery","core/ajax","core/templates"],(function($,Ajax,Templates){return{processResults:function(selector,results){var users=[];return $.each(results,(function(index,user){users.push({value:user.id,label:user._label})})),users},transport:function(selector,query,success,failure){Ajax.call([{methodname:"tool_dataprivacy_get_users",args:{query:query}}])[0].then((function(results){var promises=[],i=0;return $.each(results,(function(index,user){promises.push(Templates.render("tool_dataprivacy/form-user-selector-suggestion",user))})),$.when.apply($.when,promises).then((function(){var args=arguments;$.each(results,(function(index,user){user._label=args[i],i++})),success(results)}))})).fail(failure)}}})); /** * AMD module for purposes actions. * * @module tool_dataprivacy/purposesactions * @copyright 2018 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/purposesactions",["jquery","core/ajax","core/notification","core/str","core/modal_factory","core/modal_events"],(function($,Ajax,Notification,Str,ModalFactory,ModalEvents){var ACTIONS_DELETE='[data-action="deletepurpose"]',PurposesActions=function(){this.registerEvents()};return PurposesActions.prototype.registerEvents=function(){$(ACTIONS_DELETE).click((function(e){e.preventDefault();var id=$(this).data("id"),stringkeys=[{key:"deletepurpose",component:"tool_dataprivacy"},{key:"deletepurposetext",component:"tool_dataprivacy",param:$(this).data("name")},{key:"delete"}];Str.get_strings(stringkeys).then((function(langStrings){var title=langStrings[0],confirmMessage=langStrings[1],buttonText=langStrings[2];return ModalFactory.create({title:title,body:confirmMessage,type:ModalFactory.types.SAVE_CANCEL}).then((function(modal){return modal.setSaveButtonText(buttonText),modal.getRoot().on(ModalEvents.save,(function(){var request={methodname:"tool_dataprivacy_delete_purpose",args:{id:id}};Ajax.call([request])[0].done((function(data){data.result?$('tr[data-purposeid="'+id+'"]').remove():Notification.addNotification({message:data.warnings[0].message,type:"error"})})).fail(Notification.exception)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal}))})).done((function(modal){modal.show()})).fail(Notification.exception)}))},{init:function(){return new PurposesActions}}})); /** * JS module for the data requests filter. * * @module tool_dataprivacy/request_filter * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/request_filter",["jquery","core/form-autocomplete","core/str","core/notification"],(function($,Autocomplete,Str,Notification){var SELECTORS_REQUEST_FILTERS="#request-filters";return{init:function(){!function(){Str.get_strings([{key:"filter",component:"moodle"},{key:"nofiltersapplied",component:"moodle"}]).then((function(langstrings){var placeholder=langstrings[0],noSelectionString=langstrings[1];return Autocomplete.enhance(SELECTORS_REQUEST_FILTERS,!1,"",placeholder,!1,!0,noSelectionString,!0)})).fail(Notification.exception);var last=$(SELECTORS_REQUEST_FILTERS).val();$(SELECTORS_REQUEST_FILTERS).on("change",(function(){var current=$(this).val();last.join(",")!==current.join(",")&&(0===current.length&&$("#filters-cleared").val(1),$(this.form).submit())}))}()}}})); define("tool_dataprivacy/contactdpo",["exports","core_form/modalform","core/notification","core/str","core/toast"],(function(_exports,_modalform,_notification,_str,_toast){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Javascript module for contacting the site DPO * * @module tool_dataprivacy/contactdpo * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_modalform=_interopRequireDefault(_modalform),_notification=_interopRequireDefault(_notification);const SELECTORS_CONTACT_DPO='[data-action="contactdpo"]';_exports.init=()=>{const triggerElement=document.querySelector(SELECTORS_CONTACT_DPO);triggerElement.addEventListener("click",(event=>{event.preventDefault();const modalForm=new _modalform.default({modalConfig:{title:(0,_str.get_string)("contactdataprotectionofficer","tool_dataprivacy")},formClass:"tool_dataprivacy\\form\\contactdpo",saveButtonText:(0,_str.get_string)("send","tool_dataprivacy"),returnFocus:triggerElement});modalForm.addEventListener(modalForm.events.FORM_SUBMITTED,(event=>{if(event.detail.result)(0,_str.get_string)("requestsubmitted","tool_dataprivacy").then(_toast.add).catch();else{const warningMessages=event.detail.warnings.map((warning=>warning.message));_notification.default.addNotification({type:"error",message:warningMessages.join("<br>")})}})),modalForm.show()}))}})); /** * Request actions. * * @module tool_dataprivacy/data_request_modal * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/data_request_modal",["jquery","core/notification","core/custom_interaction_events","core/modal","core/modal_registry","tool_dataprivacy/events"],(function($,Notification,CustomEvents,Modal,ModalRegistry,DataPrivacyEvents){var registered=!1,SELECTORS_APPROVE_BUTTON='[data-action="approve"]',SELECTORS_DENY_BUTTON='[data-action="deny"]',SELECTORS_COMPLETE_BUTTON='[data-action="complete"]',ModalDataRequest=function(root){Modal.call(this,root)};return ModalDataRequest.TYPE="tool_dataprivacy-data_request",(ModalDataRequest.prototype=Object.create(Modal.prototype)).constructor=ModalDataRequest,ModalDataRequest.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this),this.getModal().on(CustomEvents.events.activate,SELECTORS_APPROVE_BUTTON,function(e,data){var approveEvent=$.Event(DataPrivacyEvents.approve);this.getRoot().trigger(approveEvent,this),approveEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this)),this.getModal().on(CustomEvents.events.activate,SELECTORS_DENY_BUTTON,function(e,data){var denyEvent=$.Event(DataPrivacyEvents.deny);this.getRoot().trigger(denyEvent,this),denyEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this)),this.getModal().on(CustomEvents.events.activate,SELECTORS_COMPLETE_BUTTON,function(e,data){var completeEvent=$.Event(DataPrivacyEvents.complete);this.getRoot().trigger(completeEvent,this),completeEvent.isDefaultPrevented()||(this.hide(),data.originalEvent.preventDefault())}.bind(this))},registered||(ModalRegistry.register(ModalDataRequest.TYPE,ModalDataRequest,"tool_dataprivacy/data_request_modal"),registered=!0),ModalDataRequest})); /** * Contain the events the data privacy tool can fire. * * @module tool_dataprivacy/events * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/events",[],(function(){return{approve:"tool_dataprivacy-data_request:approve",bulkApprove:"tool_dataprivacy-data_request:bulk_approve",deny:"tool_dataprivacy-data_request:deny",bulkDeny:"tool_dataprivacy-data_request:bulk_deny",complete:"tool_dataprivacy-data_request:complete"}})); define("tool_dataprivacy/myrequestactions",["exports","core/ajax","core/notification","core/pending","core/str"],(function(_exports,_ajax,_notification,_pending,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * AMD module to enable users to manage their own data requests. * * @module tool_dataprivacy/myrequestactions * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification),_pending=_interopRequireDefault(_pending);const SELECTORS_CANCEL_REQUEST='[data-action="cancel"][data-requestid]';_exports.init=()=>{document.addEventListener("click",(event=>{const triggerElement=event.target.closest(SELECTORS_CANCEL_REQUEST);if(null===triggerElement)return;event.preventDefault();(0,_str.get_strings)([{key:"cancelrequest",component:"tool_dataprivacy"},{key:"cancelrequestconfirmation",component:"tool_dataprivacy"}]).then((_ref=>{let[cancelRequest,cancelConfirm]=_ref;return _notification.default.confirm(cancelRequest,cancelConfirm,cancelRequest,null,(()=>{const pendingPromise=new _pending.default("tool/dataprivacy:cancelRequest"),request={methodname:"tool_dataprivacy_cancel_data_request",args:{requestid:triggerElement.dataset.requestid}};_ajax.default.call([request])[0].then((response=>(response.result?window.location.reload():_notification.default.addNotification({type:"error",message:response.warnings[0].message}),pendingPromise.resolve()))).catch(_notification.default.exception)}))})).catch()}))}})); /** * Request actions. * * @module tool_dataprivacy/requestactions * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_dataprivacy/requestactions",["jquery","core/ajax","core/notification","core/str","core/modal_factory","core/modal_events","core/templates","tool_dataprivacy/data_request_modal","tool_dataprivacy/events"],(function($,Ajax,Notification,Str,ModalFactory,ModalEvents,Templates,ModalDataRequest,DataPrivacyEvents){var ACTIONS_APPROVE_REQUEST='[data-action="approve"]',ACTIONS_DENY_REQUEST='[data-action="deny"]',ACTIONS_VIEW_REQUEST='[data-action="view"]',ACTIONS_MARK_COMPLETE='[data-action="complete"]',ACTIONS_CONFIRM_BULK_ACTION='[id="confirm-bulk-action"]',ACTIONS_SELECT_ALL='[data-action="selectall"]',BULK_ACTIONS_APPROVE=1,BULK_ACTIONS_DENY=2,SELECTORS_SELECT_REQUEST=".selectrequests",RequestActions=function(){this.registerEvents()};function approveEventWsData(requestId){return{wsfunction:"tool_dataprivacy_approve_data_request",wsparams:{requestid:requestId}}}function denyEventWsData(requestId){return{wsfunction:"tool_dataprivacy_deny_data_request",wsparams:{requestid:requestId}}}function showConfirmation(action,wsdata){var keys=[];switch(action){case DataPrivacyEvents.approve:keys=[{key:"approverequest",component:"tool_dataprivacy"},{key:"confirmapproval",component:"tool_dataprivacy"}];break;case DataPrivacyEvents.bulkApprove:keys=[{key:"bulkapproverequests",component:"tool_dataprivacy"},{key:"confirmbulkapproval",component:"tool_dataprivacy"}];break;case DataPrivacyEvents.deny:keys=[{key:"denyrequest",component:"tool_dataprivacy"},{key:"confirmdenial",component:"tool_dataprivacy"}];break;case DataPrivacyEvents.bulkDeny:keys=[{key:"bulkdenyrequests",component:"tool_dataprivacy"},{key:"confirmbulkdenial",component:"tool_dataprivacy"}];break;case DataPrivacyEvents.complete:keys=[{key:"markcomplete",component:"tool_dataprivacy"},{key:"confirmcompletion",component:"tool_dataprivacy"}]}var modalTitle="";Str.get_strings(keys).then((function(langStrings){modalTitle=langStrings[0];var confirmMessage=langStrings[1];return ModalFactory.create({title:modalTitle,body:confirmMessage,type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){modal.setSaveButtonText(modalTitle),modal.getRoot().on(ModalEvents.save,(function(){handleSave(wsdata.wsfunction,wsdata.wsparams)})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show()})).catch(Notification.exception)}function handleSave(wsfunction,params){var request={methodname:wsfunction,args:params};Ajax.call([request])[0].done((function(data){data.result?window.location.reload():Notification.addNotification({message:data.warnings[0].message,type:"error"})})).fail(Notification.exception)}return RequestActions.prototype.registerEvents=function(){$(ACTIONS_VIEW_REQUEST).click((function(e){e.preventDefault();var requestId=$(this).data("requestid"),request={methodname:"tool_dataprivacy_get_data_request",args:{requestid:requestId}},promises=Ajax.call([request]);$.when(promises[0]).then((function(data){return data.result?data.result:(Notification.addNotification({message:data.warnings[0].message,type:"error"}),!1)})).then((function(data){var body=Templates.render("tool_dataprivacy/request_details",data),templateContext={approvedeny:data.approvedeny,canmarkcomplete:data.canmarkcomplete};return ModalFactory.create({title:data.typename,body:body,type:ModalDataRequest.TYPE,large:!0,templateContext:templateContext})})).then((function(modal){modal.getRoot().on(DataPrivacyEvents.approve,(function(){showConfirmation(DataPrivacyEvents.approve,approveEventWsData(requestId))})),modal.getRoot().on(DataPrivacyEvents.deny,(function(){showConfirmation(DataPrivacyEvents.deny,denyEventWsData(requestId))})),modal.getRoot().on(DataPrivacyEvents.complete,(function(){handleSave("tool_dataprivacy_mark_complete",{requestid:requestId})})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show()})).catch(Notification.exception)})),$(ACTIONS_APPROVE_REQUEST).click((function(e){e.preventDefault();var requestId=$(this).data("requestid");showConfirmation(DataPrivacyEvents.approve,approveEventWsData(requestId))})),$(ACTIONS_DENY_REQUEST).click((function(e){e.preventDefault();var requestId=$(this).data("requestid");showConfirmation(DataPrivacyEvents.deny,denyEventWsData(requestId))})),$(ACTIONS_MARK_COMPLETE).click((function(e){e.preventDefault();var requestId=$(this).data("requestid");showConfirmation(DataPrivacyEvents.complete,function(requestId){return{wsfunction:"tool_dataprivacy_mark_complete",wsparams:{requestid:requestId}}}(requestId))})),$(ACTIONS_CONFIRM_BULK_ACTION).click((function(){var requestIds=[],actionEvent="",wsdata={},bulkActionKeys=[{key:"selectbulkaction",component:"tool_dataprivacy"},{key:"selectdatarequests",component:"tool_dataprivacy"},{key:"ok"}],bulkaction=parseInt($("#bulk-action").val());if(bulkaction==BULK_ACTIONS_APPROVE||bulkaction==BULK_ACTIONS_DENY)if($(".selectrequests:checked").each((function(){requestIds.push($(this).val())})),requestIds.length<1)Str.get_strings(bulkActionKeys).done((function(langStrings){Notification.alert("",langStrings[1],langStrings[2])})).fail(Notification.exception);else{switch(bulkaction){case BULK_ACTIONS_APPROVE:actionEvent=DataPrivacyEvents.bulkApprove,wsdata=function(requestIds){return{wsfunction:"tool_dataprivacy_bulk_approve_data_requests",wsparams:{requestids:requestIds}}}(requestIds);break;case BULK_ACTIONS_DENY:actionEvent=DataPrivacyEvents.bulkDeny,wsdata=function(requestIds){return{wsfunction:"tool_dataprivacy_bulk_deny_data_requests",wsparams:{requestids:requestIds}}}(requestIds)}showConfirmation(actionEvent,wsdata)}else Str.get_strings(bulkActionKeys).done((function(langStrings){Notification.alert("",langStrings[0],langStrings[2])})).fail(Notification.exception)})),$(ACTIONS_SELECT_ALL).change((function(e){e.preventDefault();var selectAll=$(this).is(":checked");$(SELECTORS_SELECT_REQUEST).prop("checked",selectAll)}))},RequestActions})); define("tool_langimport/search",["exports","core/pending","core/utils"],(function(_exports,_pending,_utils){var obj; /** * Add search filtering of available language packs * * @module tool_langimport/search * @copyright 2021 Paul Holden <paulh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};const SELECTORS_AVAILABLE_LANG_SELECT="select",SELECTORS_AVAILABLE_LANG_SEARCH='[data-action="search"]';_exports.init=form=>{const availableLangsElement=form.querySelector(SELECTORS_AVAILABLE_LANG_SELECT),availableLanguages={};availableLangsElement.querySelectorAll("option").forEach((option=>{availableLanguages[option.value]=option.text})),availableLangsElement.dataset.availableLanguages=JSON.stringify(availableLanguages);const availableLangsSearch=form.querySelector(SELECTORS_AVAILABLE_LANG_SEARCH);availableLangsSearch.addEventListener("keydown",(event=>{"Enter"===event.key&&event.preventDefault()}));const availableLangsSearchDebounce=(0,_utils.debounce)((event=>{const pendingPromise=new _pending.default("tool_langimport/search:filter");availableLangsElement.querySelectorAll("option").forEach((option=>{option.remove()}));const searchTerm=event.target.value.toLowerCase(),availableLanguages=JSON.parse(availableLangsElement.dataset.availableLanguages),filteredLanguages=Object.keys(availableLanguages).reduce(((matches,langcode)=>(availableLanguages[langcode].toLowerCase().includes(searchTerm)&&(matches[langcode]=availableLanguages[langcode]),matches)),[]);Object.entries(filteredLanguages).forEach((_ref=>{let[langcode,langname]=_ref;const option=document.createElement("option");option.value=langcode,option.innerText=langname,availableLangsElement.append(option)})),pendingPromise.resolve()}),250);availableLangsSearch.addEventListener("keyup",(event=>{const pendingPromise=new _pending.default("tool_langimport/search:keyup");availableLangsSearchDebounce(event),setTimeout((()=>{pendingPromise.resolve()}),250)}))}})); /** * Modal for confirming deletion of a custom license. * * @module tool_licensemanager/delete_license * @copyright 2019 Tom Dickman <tomdickman@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_licensemanager/delete_license",["jquery","core/modal_factory","core/modal_events","core/url","core/str"],(function($,ModalFactory,ModalEvents,Url,String){var trigger=$(".delete-license");ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:String.get_string("deletelicense","tool_licensemanager"),body:String.get_string("deletelicenseconfirmmessage","tool_licensemanager"),preShowCallback:function(triggerElement,modal){let params={action:"delete",license:(triggerElement=$(triggerElement)).data("license")};modal.deleteURL=Url.relativeUrl("/admin/tool/licensemanager/index.php",params,!0)},large:!0},trigger).done((function(modal){modal.getRoot().on(ModalEvents.save,(function(e){e.preventDefault(),window.location.href=modal.deleteURL}))}))})); /** * Action selector. * * To handle 'save' events use: actionselector.on('save') * This will receive the information to display in popup. * The actions have the format [{'text': sometext, 'value' : somevalue}]. * * @module tool_lp/actionselector * @copyright 2016 Serge Gauthier - <serge.gauthier.2@umontreal.ca> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/actionselector",["jquery","core/notification","core/ajax","core/templates","tool_lp/dialogue","tool_lp/event_base"],(function($,Notification,Ajax,Templates,Dialogue,EventBase){var ActionSelector=function(title,message,actions,confirm,cancel){EventBase.prototype.constructor.apply(this,[]),this._title=title,this._message=message,this._actions=actions,this._confirm=confirm,this._cancel=cancel,this._selectedValue=null,this._reset()};return(ActionSelector.prototype=Object.create(EventBase.prototype))._selectedValue=null,ActionSelector.prototype._popup=null,ActionSelector.prototype._title=null,ActionSelector.prototype._message=null,ActionSelector.prototype._actions=null,ActionSelector.prototype._confirm=null,ActionSelector.prototype._cancel=null,ActionSelector.prototype._afterRender=function(){var self=this;self._find('[data-action="action-selector-confirm"]').attr("disabled","disabled"),self._find('[data-region="action-selector-radio-buttons"]').change((function(){self._selectedValue=$("input[type='radio']:checked").val(),self._find('[data-action="action-selector-confirm"]').removeAttr("disabled"),self._refresh.bind(self)})),self._find('[data-action="action-selector-cancel"]').click((function(e){e.preventDefault(),self.close()})),self._find('[data-action="action-selector-confirm"]').click((function(e){e.preventDefault(),self._selectedValue.length&&(self._trigger("save",{action:self._selectedValue}),self.close())}))},ActionSelector.prototype.close=function(){this._popup.close(),this._reset()},ActionSelector.prototype.display=function(){var self=this;return self._render().then((function(html){self._popup=new Dialogue(self._title,html,self._afterRender.bind(self))})).fail(Notification.exception)},ActionSelector.prototype._find=function(selector){return $(this._popup.getContent()).find(selector)},ActionSelector.prototype._refresh=function(){var self=this;return self._render().then((function(html){self._find('[data-region="action-selector"]').replaceWith(html),self._afterRender()}))},ActionSelector.prototype._render=function(){var choices=[];for(var i in this._actions)choices.push(this._actions[i]);var content={message:this._message,choices:choices,confirm:this._confirm,cancel:this._cancel};return Templates.render("tool_lp/action_selector",content)},ActionSelector.prototype._reset=function(){this._popup=null,this._selectedValue=""},ActionSelector})); /** * Handle add/remove competency links. * * @module tool_lp/competencies * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencies",["jquery","core/notification","core/ajax","core/templates","core/str","tool_lp/competencypicker","tool_lp/dragdrop-reorder","core/pending"],(function($,notification,ajax,templates,str,Picker,dragdrop,Pending){var competencies=function(itemid,itemtype,pagectxid){this.itemid=itemid,this.itemtype=itemtype,this.pageContextId=pagectxid,this.pickerInstance=null,$('[data-region="actions"] button').prop("disabled",!1),this.registerEvents(),this.registerDragDrop()};return competencies.prototype.registerDragDrop=function(){var localthis=this;str.get_string("movecompetency","tool_lp").done((function(movestring){dragdrop.dragdrop("movecompetency",movestring,{identifier:"movecompetency",component:"tool_lp"},{identifier:"movecompetencyafter",component:"tool_lp"},"drag-samenode","drag-parentnode","drag-handlecontainer",(function(drag,drop){localthis.handleDrop(drag,drop)}))})).fail(notification.exception)},competencies.prototype.handleDrop=function(drag,drop){var fromid=$(drag).data("id"),toid=$(drop).data("id"),requests=[];if("course"==this.itemtype)requests=ajax.call([{methodname:"core_competency_reorder_course_competency",args:{courseid:this.itemid,competencyidfrom:fromid,competencyidto:toid}}]);else if("template"==this.itemtype)requests=ajax.call([{methodname:"core_competency_reorder_template_competency",args:{templateid:this.itemid,competencyidfrom:fromid,competencyidto:toid}}]);else{if("plan"!=this.itemtype)return;requests=ajax.call([{methodname:"core_competency_reorder_plan_competency",args:{planid:this.itemid,competencyidfrom:fromid,competencyidto:toid}}])}requests[0].fail(notification.exception)},competencies.prototype.pickCompetency=function(){var requests,pagerender,pageregion,pageContextIncludes,self=this;return self.pickerInstance||("template"!==self.itemtype&&"course"!==self.itemtype||(pageContextIncludes="parents"),self.pickerInstance=new Picker(self.pageContextId,!1,pageContextIncludes),self.pickerInstance.on("save",(function(e,data){var compIds=data.competencyIds,pendingPromise=new Pending;"course"===self.itemtype?(requests=[],$.each(compIds,(function(index,compId){requests.push({methodname:"core_competency_add_competency_to_course",args:{courseid:self.itemid,competencyid:compId}})})),requests.push({methodname:"tool_lp_data_for_course_competencies_page",args:{courseid:self.itemid,moduleid:0}}),pagerender="tool_lp/course_competencies_page",pageregion="coursecompetenciespage"):"template"===self.itemtype?(requests=[],$.each(compIds,(function(index,compId){requests.push({methodname:"core_competency_add_competency_to_template",args:{templateid:self.itemid,competencyid:compId}})})),requests.push({methodname:"tool_lp_data_for_template_competencies_page",args:{templateid:self.itemid,pagecontext:{contextid:self.pageContextId}}}),pagerender="tool_lp/template_competencies_page",pageregion="templatecompetenciespage"):"plan"===self.itemtype&&(requests=[],$.each(compIds,(function(index,compId){requests.push({methodname:"core_competency_add_competency_to_plan",args:{planid:self.itemid,competencyid:compId}})})),requests.push({methodname:"tool_lp_data_for_plan_page",args:{planid:self.itemid}}),pagerender="tool_lp/plan_page",pageregion="plan-page"),ajax.call(requests)[requests.length-1].then((function(context){return templates.render(pagerender,context)})).then((function(html,js){templates.replaceNode($('[data-region="'+pageregion+'"]'),html,js)})).then(pendingPromise.resolve).catch(notification.exception)}))),self.pickerInstance.display()},competencies.prototype.doDelete=function(deleteid){var requests=[],pagerender="",pageregion="";"course"==this.itemtype?(requests=ajax.call([{methodname:"core_competency_remove_competency_from_course",args:{courseid:this.itemid,competencyid:deleteid}},{methodname:"tool_lp_data_for_course_competencies_page",args:{courseid:this.itemid,moduleid:0}}]),pagerender="tool_lp/course_competencies_page",pageregion="coursecompetenciespage"):"template"==this.itemtype?(requests=ajax.call([{methodname:"core_competency_remove_competency_from_template",args:{templateid:this.itemid,competencyid:deleteid}},{methodname:"tool_lp_data_for_template_competencies_page",args:{templateid:this.itemid,pagecontext:{contextid:this.pageContextId}}}]),pagerender="tool_lp/template_competencies_page",pageregion="templatecompetenciespage"):"plan"==this.itemtype&&(requests=ajax.call([{methodname:"core_competency_remove_competency_from_plan",args:{planid:this.itemid,competencyid:deleteid}},{methodname:"tool_lp_data_for_plan_page",args:{planid:this.itemid}}]),pagerender="tool_lp/plan_page",pageregion="plan-page"),requests[1].done((function(context){templates.render(pagerender,context).done((function(html,js){$('[data-region="'+pageregion+'"]').replaceWith(html),templates.runTemplateJS(js)})).fail(notification.exception)})).fail(notification.exception)},competencies.prototype.deleteHandler=function(deleteid){var message,localthis=this;if("course"==localthis.itemtype)message="unlinkcompetencycourse";else if("template"==localthis.itemtype)message="unlinkcompetencytemplate";else{if("plan"!=localthis.itemtype)return;message="unlinkcompetencyplan"}ajax.call([{methodname:"core_competency_read_competency",args:{id:deleteid}}])[0].done((function(competency){str.get_strings([{key:"confirm",component:"moodle"},{key:message,component:"tool_lp",param:competency.shortname},{key:"confirm",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){localthis.doDelete(deleteid)}))})).fail(notification.exception)})).fail(notification.exception)},competencies.prototype.registerEvents=function(){var localthis=this;"course"==localthis.itemtype&&$('[data-region="coursecompetenciespage"]').on("change",'select[data-field="ruleoutcome"]',(function(e){var pendingPromise=new Pending,coursecompetencyid=$(e.target).data("id"),ruleoutcome=$(e.target).val();ajax.call([{methodname:"core_competency_set_course_competency_ruleoutcome",args:{coursecompetencyid:coursecompetencyid,ruleoutcome:ruleoutcome}},{methodname:"tool_lp_data_for_course_competencies_page",args:{courseid:localthis.itemid,moduleid:0}}])[1].then((function(context){return templates.render("tool_lp/course_competencies_page",context)})).then((function(html,js){return templates.replaceNode($('[data-region="coursecompetenciespage"]'),html,js)})).then(pendingPromise.resolve).catch(notification.exception)})),$('[data-region="actions"] button').click((function(e){var pendingPromise=new Pending;e.preventDefault(),localthis.pickCompetency().then(pendingPromise.resolve).catch()})),$('[data-action="delete-competency-link"]').click((function(e){e.preventDefault();var deleteid=$(e.target).closest("[data-id]").data("id");localthis.deleteHandler(deleteid)}))},competencies})); /** * Competency rule config. * * @module tool_lp/competency_outcomes * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competency_outcomes",["jquery","core/str"],(function($,Str){return{NONE:0,EVIDENCE:1,COMPLETE:2,RECOMMEND:3,getAll:function(){var self=this;return Str.get_strings([{key:"competencyoutcome_none",component:"tool_lp"},{key:"competencyoutcome_evidence",component:"tool_lp"},{key:"competencyoutcome_recommend",component:"tool_lp"},{key:"competencyoutcome_complete",component:"tool_lp"}]).then((function(strings){var outcomes={};return outcomes[self.NONE]={code:self.NONE,name:strings[0]},outcomes[self.EVIDENCE]={code:self.EVIDENCE,name:strings[1]},outcomes[self.RECOMMEND]={code:self.RECOMMEND,name:strings[2]},outcomes[self.COMPLETE]={code:self.COMPLETE,name:strings[3]},outcomes}))},getString:function(id){return this.getAll().then((function(outcomes){return void 0===outcomes[id]?$.Deferred().reject().promise():outcomes[id].name}))}}})); /** * Event click on selecting competency in the competency autocomplete. * * @module tool_lp/competency_plan_navigation * @copyright 2016 Issam Taboubi <issam.taboubi@umontreal.ca> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competency_plan_navigation",["jquery"],(function($){var CompetencyPlanNavigation=function(competencySelector,baseUrl,userId,competencyId,planId){this._baseUrl=baseUrl,this._userId=userId+"",this._competencyId=competencyId+"",this._planId=planId,this._ignoreFirstCompetency=!0,$(competencySelector).on("change",this._competencyChanged.bind(this))};return CompetencyPlanNavigation.prototype._competencyChanged=function(e){if(this._ignoreFirstCompetency)this._ignoreFirstCompetency=!1;else{var newCompetencyId=$(e.target).val(),queryStr="?userid="+this._userId+"&planid="+this._planId+"&competencyid="+newCompetencyId;document.location=this._baseUrl+queryStr}},CompetencyPlanNavigation.prototype._competencyId=null,CompetencyPlanNavigation.prototype._userId=null,CompetencyPlanNavigation.prototype._planId=null,CompetencyPlanNavigation.prototype._baseUrl=null,CompetencyPlanNavigation.prototype._ignoreFirstCompetency=null,CompetencyPlanNavigation})); /** * Competency rule all module. * * @module tool_lp/competency_rule_all * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competency_rule_all",["jquery","core/str","tool_lp/competency_rule"],(function($,Str,RuleBase){var Rule=function(){RuleBase.apply(this,arguments)};return(Rule.prototype=Object.create(RuleBase.prototype)).getType=function(){return"core_competency\\competency_rule_all"},Rule.prototype.isValid=function(){return!0},Rule})); /** * Handle selection changes and actions on the competency tree. * * @module tool_lp/competencyactions * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencyactions",["jquery","core/url","core/templates","core/notification","core/str","core/ajax","tool_lp/dragdrop-reorder","tool_lp/tree","tool_lp/dialogue","tool_lp/menubar","tool_lp/competencypicker","tool_lp/competency_outcomes","tool_lp/competencyruleconfig","core/pending"],(function($,url,templates,notification,str,ajax,dragdrop,Ariatree,Dialogue,menubar,Picker,Outcomes,RuleConfig,Pending){var pageContextId,pickerInstance,ruleConfigInstance,relatedTarget,taxonomiesConstants,rulesModules,treeModel=null,moveSource=null,moveTarget=null,selectedCompetencyId=null,addHandler=function(){var parent=$('[data-region="competencyactions"]').data("competency"),params={competencyframeworkid:treeModel.getCompetencyFrameworkId(),pagecontextid:pageContextId};null!==parent&&(params.parentid=parent.id);var relocate=function(){var queryparams=$.param(params);window.location=url.relativeUrl("/admin/tool/lp/editcompetency.php?"+queryparams)};null!==parent&&treeModel.hasRule(parent.id)?str.get_strings([{key:"confirm",component:"moodle"},{key:"addingcompetencywillresetparentrule",component:"tool_lp",param:parent.shortname},{key:"yes",component:"core"},{key:"no",component:"core"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],relocate)})).fail(notification.exception):relocate()},doMove=function(){var frameworkid=$('[data-region="filtercompetencies"]').data("frameworkid");ajax.call([{methodname:"core_competency_set_parent_competency",args:{competencyid:moveSource,parentid:moveTarget}},{methodname:"tool_lp_data_for_competencies_manage_page",args:{competencyframeworkid:frameworkid,search:$('[data-region="filtercompetencies"] input').val()}}])[1].done(reloadPage).fail(notification.exception)},confirmMove=function(){if((moveTarget=void 0===moveTarget?0:moveTarget)!=moveSource){var targetComp=treeModel.getCompetency(moveTarget)||{},sourceComp=treeModel.getCompetency(moveSource)||{},confirmMessage="movecompetencywillresetrules",showConfirm=!1;sourceComp.parentid!=moveTarget&&(targetComp.path&&targetComp.path.indexOf("/"+sourceComp.id+"/")>=0&&(confirmMessage="movecompetencytochildofselfwillresetrules",showConfirm=showConfirm||treeModel.hasRule(sourceComp.id)),(showConfirm=showConfirm||treeModel.hasRule(targetComp.id)||treeModel.hasRule(sourceComp.parentid))?str.get_strings([{key:"confirm",component:"moodle"},{key:confirmMessage,component:"tool_lp"},{key:"yes",component:"moodle"},{key:"no",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],doMove)})).fail(notification.exception):doMove())}},initMovePopup=function(popup){var body=$(popup.getContent()),treeRoot=body.find("[data-enhance=movetree]");new Ariatree(treeRoot,!1).on("selectionchanged",(function(evt,params){var target=params.selected;moveTarget=$(target).data("id")})),treeRoot.show(),body.on("click",'[data-action="move"]',(function(){popup.close(),confirmMove()})),body.on("click",'[data-action="cancel"]',(function(){popup.close()}))},addCompetencyChildren=function(parent,competencies){var i;for(i=0;i<competencies.length;i++)competencies[i].parentid==parent.id&&(parent.haschildren=!0,competencies[i].children=[],competencies[i].haschildren=!1,parent.children[parent.children.length]=competencies[i],addCompetencyChildren(competencies[i],competencies))},moveHandler=function(e){e.preventDefault();var competency=$('[data-region="competencyactions"]').data("competency");moveSource=competency.id;var requests=ajax.call([{methodname:"core_competency_search_competencies",args:{competencyframeworkid:competency.competencyframeworkid,searchtext:""}},{methodname:"core_competency_read_competency_framework",args:{id:competency.competencyframeworkid}}]);$.when.apply(null,requests).done((function(competencies,framework){var i,competenciestree=[];for(i=0;i<competencies.length;i++){var onecompetency=competencies[i];"0"==onecompetency.parentid&&(onecompetency.children=[],onecompetency.haschildren=0,competenciestree[competenciestree.length]=onecompetency,addCompetencyChildren(onecompetency,competencies))}str.get_strings([{key:"movecompetency",component:"tool_lp",param:competency.shortname},{key:"move",component:"tool_lp"},{key:"cancel",component:"moodle"}]).done((function(strings){var context={framework:framework,competencies:competenciestree};templates.render("tool_lp/competencies_move_tree",context).done((function(tree){new Dialogue(strings[0],tree,initMovePopup)})).fail(notification.exception)})).fail(notification.exception)})).fail(notification.exception)},editHandler=function(){var competency=$('[data-region="competencyactions"]').data("competency"),params={competencyframeworkid:treeModel.getCompetencyFrameworkId(),id:competency.id,parentid:competency.parentid,pagecontextid:pageContextId},queryparams=$.param(params);window.location=url.relativeUrl("/admin/tool/lp/editcompetency.php?"+queryparams)},reloadPage=function(context){templates.render("tool_lp/manage_competencies_page",context).done((function(newhtml,newjs){$('[data-region="managecompetencies"]').replaceWith(newhtml),templates.runTemplateJS(newjs)})).fail(notification.exception)},updateSearchHandler=function(e){e.preventDefault();var frameworkid=$('[data-region="filtercompetencies"]').data("frameworkid");ajax.call([{methodname:"tool_lp_data_for_competencies_manage_page",args:{competencyframeworkid:frameworkid,search:$('[data-region="filtercompetencies"] input').val()}}])[0].done(reloadPage).fail(notification.exception)},moveUpHandler=function(){var competency=$('[data-region="competencyactions"]').data("competency");ajax.call([{methodname:"core_competency_move_up_competency",args:{id:competency.id}},{methodname:"tool_lp_data_for_competencies_manage_page",args:{competencyframeworkid:competency.competencyframeworkid,search:$('[data-region="filtercompetencies"] input').val()}}])[1].done(reloadPage).fail(notification.exception)},moveDownHandler=function(){var competency=$('[data-region="competencyactions"]').data("competency");ajax.call([{methodname:"core_competency_move_down_competency",args:{id:competency.id}},{methodname:"tool_lp_data_for_competencies_manage_page",args:{competencyframeworkid:competency.competencyframeworkid,search:$('[data-region="filtercompetencies"] input').val()}}])[1].done(reloadPage).fail(notification.exception)},seeCoursesHandler=function(){var competency=$('[data-region="competencyactions"]').data("competency");ajax.call([{methodname:"tool_lp_list_courses_using_competency",args:{id:competency.id}}])[0].done((function(courses){var context={courses:courses};templates.render("tool_lp/linked_courses_summary",context).done((function(html){str.get_string("linkedcourses","tool_lp").done((function(linkedcourses){new Dialogue(linkedcourses,html,initMovePopup)})).fail(notification.exception)})).fail(notification.exception)})).fail(notification.exception)},relateCompetenciesHandler=function(){relatedTarget=$('[data-region="competencyactions"]').data("competency"),pickerInstance||(pickerInstance=new Picker(pageContextId,relatedTarget.competencyframeworkid)).on("save",(function(e,data){var pendingPromise=new Pending,compIds=data.competencyIds,calls=[];$.each(compIds,(function(index,value){calls.push({methodname:"core_competency_add_related_competency",args:{competencyid:value,relatedcompetencyid:relatedTarget.id}})})),calls.push({methodname:"tool_lp_data_for_related_competencies_section",args:{competencyid:relatedTarget.id}}),ajax.call(calls)[calls.length-1].then((function(context){return templates.render("tool_lp/related_competencies",context)})).then((function(html,js){$('[data-region="relatedcompetencies"]').replaceWith(html),templates.runTemplateJS(js),updatedRelatedCompetencies()})).then(pendingPromise.resolve).catch(notification.exception)})),pickerInstance.setDisallowedCompetencyIDs([relatedTarget.id]),pickerInstance.display()},ruleConfigHandler=function(e){e.preventDefault(),relatedTarget=$('[data-region="competencyactions"]').data("competency"),ruleConfigInstance.setTargetCompetencyId(relatedTarget.id),ruleConfigInstance.display()},ruleConfigSaveHandler=function(e,config){var update={id:relatedTarget.id,shortname:relatedTarget.shortname,idnumber:relatedTarget.idnumber,description:relatedTarget.description,descriptionformat:relatedTarget.descriptionformat,ruletype:config.ruletype,ruleoutcome:config.ruleoutcome,ruleconfig:config.ruleconfig};ajax.call([{methodname:"core_competency_update_competency",args:{competency:update}}])[0].then((function(result){result&&(relatedTarget.ruletype=config.ruletype,relatedTarget.ruleoutcome=config.ruleoutcome,relatedTarget.ruleconfig=config.ruleconfig,renderCompetencySummary(relatedTarget))})).catch(notification.exception)},doDelete=function(){var competency=$('[data-region="competencyactions"]').data("competency"),requests=ajax.call([{methodname:"core_competency_delete_competency",args:{id:competency.id}},{methodname:"tool_lp_data_for_competencies_manage_page",args:{competencyframeworkid:competency.competencyframeworkid,search:$('[data-region="filtercompetencies"] input').val()}}]);requests[0].done((function(success){!1===success&&str.get_strings([{key:"competencycannotbedeleted",component:"tool_lp",param:competency.shortname},{key:"cancel",component:"moodle"}]).done((function(strings){notification.alert(null,strings[0])})).fail(notification.exception)})).fail(notification.exception),requests[1].done(reloadPage).fail(notification.exception)},deleteCompetencyHandler=function(){var competency=$('[data-region="competencyactions"]').data("competency"),confirmMessage="deletecompetency";treeModel.hasRule(competency.parentid)&&(confirmMessage="deletecompetencyparenthasrule"),str.get_strings([{key:"confirm",component:"moodle"},{key:confirmMessage,component:"tool_lp",param:competency.shortname},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],doDelete)})).fail(notification.exception)},dragStart=function(e){e.originalEvent.dataTransfer.setData("text",$(e.target).parent().data("id"))},allowDrop=function(e){e.originalEvent.dataTransfer.dropEffect="move",e.preventDefault()},dragEnter=function(e){e.preventDefault(),$(this).addClass("currentdragtarget")},dragLeave=function(e){e.preventDefault(),$(this).removeClass("currentdragtarget")},dropOver=function(e){e.preventDefault(),moveSource=e.originalEvent.dataTransfer.getData("text"),moveTarget=$(e.target).parent().data("id"),$(this).removeClass("currentdragtarget"),confirmMove()},deleteRelatedHandler=function(e){e.preventDefault();var relatedid=this.id.substr(11),competency=$('[data-region="competencyactions"]').data("competency");ajax.call([{methodname:"core_competency_remove_related_competency",args:{relatedcompetencyid:relatedid,competencyid:competency.id}},{methodname:"tool_lp_data_for_related_competencies_section",args:{competencyid:competency.id}}])[1].done((function(context){templates.render("tool_lp/related_competencies",context).done((function(html){$('[data-region="relatedcompetencies"]').replaceWith(html),updatedRelatedCompetencies()})).fail(notification.exception)})).fail(notification.exception)},updatedRelatedCompetencies=function(){$('[data-action="deleterelation"]').on("click",deleteRelatedHandler)},getTaxonomyAtLevel=function(level){var constant=taxonomiesConstants[level];return constant||(constant="competency"),constant},renderCompetencySummary=function(competency){var promise=$.Deferred().resolve().promise(),context={};context.competency=competency,context.showdeleterelatedaction=!0,context.showrelatedcompetencies=!0,context.showrule=!1,context.pluginbaseurl=url.relativeUrl("/admin/tool/lp"),competency.ruleoutcome!=Outcomes.NONE&&(promise=Outcomes.getString(competency.ruleoutcome).then((function(str){var name;return $.each(rulesModules,(function(index,modInfo){modInfo.type==competency.ruletype&&(name=modInfo.name)})),[str,name]}))),promise.then((function(strs){return void 0!==strs&&(context.showrule=!0,context.rule={outcome:strs[0],type:strs[1]}),context})).then((function(context){return templates.render("tool_lp/competency_summary",context)})).then((function(html){return $('[data-region="competencyinfo"]').html(html),$('[data-action="deleterelation"]').on("click",deleteRelatedHandler),templates.render("tool_lp/loading",{})})).then((function(html,js){return templates.replaceNodeContents('[data-region="relatedcompetencies"]',html,js),ajax.call([{methodname:"tool_lp_data_for_related_competencies_section",args:{competencyid:competency.id}}])[0]})).then((function(context){return templates.render("tool_lp/related_competencies",context)})).then((function(html,js){$('[data-region="relatedcompetencies"]').replaceWith(html),templates.runTemplateJS(js),updatedRelatedCompetencies()})).catch(notification.exception)},selectionChanged=function(evt,params){var node=params.selected,id=$(node).data("id"),btn=$('[data-region="competencyactions"] [data-action="add"]'),actionMenu=$('[data-region="competencyactionsmenu"]'),selectedTitle=$('[data-region="selected-competency"]'),level=0,sublevel=1;if(menubar.closeAll(),void 0===id)$('[data-region="competencyinfo"]').html(node.clone().children().remove().end().text()),$('[data-region="competencyactions"]').data("competency",null),actionMenu.hide();else{var competency=treeModel.getCompetency(id);sublevel=(level=treeModel.getCompetencyLevel(id))+1,actionMenu.show(),$('[data-region="competencyactions"]').data("competency",competency),renderCompetencySummary(competency),function(competency){competency.id!==selectedCompetencyId&&(selectedCompetencyId=competency.id,ajax.call([{methodname:"core_competency_competency_viewed",args:{id:competency.id}}]))}(competency)}return function(level){return str.get_string("taxonomy_selected_"+getTaxonomyAtLevel(level),"tool_lp")}(level).then((function(str){selectedTitle.text(str)})).catch(notification.exception),function(level){return str.get_string("taxonomy_add_"+getTaxonomyAtLevel(level),"tool_lp")}(sublevel).then((function(str){btn.show().find('[data-region="term"]').text(str)})).catch(notification.exception),evt.preventDefault(),!1};return{init:function(model,pagectxid,taxonomies,rulesMods){var all;treeModel=model,pageContextId=pagectxid,(all=taxonomies.split(",")).unshift(""),delete all[0],taxonomiesConstants=all,rulesModules=rulesMods,$('[data-region="competencyactions"] [data-action="add"]').on("click",addHandler),menubar.enhance(".competencyactionsmenu",{'[data-action="edit"]':editHandler,'[data-action="delete"]':deleteCompetencyHandler,'[data-action="move"]':moveHandler,'[data-action="moveup"]':moveUpHandler,'[data-action="movedown"]':moveDownHandler,'[data-action="linkedcourses"]':seeCoursesHandler,'[data-action="relatedcompetencies"]':relateCompetenciesHandler.bind(this),'[data-action="competencyrules"]':ruleConfigHandler.bind(this)}),$('[data-region="competencyactionsmenu"]').hide(),$('[data-region="competencyactions"] [data-action="add"]').hide(),$('[data-region="filtercompetencies"]').on("submit",updateSearchHandler),$('[data-region="managecompetencies"] [data-enhance="tree"]').on("dragstart","li>span",dragStart).on("dragover","li>span",allowDrop).on("dragenter","li>span",dragEnter).on("dragleave","li>span",dragLeave).on("drop","li>span",dropOver),model.on("selectionchanged",selectionChanged),(ruleConfigInstance=new RuleConfig(treeModel,rulesModules)).on("save",ruleConfigSaveHandler.bind(this))}}})); /** * Competency picker. * * To handle 'save' events use: picker.on('save') * This will receive a object with either a single 'competencyId', or an array in 'competencyIds' * depending on the value of multiSelect. * * @module tool_lp/competencypicker * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencypicker",["jquery","core/notification","core/ajax","core/templates","tool_lp/dialogue","core/str","tool_lp/tree","core/pending"],(function($,Notification,Ajax,Templates,Dialogue,Str,Tree,Pending){var Picker=function(pageContextId,singleFramework,pageContextIncludes,multiSelect){this._eventNode=$("<div></div>"),this._frameworks=[],this._reset(),this._pageContextId=pageContextId,this._pageContextIncludes=pageContextIncludes||"children",this._multiSelect=void 0===multiSelect||!0===multiSelect,singleFramework&&(this._frameworkId=singleFramework,this._singleFramework=!0)};return Picker.prototype._competencies=null,Picker.prototype._disallowedCompetencyIDs=null,Picker.prototype._eventNode=null,Picker.prototype._frameworks=null,Picker.prototype._frameworkId=null,Picker.prototype._pageContextId=null,Picker.prototype._pageContextIncludes=null,Picker.prototype._popup=null,Picker.prototype._searchText="",Picker.prototype._selectedCompetencies=null,Picker.prototype._singleFramework=!1,Picker.prototype._multiSelect=!0,Picker.prototype._onlyVisible=!0,Picker.prototype._afterRender=function(){var self=this,tree=new Tree(self._find("[data-enhance=linktree]"),self._multiSelect);self._find("[data-enhance=linktree]").show(),tree.on("selectionchanged",(function(evt,params){var selected=params.selected;evt.preventDefault();var validIds=[];$.each(selected,(function(index,item){var compId=$(item).data("id"),valid=!0;void 0===compId?valid=!1:$.each(self._disallowedCompetencyIDs,(function(i,id){id==compId&&(valid=!1)})),valid&&validIds.push(compId)})),self._selectedCompetencies=validIds,self._selectedCompetencies.length?self._find('[data-region="competencylinktree"] [data-action="add"]').removeAttr("disabled"):self._find('[data-region="competencylinktree"] [data-action="add"]').attr("disabled","disabled")})),self._singleFramework||self._find('[data-action="chooseframework"]').change((function(e){self._frameworkId=$(e.target).val(),self._loadCompetencies().then(self._refresh.bind(self)).catch(Notification.exception)})),self._find('[data-region="filtercompetencies"] button').click((function(e){return e.preventDefault(),$(e.target).attr("disabled","disabled"),self._searchText=self._find('[data-region="filtercompetencies"] input').val()||"",self._refresh().always((function(){$(e.target).removeAttr("disabled")}))})),self._find('[data-region="competencylinktree"] [data-action="cancel"]').click((function(e){e.preventDefault(),self.close()})),self._find('[data-region="competencylinktree"] [data-action="add"]').click((function(e){e.preventDefault();var pendingPromise=new Pending;self._selectedCompetencies.length&&(self._multiSelect?self._trigger("save",{competencyIds:self._selectedCompetencies}):self._trigger("save",{competencyId:self._selectedCompetencies[0]}),self.close(),pendingPromise.resolve())}));var currentItems=self._selectedCompetencies.slice(0);$.each(currentItems,(function(index,id){var node=self._find("[data-id="+id+"]");node.length&&(tree.toggleItem(node),tree.updateFocus(node))}))},Picker.prototype.close=function(){this._popup.close(),this._reset()},Picker.prototype.display=function(){var self=this;return $.when(Str.get_string("competencypicker","tool_lp"),self._render()).then((function(title,render){self._popup=new Dialogue(title,render[0],self._afterRender.bind(self))})).catch(Notification.exception)},Picker.prototype._fetchCompetencies=function(frameworkId,searchText){var self=this;return Ajax.call([{methodname:"core_competency_search_competencies",args:{searchtext:searchText,competencyframeworkid:frameworkId}}])[0].done((function(competencies){function addCompetencyChildren(parent,competencies){for(var i=0;i<competencies.length;i++)competencies[i].parentid==parent.id&&(parent.haschildren=!0,competencies[i].children=[],competencies[i].haschildren=!1,parent.children[parent.children.length]=competencies[i],addCompetencyChildren(competencies[i],competencies))}var i,comp,tree=[];for(i=0;i<competencies.length;i++)"0"==(comp=competencies[i]).parentid&&(comp.children=[],comp.haschildren=0,tree[tree.length]=comp,addCompetencyChildren(comp,competencies));self._competencies=tree})).fail(Notification.exception)},Picker.prototype._find=function(selector){return $(this._popup.getContent()).find(selector)},Picker.prototype._getFramework=function(fid){var frm;return $.each(this._frameworks,(function(i,f){f.id!=fid||(frm=f)})),frm},Picker.prototype._loadCompetencies=function(){return this._fetchCompetencies(this._frameworkId,this._searchText)},Picker.prototype._loadFrameworks=function(){var self=this;return self._frameworks.length>0?$.when():(self._singleFramework?Ajax.call([{methodname:"core_competency_read_competency_framework",args:{id:this._frameworkId}}])[0].then((function(framework){return[framework]})):Ajax.call([{methodname:"core_competency_list_competency_frameworks",args:{sort:"shortname",context:{contextid:self._pageContextId},includes:self._pageContextIncludes,onlyvisible:self._onlyVisible}}])[0]).done((function(frameworks){self._frameworks=frameworks})).fail(Notification.exception)},Picker.prototype.on=function(type,handler){this._eventNode.on(type,handler)},Picker.prototype._preRender=function(){var self=this;return self._loadFrameworks().then((function(){return!self._frameworkId&&self._frameworks.length>0&&(self._frameworkId=self._frameworks[0].id),self._frameworkId?self._loadCompetencies():(self._frameworks=[],$.when())}))},Picker.prototype._refresh=function(){var self=this;return self._render().then((function(html){self._find('[data-region="competencylinktree"]').replaceWith(html),self._afterRender()}))},Picker.prototype._render=function(){var self=this;return self._preRender().then((function(){self._singleFramework||$.each(self._frameworks,(function(i,framework){framework.id==self._frameworkId?framework.selected=!0:framework.selected=!1}));var context={competencies:self._competencies,framework:self._getFramework(self._frameworkId),frameworks:self._frameworks,search:self._searchText,singleFramework:self._singleFramework};return Templates.render("tool_lp/competency_picker",context)}))},Picker.prototype._reset=function(){this._competencies=[],this._disallowedCompetencyIDs=[],this._popup=null,this._searchText="",this._selectedCompetencies=[]},Picker.prototype.setDisallowedCompetencyIDs=function(ids){this._disallowedCompetencyIDs=ids},Picker.prototype._trigger=function(type,data){this._eventNode.trigger(type,[data])},Picker})); /** * Competency picker from user plans. * * To handle 'save' events use: picker.on('save'). * * This will receive a object with either a single 'competencyId', or an array in 'competencyIds' * depending on the value of multiSelect. * * @module tool_lp/competencypicker_user_plans * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencypicker_user_plans",["jquery","core/notification","core/ajax","core/templates","core/str","tool_lp/tree","tool_lp/competencypicker"],(function($,Notification,Ajax,Templates,Str,Tree,PickerBase){var Picker=function(userId,singlePlan,multiSelect){PickerBase.prototype.constructor.apply(this,[1,!1,"self",multiSelect]),this._userId=userId,this._plans=[],singlePlan&&(this._planId=singlePlan,this._singlePlan=!0)};return(Picker.prototype=Object.create(PickerBase.prototype))._plans=null,Picker.prototype._planId=null,Picker.prototype._singlePlan=!1,Picker.prototype._userId=null,Picker.prototype._afterRender=function(){var self=this;PickerBase.prototype._afterRender.apply(self,arguments),self._singlePlan||self._find('[data-action="chooseplan"]').change((function(e){self._planId=$(e.target).val(),self._loadCompetencies().then(self._refresh.bind(self)).catch(Notification.exception)}))},Picker.prototype._fetchCompetencies=function(planId,searchText){var self=this;return Ajax.call([{methodname:"core_competency_list_plan_competencies",args:{id:planId}}])[0].done((function(competencies){var i,comp,tree=[];for(i=0;i<competencies.length;i++)(comp=competencies[i].competency).shortname.toLowerCase().indexOf(searchText.toLowerCase())<0||(comp.children=[],comp.haschildren=0,tree.push(comp));self._competencies=tree})).fail(Notification.exception)},Picker.prototype._getPlan=function(id){var plan;return $.each(this._plans,(function(i,f){f.id!=id||(plan=f)})),plan},Picker.prototype._loadCompetencies=function(){return this._fetchCompetencies(this._planId,this._searchText)},Picker.prototype._loadPlans=function(){var self=this;return self._plans.length>0?$.when():(self._singlePlan?Ajax.call([{methodname:"core_competency_read_plan",args:{id:this._planId}}])[0].then((function(plan){return[plan]})):Ajax.call([{methodname:"core_competency_list_user_plans",args:{userid:self._userId}}])[0]).done((function(plans){self._plans=plans})).fail(Notification.exception)},Picker.prototype._preRender=function(){var self=this;return self._loadPlans().then((function(){return!self._planId&&self._plans.length>0&&(self._planId=self._plans[0].id),self._planId?self._loadCompetencies():(self._plans=[],$.when())}))},Picker.prototype._render=function(){var self=this;return self._preRender().then((function(){self._singlePlan||$.each(self._plans,(function(i,plan){plan.id==self._planId?plan.selected=!0:plan.selected=!1}));var context={competencies:self._competencies,plan:self._getPlan(self._planId),plans:self._plans,search:self._searchText,singlePlan:self._singlePlan};return Templates.render("tool_lp/competency_picker_user_plans",context)}))},Picker})); /** * Competency rule config. * * @module tool_lp/competencyruleconfig * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencyruleconfig",["jquery","core/notification","core/templates","tool_lp/dialogue","tool_lp/competency_outcomes","core/str"],(function($,Notification,Templates,Dialogue,Outcomes,Str){var RuleConfig=function(tree,rulesModules){this._eventNode=$("<div></div>"),this._tree=tree,this._rulesModules=rulesModules,this._setUp()};return RuleConfig.prototype._competency=null,RuleConfig.prototype._eventNode=null,RuleConfig.prototype._outcomesOption=null,RuleConfig.prototype._popup=null,RuleConfig.prototype._ready=null,RuleConfig.prototype._rules=null,RuleConfig.prototype._rulesModules=null,RuleConfig.prototype._tree=null,RuleConfig.prototype._afterChange=function(){this._isValid()?this._find('[data-action="save"]').prop("disabled",!1):this._find('[data-action="save"]').prop("disabled",!0)},RuleConfig.prototype._afterRuleConfigChange=function(e,rule){rule==this._getRule()&&this._afterChange()},RuleConfig.prototype._afterRender=function(){var self=this;self._find('[name="outcome"]').on("change",(function(){self._switchedOutcome()})).trigger("change"),self._find('[name="rule"]').on("change",(function(){self._switchedRule()})).trigger("change"),self._find('[data-action="save"]').on("click",(function(){self._trigger("save",self._getConfig()),self.close()})),self._find('[data-action="cancel"]').on("click",(function(){self.close()}))},RuleConfig.prototype.canBeConfigured=function(){var can=!1;return $.each(this._rules,(function(index,rule){rule.canConfig()&&(can=!0)})),can},RuleConfig.prototype.close=function(){this._popup.close(),this._popup=null},RuleConfig.prototype.display=function(){var self=this;return!!self._competency&&$.when(Str.get_string("competencyrule","tool_lp"),self._render()).then((function(title,render){self._popup=new Dialogue(title,render[0],self._afterRender.bind(self),null,!1,"515px")})).fail(Notification.exception)},RuleConfig.prototype._find=function(selector){return $(this._popup.getContent()).find(selector)},RuleConfig.prototype._getApplicableOutcomesOptions=function(){var self=this,options=[];return $.each(self._outcomesOption,(function(index,outcome){options.push({code:outcome.code,name:outcome.name,selected:outcome.code==self._competency.ruleoutcome})})),options},RuleConfig.prototype._getApplicableRulesOptions=function(){var self=this,options=[];return $.each(self._rules,(function(index,rule){rule.canConfig()&&options.push({name:self._getRuleName(rule.getType()),type:rule.getType(),selected:rule.getType()==self._competency.ruletype})})),options},RuleConfig.prototype._getConfig=function(){var rule=this._getRule();return{ruletype:rule?rule.getType():null,ruleconfig:rule?rule.getConfig():null,ruleoutcome:this._getOutcome()}},RuleConfig.prototype._getOutcome=function(){return this._find('[name="outcome"]').val()},RuleConfig.prototype._getRule=function(){var result,type=this._find('[name="rule"]').val();return $.each(this._rules,(function(index,rule){rule.getType()!=type||(result=rule)})),result},RuleConfig.prototype._getRuleName=function(type){var name;return $.each(this._rulesModules,(function(index,modInfo){modInfo.type!=type||(name=modInfo.name)})),name},RuleConfig.prototype._initOutcomes=function(){var self=this;return Outcomes.getAll().then((function(outcomes){self._outcomesOption=outcomes}))},RuleConfig.prototype._initRules=function(){var self=this,promises=[];return $.each(self._rules,(function(index,rule){var promise=rule.init().then((function(){rule.setTargetCompetency(self._competency),rule.on("change",self._afterRuleConfigChange.bind(self))}),(function(){return self._rules.splice(index,1),$.when()}));promises.push(promise)})),$.when.apply($.when,promises)},RuleConfig.prototype._isValid=function(){var outcome=this._getOutcome(),rule=this._getRule();return outcome==Outcomes.NONE||!!rule&&rule.isValid()},RuleConfig.prototype.on=function(type,handler){this._eventNode.on(type,handler)},RuleConfig.prototype._preRender=function(){return this.ready()},RuleConfig.prototype.ready=function(){return this._ready.promise()},RuleConfig.prototype._render=function(){var self=this;return this._preRender().then((function(){var config;self.canBeConfigured()?((config={}).outcomes=self._getApplicableOutcomesOptions(),config.rules=self._getApplicableRulesOptions()):config=!1;var context={competencyshortname:self._competency.shortname,config:config};return Templates.render("tool_lp/competency_rule_config",context)}))},RuleConfig.prototype.setTargetCompetencyId=function(competencyId){var self=this;self._competency=self._tree.getCompetency(competencyId),$.each(self._rules,(function(index,rule){rule.setTargetCompetency(self._competency)}))},RuleConfig.prototype._setUp=function(){var self=this,promises=[],modules=[];self._ready=$.Deferred(),self._rules=[],$.each(self._rulesModules,(function(index,rule){modules.push(rule.amd)})),require(modules,(function(){$.each(arguments,(function(index,Module){var rule=new Module(self._tree);self._rules.push(rule)})),promises.push(self._initRules()),promises.push(self._initOutcomes()),$.when.apply($.when,promises).always((function(){self._ready.resolve()}))}))},RuleConfig.prototype._switchedOutcome=function(){if(this._getOutcome()==Outcomes.NONE)return this._find('[data-region="rule-type"]').hide().find('[name="rule"]').val(-1),this._find('[data-region="rule-config"]').empty().hide(),void this._afterChange();this._find('[data-region="rule-type"]').show(),this._find('[data-region="rule-config"]').show(),this._afterChange()},RuleConfig.prototype._switchedRule=function(){var self=this,container=self._find('[data-region="rule-config"]'),rule=self._getRule();if(!rule)return container.empty().hide(),void self._afterChange();rule.injectTemplate(container).then((function(){container.show()})).always((function(){self._afterChange()})).catch((function(){container.empty().hide()}))},RuleConfig.prototype._trigger=function(type,data){this._eventNode.trigger(type,[data])},RuleConfig})); /** * Wrapper for the YUI M.core.notification class. Allows us to * use the YUI version in AMD code until it is replaced. * * @module tool_lp/dialogue * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/dialogue",["core/yui"],(function(Y){var dialogue=function(title,content,afterShow,afterHide,wide,height){M.util.js_pending("tool_lp/dialogue:dialogue"),this.yuiDialogue=null;var parent=this;void 0===wide&&(wide=!1),Y.use("moodle-core-notification","timers",(function(){var width="480px";wide&&(width="800px"),height||(height="auto"),parent.yuiDialogue=new M.core.dialogue({headerContent:title,bodyContent:content,draggable:!0,visible:!1,center:!0,modal:!0,width:width,height:height}),parent.yuiDialogue.before("visibleChange",(function(){M.util.js_pending("tool_lp/dialogue:before:visibleChange")})),parent.yuiDialogue.after("visibleChange",(function(e){e.newVal?void 0!==afterShow?Y.soon((function(){afterShow(parent),parent.yuiDialogue.centerDialogue(),M.util.js_complete("tool_lp/dialogue:before:visibleChange")})):M.util.js_complete("tool_lp/dialogue:before:visibleChange"):void 0!==afterHide?Y.soon((function(){afterHide(parent),M.util.js_complete("tool_lp/dialogue:before:visibleChange")})):M.util.js_complete("tool_lp/dialogue:before:visibleChange")})),parent.yuiDialogue.show(),M.util.js_complete("tool_lp/dialogue:dialogue")}))};return dialogue.prototype.close=function(){this.yuiDialogue.hide(),this.yuiDialogue.destroy()},dialogue.prototype.getContent=function(){return this.yuiDialogue.bodyNode.getDOMNode()},dialogue})); /** * Drag and drop reorder via HTML5. * * @module tool_lp/dragdrop-reorder * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/dragdrop-reorder",["core/str","core/yui"],(function(str,Y){var dragDropInstance=null,proxyCallback=function(e){var dragNode=e.drag.get("node"),dropNode=e.drop.get("node");this.callback(dragNode.getDOMNode(),dropNode.getDOMNode())};return{dragdrop:function(group,dragHandleText,sameNodeText,parentNodeText,sameNodeClass,parentNodeClass,dragHandleInsertClass,callback){str.get_strings([{key:"emptydragdropregion",component:"moodle"},{key:"movecontent",component:"moodle"},{key:"tocontent",component:"moodle"}]).done((function(){Y.use("moodle-tool_lp-dragdrop-reorder",(function(){var context={callback:callback};dragDropInstance&&dragDropInstance.destroy(),dragDropInstance=M.tool_lp.dragdrop_reorder({group:group,dragHandleText:dragHandleText,sameNodeText:sameNodeText,parentNodeText:parentNodeText,sameNodeClass:sameNodeClass,parentNodeClass:parentNodeClass,dragHandleInsertClass:dragHandleInsertClass,callback:Y.bind(proxyCallback,context)})}))}))}}})); /** * Event base javascript module. * * @module tool_lp/event_base * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/event_base",["jquery"],(function($){var Base=function(){this._eventNode=$("<div></div>")};return Base.prototype._eventNode=null,Base.prototype.on=function(type,handler){this._eventNode.on(type,handler)},Base.prototype._trigger=function(type,data){this._eventNode.trigger(type,[data])},Base})); /** * Evidence delete. * * @module tool_lp/evidence_delete * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/evidence_delete",["jquery","core/notification","core/ajax","core/str","core/log"],(function($,Notification,Ajax,Str,Log){var selectors={};return{register:function(triggerSelector,containerSelector){void 0===selectors[triggerSelector]&&(selectors[triggerSelector]=$("body").delegate(triggerSelector,"click",(function(e){var parent=$(e.currentTarget).parents(containerSelector);if(!parent.length||parent.length>1)Log.error("None or too many evidence container were found.");else{var evidenceId=parent.data("id");evidenceId?(e.preventDefault(),e.stopPropagation(),Str.get_strings([{key:"confirm",component:"moodle"},{key:"areyousure",component:"moodle"},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){Notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){Ajax.call([{methodname:"core_competency_delete_evidence",args:{id:evidenceId}}])[0].then((function(){parent.remove()})).fail(Notification.exception)}))})).fail(Notification.exception)):Log.error("Evidence ID was not found.")}})))}}})); /** * User selector module. * * @module tool_lp/form-user-selector * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/form-user-selector",["jquery","core/ajax","core/templates"],(function($,Ajax,Templates){return{processResults:function(selector,results){var users=[];return $.each(results,(function(index,user){users.push({value:user.id,label:user._label})})),users},transport:function(selector,query,success,failure){var capability=$(selector).data("capability");void 0===capability&&(capability=""),Ajax.call([{methodname:"tool_lp_search_users",args:{query:query,capability:capability}}])[0].then((function(results){var promises=[],i=0;return $.each(results.users,(function(index,user){var ctx=user,identity=[];$.each(["idnumber","email","phone1","phone2","department","institution"],(function(i,k){void 0!==user[k]&&""!==user[k]&&(ctx.hasidentity=!0,identity.push(user[k]))})),ctx.identity=identity.join(", "),promises.push(Templates.render("tool_lp/form-user-selector-suggestion",ctx))})),$.when.apply($.when,promises).then((function(){var args=arguments;$.each(results.users,(function(index,user){user._label=args[i],i++})),success(results.users)}))})).catch(failure)}}})); /** * Badge select competency actions * * @module tool_lp/form_competency_element * @copyright 2019 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/form_competency_element",["jquery","tool_lp/competencypicker","core/ajax","core/notification","core/templates"],(function($,Picker,Ajax,Notification,Templates){var pickerInstance=null,pageContextId=1,renderCompetencies=function(){var currentCompetencies=$('[data-action="competencies"]').val(),requests=[],i=0;if(""!=currentCompetencies)for(currentCompetencies=currentCompetencies.split(","),i=0;i<currentCompetencies.length;i++)requests[requests.length]={methodname:"core_competency_read_competency",args:{id:currentCompetencies[i]}};return $.when.apply($,Ajax.call(requests,!1)).then((function(){var i=0,competencies=[];for(i=0;i<arguments.length;i++)competencies[i]=arguments[i];var context={competencies:competencies};return Templates.render("tool_lp/form_competency_list",context)})).then((function(html,js){return Templates.replaceNode($('[data-region="competencies"]'),html,js),!0})).fail(Notification.exception),!0},unpickCompetenciesHandler=function(e){var i,currentCompetencies=$('[data-action="competencies"]').val().split(","),newCompetencies=[],toRemove=$(e.currentTarget).data("id");for(i=0;i<currentCompetencies.length;i++)currentCompetencies[i]!=toRemove&&(newCompetencies[newCompetencies.length]=currentCompetencies[i]);return $('[data-action="competencies"]').val(newCompetencies.join(",")),renderCompetencies()},pickCompetenciesHandler=function(){var currentCompetencies=$('[data-action="competencies"]').val().split(",");pickerInstance||(pickerInstance=new Picker(pageContextId,!1,"parents",!0)).on("save",(function(e,data){var before=$('[data-action="competencies"]').val(),compIds=data.competencyIds;""!=before&&(compIds=compIds.concat(before.split(",")));var value=compIds.join(",");return $('[data-action="competencies"]').val(value),renderCompetencies()})),pickerInstance.setDisallowedCompetencyIDs(currentCompetencies),pickerInstance.display()};return{init:function(contextId){pageContextId=contextId,renderCompetencies(),$('[data-action="select-competencies"]').on("click",pickCompetenciesHandler),$("body").on("click",'[data-action="deselect-competency"]',unpickCompetenciesHandler)}}})); /** * Competency frameworks actions via ajax. * * @module tool_lp/frameworkactions * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/frameworkactions",["jquery","core/templates","core/ajax","core/notification","core/str"],(function($,templates,ajax,notification,str){var pagecontextid=0,frameworkid=0,updatePage=function(newhtml,newjs){$('[data-region="managecompetencies"]').replaceWith(newhtml),templates.runTemplateJS(newjs)},reloadList=function(context){templates.render("tool_lp/manage_competency_frameworks_page",context).done(updatePage).fail(notification.exception)},doDelete=function(){var requests=ajax.call([{methodname:"core_competency_delete_competency_framework",args:{id:frameworkid}},{methodname:"tool_lp_data_for_competency_frameworks_manage_page",args:{pagecontext:{contextid:pagecontextid}}}]);requests[0].done((function(success){!1===success&&ajax.call([{methodname:"core_competency_read_competency_framework",args:{id:frameworkid}}])[0].done((function(framework){str.get_strings([{key:"frameworkcannotbedeleted",component:"tool_lp",param:framework.shortname},{key:"cancel",component:"moodle"}]).done((function(strings){notification.alert(null,strings[0])})).fail(notification.exception)}))})).fail(notification.exception),requests[1].done(reloadList).fail(notification.exception)};return{deleteHandler:function(e){e.preventDefault();var id=$(this).attr("data-frameworkid");frameworkid=id,ajax.call([{methodname:"core_competency_read_competency_framework",args:{id:frameworkid}}])[0].done((function(framework){str.get_strings([{key:"confirm",component:"moodle"},{key:"deletecompetencyframework",component:"tool_lp",param:framework.shortname},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],doDelete)})).fail(notification.exception)})).fail(notification.exception)},duplicateHandler:function(e){e.preventDefault(),frameworkid=$(this).attr("data-frameworkid"),ajax.call([{methodname:"core_competency_duplicate_competency_framework",args:{id:frameworkid}},{methodname:"tool_lp_data_for_competency_frameworks_manage_page",args:{pagecontext:{contextid:pagecontextid}}}])[1].done(reloadList).fail(notification.exception)},init:function(contextid){pagecontextid=contextid}}})); /** * Frameworks datasource. * * This module is compatible with core/form-autocomplete. * * @module tool_lp/frameworks_datasource * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/frameworks_datasource",["jquery","core/ajax","core/notification"],(function($,Ajax,Notification){return{list:function(contextId,options){var args={context:{contextid:contextId}};return $.extend(args,void 0===options?{}:options),Ajax.call([{methodname:"core_competency_list_competency_frameworks",args:args}])[0]},processResults:function(selector,results){var options=[];return $.each(results,(function(index,data){options.push({value:data.id,label:data.shortname+" "+data.idnumber})})),options},transport:function(selector,query,callback){var el=$(selector),contextId=el.data("contextid"),onlyVisible=el.data("onlyvisible");if(!contextId)throw new Error("The attribute data-contextid is required on "+selector);this.list(contextId,{query:query,onlyvisible:onlyVisible}).then(callback).catch(Notification.exception)}}})); /** * Grade dialogue. * * @module tool_lp/grade_dialogue * @copyright 2016 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/grade_dialogue",["jquery","core/notification","core/templates","tool_lp/dialogue","tool_lp/event_base","core/str"],(function($,Notification,Templates,Dialogue,EventBase,Str){var Grade=function(ratingOptions){EventBase.prototype.constructor.apply(this,[]),this._ratingOptions=ratingOptions};return(Grade.prototype=Object.create(EventBase.prototype))._popup=null,Grade.prototype._ratingOptions=null,Grade.prototype._afterRender=function(){var btnRate=this._find('[data-action="rate"]'),lstRating=this._find('[name="rating"]'),txtComment=this._find('[name="comment"]');this._find('[data-action="cancel"]').click(function(e){e.preventDefault(),this._trigger("cancelled"),this.close()}.bind(this)),lstRating.change((function(){$(this).val()?btnRate.prop("disabled",!1):btnRate.prop("disabled",!0)})).change(),btnRate.click(function(e){e.preventDefault();var val=lstRating.val();val&&(this._trigger("rated",{rating:val,note:txtComment.val()}),this.close())}.bind(this))},Grade.prototype.close=function(){this._popup.close(),this._popup=null},Grade.prototype.display=function(){return M.util.js_pending("tool_lp/grade_dialogue:display"),$.when(Str.get_string("rate","tool_lp"),this._render()).then(function(title,templateResult){return this._popup=new Dialogue(title,templateResult[0],function(){this._afterRender(),M.util.js_complete("tool_lp/grade_dialogue:display")}.bind(this)),this._popup}.bind(this)).catch(Notification.exception)},Grade.prototype._find=function(selector){return $(this._popup.getContent()).find(selector)},Grade.prototype._render=function(){var context={cangrade:this._canGrade,ratings:this._ratingOptions};return Templates.render("tool_lp/competency_grader",context)},Grade})); /** * Module to enable inline editing of a comptency grade. * * @module tool_lp/grade_user_competency_inline * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/grade_user_competency_inline",["jquery","core/notification","core/ajax","core/log","tool_lp/grade_dialogue","tool_lp/event_base","tool_lp/scalevalues"],(function($,notification,ajax,log,GradeDialogue,EventBase,ScaleValues){var InlineEditor=function(selector,scaleId,competencyId,userId,planId,courseId,chooseStr){EventBase.prototype.constructor.apply(this,[]);var trigger=$(selector);if(!trigger.length)throw new Error("Could not find the trigger");this._scaleId=scaleId,this._competencyId=competencyId,this._userId=userId,this._planId=planId,this._courseId=courseId,this._chooseStr=chooseStr,this._setUp(),trigger.click(function(e){e.preventDefault(),this._dialogue.display()}.bind(this)),this._planId?(this._methodName="core_competency_grade_competency_in_plan",this._args={competencyid:this._competencyId,planid:this._planId}):this._courseId?(this._methodName="core_competency_grade_competency_in_course",this._args={competencyid:this._competencyId,courseid:this._courseId,userid:this._userId}):(this._methodName="core_competency_grade_competency",this._args={userid:this._userId,competencyid:this._competencyId})};return(InlineEditor.prototype=Object.create(EventBase.prototype))._setUp=function(){var options=[],self=this;M.util.js_pending("tool_lp/grade_user_competency_inline:_setUp"),ScaleValues.get_values(self._scaleId).then((function(scalevalues){options.push({value:"",name:self._chooseStr});for(var i=0;i<scalevalues.length;i++){var optionConfig=scalevalues[i];options.push({value:optionConfig.id,name:optionConfig.name})}return options})).then((function(options){return new GradeDialogue(options)})).then((function(dialogue){return dialogue.on("rated",(function(e,data){var args=self._args;args.grade=data.rating,args.note=data.note,ajax.call([{methodname:self._methodName,args:args,done:function(evidence){self._trigger("competencyupdated",{args:args,evidence:evidence})},fail:notification.exception}])})),dialogue})).then((function(dialogue){self._dialogue=dialogue,M.util.js_complete("tool_lp/grade_user_competency_inline:_setUp")})).fail(notification.exception)},InlineEditor.prototype._scaleId=null,InlineEditor.prototype._competencyId=null,InlineEditor.prototype._userId=null,InlineEditor.prototype._planId=null,InlineEditor.prototype._courseId=null,InlineEditor.prototype._chooseStr=null,InlineEditor.prototype._dialogue=null,InlineEditor})); /** * Aria menubar functionality. Enhances a simple nested list structure into a full aria widget. * Based on the open ajax example: http://oaa-accessibility.org/example/26/ * * @module tool_lp/menubar * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/menubar",["jquery"],(function($){var documentClickHandlerRegistered=!1,menuActive=!1,closeAllSubMenus=function(){$(".tool-lp-menu .tool-lp-sub-menu").attr("aria-hidden","true"),menuActive=!1},Menubar=function(menuRoot,handlers){this.menuRoot=menuRoot,this.handlers=handlers,this.rootMenus=this.menuRoot.children("li"),this.subMenus=this.rootMenus.children("ul"),this.subMenuItems=this.subMenus.children("li"),this.allItems=this.rootMenus.add(this.subMenuItems),this.activeItem=null,this.isChildOpen=!1,this.keys={tab:9,enter:13,esc:27,space:32,left:37,up:38,right:39,down:40},this.addAriaAttributes(),this.addEventListeners()};return Menubar.prototype.openSubMenu=function(menu){this.setOpenDirection(),closeAllSubMenus(),menu.attr("aria-hidden","false"),menuActive=!0},Menubar.prototype.addEventListeners=function(){var currentThis=this;!1===documentClickHandlerRegistered&&($(document).click((function(){menuActive&&closeAllSubMenus()})),documentClickHandlerRegistered=!0),this.subMenuItems.mouseenter((function(){return $(this).addClass("menu-hover"),!0})),this.subMenuItems.mouseout((function(){return $(this).removeClass("menu-hover"),!0})),this.allItems.click((function(e){return currentThis.handleClick($(this),e)})),this.allItems.keydown((function(e){return currentThis.handleKeyDown($(this),e)})),this.allItems.focus((function(){return currentThis.handleFocus($(this))})),this.allItems.blur((function(){return currentThis.handleBlur($(this))}))},Menubar.prototype.handleClick=function(item,e){if(e.stopPropagation(),item.parent().is(".tool-lp-menu"))"true"==item.children("ul").first().attr("aria-hidden")?this.openSubMenu(item.children("ul").first()):item.children("ul").first().attr("aria-hidden","true");else{this.allItems.removeClass("menu-hover menu-focus"),this.activeItem=null,this.menuRoot.find("ul").not(".root-level").attr("aria-hidden","true");var anchor=item.find("a").first(),clickEvent=new $.Event("click");clickEvent.target=anchor;var eventHandled=!1;this.handlers&&$.each(this.handlers,(function(selector,handler){if(!eventHandled&&item.find(selector).length>0){var callable=$.proxy(handler,anchor);eventHandled=!1===callable(clickEvent)||clickEvent.isDefaultPrevented()}})),eventHandled||"#"===anchor.attr("href")||(window.location.href=anchor.attr("href"))}return!1},Menubar.prototype.handleFocus=function(item){if(null===this.activeItem)this.activeItem=item;else if(item[0]!=this.activeItem[0])return!0;var parentItems=this.activeItem.parentsUntil("ul.tool-lp-menu").filter("li");(this.allItems.removeClass("menu-focus"),this.activeItem.addClass("menu-focus"),parentItems.addClass("menu-focus"),!0===this.isChildOpen)&&(item.parent().is(".tool-lp-menu")&&"true"==item.attr("aria-haspopup")&&this.openSubMenu(item.children("ul").first()));return!0},Menubar.prototype.handleBlur=function(item){return item.removeClass("menu-focus"),!0},Menubar.prototype.setOpenDirection=function(){var pos=this.menuRoot.offset(),isRTL=$(document.body).hasClass("dir-rtl"),heightmenuRoot=this.rootMenus.outerHeight(),widthmenuRoot=this.rootMenus.outerWidth(),subMenuContainer=this.rootMenus.find("ul.tool-lp-sub-menu");subMenuContainer.css("margin-right",""),subMenuContainer.css("margin-left",""),subMenuContainer.css("margin-top",""),subMenuContainer.attr("aria-hidden",!1);var menuRealWidth=subMenuContainer.outerWidth(),menuRealHeight=subMenuContainer.outerHeight(),margintop=null,marginright=null,marginleft=null;pos.top-$(window).scrollTop()+menuRealHeight>$(window).height()&&(margintop=menuRealHeight+heightmenuRoot,subMenuContainer.css("margin-top","-"+margintop+"px")),isRTL?pos.left-menuRealWidth<0&&(marginright=menuRealWidth-widthmenuRoot,subMenuContainer.css("margin-right","-"+marginright+"px")):pos.left+menuRealWidth>$(window).width()&&(marginleft=menuRealWidth-widthmenuRoot,subMenuContainer.css("margin-left","-"+marginleft+"px")),this.menuRoot.addClass("tool-lp-menu-open-left")},Menubar.prototype.handleKeyDown=function(item,e){if(e.altKey||e.ctrlKey)return!0;switch(e.keyCode){case this.keys.tab:this.menuRoot.find("ul").attr("aria-hidden","true"),this.allItems.removeClass("menu-focus"),this.activeItem=null,this.isChildOpen=!1;break;case this.keys.esc:var itemUL=item.parent();return itemUL.is(".tool-lp-menu")?item.children("ul").first().attr("aria-hidden","true"):(this.activeItem=itemUL.parent(),this.isChildOpen=!1,this.activeItem.focus(),itemUL.attr("aria-hidden","true")),e.stopPropagation(),!1;case this.keys.enter:case this.keys.space:return this.handleClick(item,e);case this.keys.left:return this.activeItem=this.moveToPrevious(item),this.activeItem.focus(),e.stopPropagation(),!1;case this.keys.right:return this.activeItem=this.moveToNext(item),this.activeItem.focus(),e.stopPropagation(),!1;case this.keys.up:return this.activeItem=this.moveUp(item),this.activeItem.focus(),e.stopPropagation(),!1;case this.keys.down:return this.activeItem=this.moveDown(item),this.activeItem.focus(),e.stopPropagation(),!1}return!0},Menubar.prototype.moveToNext=function(item){var itemUL=item.parent(),menuItems=itemUL.children("li"),menuNum=menuItems.length,menuIndex=menuItems.index(item),newItem=null,childMenu=null;if(itemUL.is(".tool-lp-menu"))newItem=menuIndex<menuNum-1?item.next():menuItems.first(),"true"==item.attr("aria-haspopup")&&"false"==(childMenu=item.children("ul").first()).attr("aria-hidden")&&(childMenu.attr("aria-hidden","true"),this.isChildOpen=!0),item.removeClass("menu-focus"),"true"===newItem.attr("aria-haspopup")&&!0===this.isChildOpen&&(childMenu=newItem.children("ul").first(),this.openSubMenu(childMenu));else if("true"==item.attr("aria-haspopup"))newItem=(childMenu=item.children("ul").first()).children("li").first(),this.openSubMenu(childMenu);else{var parentMenus=null,rootItem=null;(parentMenus=item.parentsUntil("ul.tool-lp-menu").filter("ul").not(".tool-lp-menu")).attr("aria-hidden","true"),parentMenus.find("li").removeClass("menu-focus"),parentMenus.last().parent().removeClass("menu-focus"),rootItem=parentMenus.last().parent(),(newItem=(menuIndex=this.rootMenus.index(rootItem))<this.rootMenus.length-1?rootItem.next():this.rootMenus.first()).addClass("menu-focus"),"true"==newItem.attr("aria-haspopup")&&(childMenu=newItem.children("ul").first(),newItem=childMenu.children("li").first(),this.openSubMenu(childMenu),this.isChildOpen=!0)}return newItem},Menubar.prototype.moveToPrevious=function(item){var itemUL=item.parent(),menuItems=itemUL.children("li"),menuIndex=menuItems.index(item),newItem=null,childMenu=null;if(itemUL.is(".tool-lp-menu"))newItem=menuIndex>0?item.prev():menuItems.last(),"true"==item.attr("aria-haspopup")&&"false"==(childMenu=item.children("ul").first()).attr("aria-hidden")&&(childMenu.attr("aria-hidden","true"),this.isChildOpen=!0),item.removeClass("menu-focus"),"true"===newItem.attr("aria-haspopup")&&!0===this.isChildOpen&&(childMenu=newItem.children("ul").first(),this.openSubMenu(childMenu));else{var parentLI=itemUL.parent();parentLI.parent().is(".tool-lp-menu")?(itemUL.attr("aria-hidden","true"),item.removeClass("menu-focus"),parentLI.removeClass("menu-focus"),(newItem=(menuIndex=this.rootMenus.index(parentLI))>0?parentLI.prev():this.rootMenus.last()).addClass("menu-focus"),"true"==newItem.attr("aria-haspopup")&&(childMenu=newItem.children("ul").first(),this.openSubMenu(childMenu),this.isChildOpen=!0,newItem=childMenu.children("li").first())):(newItem=itemUL.parent(),itemUL.attr("aria-hidden","true"),item.removeClass("menu-focus"))}return newItem},Menubar.prototype.moveDown=function(item,startChr){var itemUL=item.parent(),menuItems=itemUL.children("li").not(".separator"),menuNum=menuItems.length,menuIndex=menuItems.index(item),newItem=null,newItemUL=null;if(itemUL.is(".tool-lp-menu"))return"true"!=item.attr("aria-haspopup")?item:(newItem=(newItemUL=item.children("ul").first()).children("li").first(),this.openSubMenu(newItemUL),newItem);if(startChr){var match=!1,curNdx=menuIndex+1;for(curNdx==menuNum&&(curNdx=0);curNdx!=menuIndex;){if(menuItems.eq(curNdx).html().charAt(0).toLowerCase()==startChr){match=!0;break}(curNdx+=1)==menuNum&&(curNdx=0)}return!0===match?(newItem=menuItems.eq(curNdx),item.removeClass("menu-focus"),newItem):item}return newItem=menuIndex<menuNum-1?menuItems.eq(menuIndex+1):menuItems.first(),item.removeClass("menu-focus"),newItem},Menubar.prototype.moveUp=function(item){var itemUL=item.parent(),menuItems=itemUL.children("li").not(".separator"),menuIndex=menuItems.index(item),newItem=null;return itemUL.is(".tool-lp-menu")?item:(newItem=menuIndex>0?menuItems.eq(menuIndex-1):menuItems.last(),item.removeClass("menu-focus"),newItem)},Menubar.prototype.addAriaAttributes=function(){this.menuRoot.attr("role","menubar"),this.rootMenus.attr("role","menuitem"),this.rootMenus.attr("tabindex","0"),this.rootMenus.attr("aria-haspopup","true"),this.subMenus.attr("role","menu"),this.subMenus.attr("aria-hidden","true"),this.subMenuItems.attr("role","menuitem"),this.subMenuItems.attr("tabindex","-1"),this.menuRoot.addClass("tool-lp-menu"),this.allItems.addClass("tool-lp-menu-item"),this.rootMenus.addClass("tool-lp-root-menu"),this.subMenus.addClass("tool-lp-sub-menu"),this.subMenuItems.addClass("dropdown-item")},{enhance:function(selector,handler){$(selector).each((function(index,element){var menuRoot=$(element);!0!==menuRoot.data("menubarEnhanced")&&(new Menubar(menuRoot,handler),menuRoot.data("menubarEnhanced",!0))}))},closeAll:closeAllSubMenus}})); /** * Module to navigation between users in a course. * * @module tool_lp/module_navigation * @copyright 2019 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/module_navigation",["jquery"],(function($){var ModuleNavigation=function(moduleSelector,baseUrl,courseId,moduleId){this._baseUrl=baseUrl,this._moduleId=moduleId,this._courseId=courseId,$(moduleSelector).on("change",this._moduleChanged.bind(this))};return ModuleNavigation.prototype._moduleChanged=function(e){var queryStr="?mod="+$(e.target).val()+"&courseid="+this._courseId;document.location=this._baseUrl+queryStr},ModuleNavigation.prototype._courseId=null,ModuleNavigation.prototype._moduleId=null,ModuleNavigation.prototype._baseUrl=null,ModuleNavigation})); /** * Handle selecting parent competency in competency form. * * @module tool_lp/parentcompetency_form * @copyright 2015 Issam Taboubi <issam.taboubi@umontreal.ca> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/parentcompetency_form",["jquery","core/ajax","core/str","tool_lp/competencypicker","core/templates","core/notification"],(function($,ajax,Str,Picker,Templates,Notification){var ParentCompetencyForm=function(buttonSelector,inputHiddenSelector,staticElementSelector,frameworkId,pageContextId){this.buttonSelector=buttonSelector,this.inputHiddenSelector=inputHiddenSelector,this.staticElementSelector=staticElementSelector,this.frameworkId=frameworkId,this.pageContextId=pageContextId,this.registerEvents()};return ParentCompetencyForm.prototype.buttonSelector=null,ParentCompetencyForm.prototype.inputHiddenSelector=null,ParentCompetencyForm.prototype.staticElementSelector=null,ParentCompetencyForm.prototype.frameworkId=null,ParentCompetencyForm.prototype.pageContextId=null,ParentCompetencyForm.prototype.setParent=function(data){var self=this;0!==data.competencyId?ajax.call([{methodname:"core_competency_read_competency",args:{id:data.competencyId}}])[0].done((function(competency){$(self.staticElementSelector).html(competency.shortname),$(self.inputHiddenSelector).val(competency.id)})).fail(Notification.exception):Str.get_string("competencyframeworkroot","tool_lp").then((function(rootframework){$(self.staticElementSelector).html(rootframework),$(self.inputHiddenSelector).val(data.competencyId)})).fail(Notification.exception)},ParentCompetencyForm.prototype.registerEvents=function(){var self=this;$(self.buttonSelector).on("click",(function(e){e.preventDefault();var picker=new Picker(self.pageContextId,self.frameworkId,"self",!1);picker._render=function(){var self=this;return self._preRender().then((function(){var context={competencies:self._competencies,framework:self._getFramework(self._frameworkId),frameworks:self._frameworks,search:self._searchText,singleFramework:self._singleFramework};return Templates.render("tool_lp/competency_picker_competencyform",context)}))},picker.on("save",(function(e,data){self.setParent(data)})),picker.display()}))},{init:function(buttonSelector,inputSelector,staticElementSelector,frameworkId,pageContextId){new ParentCompetencyForm(buttonSelector,inputSelector,staticElementSelector,frameworkId,pageContextId)}}})); /** * Plan actions via ajax. * * @module tool_lp/planactions * @copyright 2015 David Monllao * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/planactions",["jquery","core/templates","core/ajax","core/notification","core/str","tool_lp/menubar","tool_lp/dialogue"],(function($,templates,ajax,notification,str,Menubar,Dialogue){var PlanActions=function(type){if(this._type=type,"plan"===type)this._region='[data-region="plan-page"]',this._planNode='[data-region="plan-page"]',this._template="tool_lp/plan_page",this._contextMethod="tool_lp_data_for_plan_page";else{if("plans"!==type)throw new TypeError("Unexpected type.");this._region='[data-region="plans"]',this._planNode='[data-region="plan-node"]',this._template="tool_lp/plans_page",this._contextMethod="tool_lp_data_for_plans_page"}};return PlanActions.prototype._contextMethod=null,PlanActions.prototype._planNode=null,PlanActions.prototype._region=null,PlanActions.prototype._template=null,PlanActions.prototype._type=null,PlanActions.prototype._getContextArgs=function(planData){var args={};return"plan"===this._type?args={planid:planData.id}:"plans"===this._type&&(args={userid:planData.userid}),args},PlanActions.prototype.refresh=function(selector){var planData=this._findPlanData($(selector));this._callAndRefresh([],planData)},PlanActions.prototype._renderView=function(context){var self=this;return templates.render(self._template,context).then((function(newhtml,newjs){$(self._region).replaceWith(newhtml),templates.runTemplateJS(newjs)}))},PlanActions.prototype._callAndRefresh=function(calls,planData){var callKey="tool_lp/planactions:_callAndRefresh-"+Math.floor(Math.random()*Math.floor(1e3));M.util.js_pending(callKey);var self=this;return calls.push({methodname:self._contextMethod,args:self._getContextArgs(planData)}),$.when.apply($,ajax.call(calls)).then((function(){return self._renderView(arguments[arguments.length-1])})).fail(notification.exception).always((function(){return M.util.js_complete(callKey)}))},PlanActions.prototype._doDelete=function(planData){var calls=[{methodname:"core_competency_delete_plan",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.deletePlan=function(planData){var self=this;ajax.call([{methodname:"core_competency_read_plan",args:{id:planData.id}}])[0].done((function(plan){str.get_strings([{key:"confirm",component:"moodle"},{key:"deleteplan",component:"tool_lp",param:plan.name},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doDelete(planData)}))})).fail(notification.exception)})).fail(notification.exception)},PlanActions.prototype._doReopenPlan=function(planData){var calls=[{methodname:"core_competency_reopen_plan",args:{planid:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.reopenPlan=function(planData){var self=this;ajax.call([{methodname:"core_competency_read_plan",args:{id:planData.id}}])[0].done((function(plan){str.get_strings([{key:"confirm",component:"moodle"},{key:"reopenplanconfirm",component:"tool_lp",param:plan.name},{key:"reopenplan",component:"tool_lp"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doReopenPlan(planData)}))})).fail(notification.exception)})).fail(notification.exception)},PlanActions.prototype._doCompletePlan=function(planData){var calls=[{methodname:"core_competency_complete_plan",args:{planid:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.completePlan=function(planData){var self=this;ajax.call([{methodname:"core_competency_read_plan",args:{id:planData.id}}])[0].done((function(plan){str.get_strings([{key:"confirm",component:"moodle"},{key:"completeplanconfirm",component:"tool_lp",param:plan.name},{key:"completeplan",component:"tool_lp"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doCompletePlan(planData)}))})).fail(notification.exception)})).fail(notification.exception)},PlanActions.prototype._doUnlinkPlan=function(planData){var calls=[{methodname:"core_competency_unlink_plan_from_template",args:{planid:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.unlinkPlan=function(planData){var self=this;ajax.call([{methodname:"core_competency_read_plan",args:{id:planData.id}}])[0].done((function(plan){str.get_strings([{key:"confirm",component:"moodle"},{key:"unlinkplantemplateconfirm",component:"tool_lp",param:plan.name},{key:"unlinkplantemplate",component:"tool_lp"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doUnlinkPlan(planData)}))})).fail(notification.exception)})).fail(notification.exception)},PlanActions.prototype._doRequestReview=function(planData){var calls=[{methodname:"core_competency_plan_request_review",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.requestReview=function(planData){this._doRequestReview(planData)},PlanActions.prototype._doCancelReviewRequest=function(planData){var calls=[{methodname:"core_competency_plan_cancel_review_request",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.cancelReviewRequest=function(planData){this._doCancelReviewRequest(planData)},PlanActions.prototype._doStartReview=function(planData){var calls=[{methodname:"core_competency_plan_start_review",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.startReview=function(planData){this._doStartReview(planData)},PlanActions.prototype._doStopReview=function(planData){var calls=[{methodname:"core_competency_plan_stop_review",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.stopReview=function(planData){this._doStopReview(planData)},PlanActions.prototype._doApprove=function(planData){var calls=[{methodname:"core_competency_approve_plan",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.approve=function(planData){this._doApprove(planData)},PlanActions.prototype._doUnapprove=function(planData){var calls=[{methodname:"core_competency_unapprove_plan",args:{id:planData.id}}];this._callAndRefresh(calls,planData)},PlanActions.prototype.unapprove=function(planData){this._doUnapprove(planData)},PlanActions.prototype._showLinkedCoursesHandler=function(e){e.preventDefault();var competencyid=$(e.target).data("id");ajax.call([{methodname:"tool_lp_list_courses_using_competency",args:{id:competencyid}}])[0].done((function(courses){var context={courses:courses};templates.render("tool_lp/linked_courses_summary",context).done((function(html){str.get_string("linkedcourses","tool_lp").done((function(linkedcourses){new Dialogue(linkedcourses,html)})).fail(notification.exception)})).fail(notification.exception)})).fail(notification.exception)},PlanActions.prototype._eventHandler=function(method,e){e.preventDefault();var data=this._findPlanData($(e.target));this[method](data)},PlanActions.prototype._findPlanData=function(node){var data,parent=node.parentsUntil($(this._region).parent(),this._planNode);if(1!=parent.length)throw new Error("The plan node was not located.");if(void 0===(data=parent.data())||void 0===data.id)throw new Error("Plan data could not be found.");return data},PlanActions.prototype.enhanceMenubar=function(selector){Menubar.enhance(selector,{'[data-action="plan-delete"]':this._eventHandler.bind(this,"deletePlan"),'[data-action="plan-complete"]':this._eventHandler.bind(this,"completePlan"),'[data-action="plan-reopen"]':this._eventHandler.bind(this,"reopenPlan"),'[data-action="plan-unlink"]':this._eventHandler.bind(this,"unlinkPlan"),'[data-action="plan-request-review"]':this._eventHandler.bind(this,"requestReview"),'[data-action="plan-cancel-review-request"]':this._eventHandler.bind(this,"cancelReviewRequest"),'[data-action="plan-start-review"]':this._eventHandler.bind(this,"startReview"),'[data-action="plan-stop-review"]':this._eventHandler.bind(this,"stopReview"),'[data-action="plan-approve"]':this._eventHandler.bind(this,"approve"),'[data-action="plan-unapprove"]':this._eventHandler.bind(this,"unapprove")})},PlanActions.prototype.registerEvents=function(){var wrapper=$(this._region);wrapper.find('[data-action="plan-delete"]').click(this._eventHandler.bind(this,"deletePlan")),wrapper.find('[data-action="plan-complete"]').click(this._eventHandler.bind(this,"completePlan")),wrapper.find('[data-action="plan-reopen"]').click(this._eventHandler.bind(this,"reopenPlan")),wrapper.find('[data-action="plan-unlink"]').click(this._eventHandler.bind(this,"unlinkPlan")),wrapper.find('[data-action="plan-request-review"]').click(this._eventHandler.bind(this,"requestReview")),wrapper.find('[data-action="plan-cancel-review-request"]').click(this._eventHandler.bind(this,"cancelReviewRequest")),wrapper.find('[data-action="plan-start-review"]').click(this._eventHandler.bind(this,"startReview")),wrapper.find('[data-action="plan-stop-review"]').click(this._eventHandler.bind(this,"stopReview")),wrapper.find('[data-action="plan-approve"]').click(this._eventHandler.bind(this,"approve")),wrapper.find('[data-action="plan-unapprove"]').click(this._eventHandler.bind(this,"unapprove")),wrapper.find('[data-action="find-courses-link"]').click(this._showLinkedCoursesHandler.bind(this))},PlanActions})); /** * Handle opening a dialogue to configure scale data. * * @module tool_lp/scaleconfig * @copyright 2015 Adrian Greeve <adrian@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/scaleconfig",["jquery","core/notification","core/templates","core/ajax","tool_lp/dialogue","tool_lp/scalevalues"],(function($,notification,templates,ajax,Dialogue,ModScaleValues){var ScaleConfig=function(selectSelector,inputSelector,triggerSelector){this.selectSelector=selectSelector,this.inputSelector=inputSelector,this.triggerSelector=triggerSelector,this.originalscaleid=$(selectSelector).val(),$(selectSelector).on("change",this.scaleChangeHandler.bind(this)).change(),$(triggerSelector).click(this.showConfig.bind(this))};return ScaleConfig.prototype.selectSelector=null,ScaleConfig.prototype.inputSelector=null,ScaleConfig.prototype.triggerSelector=null,ScaleConfig.prototype.scalevalues=null,ScaleConfig.prototype.originalscaleid=0,ScaleConfig.prototype.scaleid=0,ScaleConfig.prototype.popup=null,ScaleConfig.prototype.showConfig=function(){var self=this;if(this.scaleid=$(this.selectSelector).val(),!(this.scaleid<=0)){var scalename=$(this.selectSelector).find("option:selected").text();this.getScaleValues(this.scaleid).done((function(){var context={scalename:scalename,scales:self.scalevalues};templates.render("tool_lp/scale_configuration_page",context).done((function(html){new Dialogue(scalename,html,self.initScaleConfig.bind(self))})).fail(notification.exception)})).fail(notification.exception)}},ScaleConfig.prototype.retrieveOriginalScaleConfig=function(){var jsonstring=$(this.inputSelector).val();if(""!==jsonstring){var scaleconfiguration=$.parseJSON(jsonstring);if(scaleconfiguration.shift().scaleid===this.originalscaleid)return scaleconfiguration}return""},ScaleConfig.prototype.initScaleConfig=function(popup){this.popup=popup;var body=$(popup.getContent());if(this.originalscaleid===this.scaleid){var currentconfig=this.retrieveOriginalScaleConfig();""!==currentconfig&¤tconfig.forEach((function(value){1===value.scaledefault&&body.find('[data-field="tool_lp_scale_default_'+value.id+'"]').attr("checked",!0),1===value.proficient&&body.find('[data-field="tool_lp_scale_proficient_'+value.id+'"]').attr("checked",!0)}))}body.on("click",'[data-action="close"]',function(){this.setScaleConfig(),popup.close()}.bind(this)),body.on("click",'[data-action="cancel"]',(function(){popup.close()}))},ScaleConfig.prototype.setScaleConfig=function(){var body=$(this.popup.getContent()),data=[{scaleid:this.scaleid}];this.scalevalues.forEach((function(value){var scaledefault=0,proficient=0;body.find('[data-field="tool_lp_scale_default_'+value.id+'"]').is(":checked")&&(scaledefault=1),body.find('[data-field="tool_lp_scale_proficient_'+value.id+'"]').is(":checked")&&(proficient=1),(scaledefault||proficient)&&data.push({id:value.id,scaledefault:scaledefault,proficient:proficient})}));var datastring=JSON.stringify(data);$(this.inputSelector).val(datastring),this.originalscaleid=this.scaleid},ScaleConfig.prototype.getScaleValues=function(scaleid){return ModScaleValues.get_values(scaleid).then(function(values){return this.scalevalues=values,values}.bind(this))},ScaleConfig.prototype.scaleChangeHandler=function(e){$(e.target).val()<=0?$(this.triggerSelector).prop("disabled",!0):$(this.triggerSelector).prop("disabled",!1)},{init:function(selectSelector,inputSelector,triggerSelector){return new ScaleConfig(selectSelector,inputSelector,triggerSelector)}}})); /** * Module to get the scale values. * * @module tool_lp/scalevalues * @copyright 2016 Serge Gauthier * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/scalevalues",["jquery","core/ajax"],(function($,ajax){var localCache=[];return{get_values:function(scaleid){var deferred=$.Deferred();return void 0===localCache[scaleid]?ajax.call([{methodname:"core_competency_get_scale_values",args:{scaleid:scaleid},done:function(scaleinfo){localCache[scaleid]=scaleinfo,deferred.resolve(scaleinfo)},fail:deferred.reject}]):deferred.resolve(localCache[scaleid]),deferred.promise()}}})); /** * Handle actions on learning plan templates via ajax. * * @module tool_lp/templateactions * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/templateactions",["jquery","core/templates","core/ajax","core/notification","core/str","tool_lp/actionselector"],(function($,templates,ajax,notification,str,Actionselector){var pagecontextid=0,templateid=0,deleteplans=!0,updatePage=function(newhtml,newjs){$('[data-region="managetemplates"]').replaceWith(newhtml),templates.runTemplateJS(newjs)},reloadList=function(context){templates.render("tool_lp/manage_templates_page",context).done(updatePage).fail(notification.exception)},doDelete=function(){ajax.call([{methodname:"core_competency_delete_template",args:{id:templateid,deleteplans:deleteplans}},{methodname:"tool_lp_data_for_templates_manage_page",args:{pagecontext:{contextid:pagecontextid}}}])[1].done(reloadList).fail(notification.exception)};return{deleteHandler:function(e){e.preventDefault();var id=$(this).attr("data-templateid");templateid=id,deleteplans=!0;var requests=ajax.call([{methodname:"core_competency_read_template",args:{id:templateid}},{methodname:"core_competency_template_has_related_data",args:{id:templateid}}]);requests[0].done((function(template){requests[1].done((function(templatehasrelateddata){templatehasrelateddata?str.get_strings([{key:"deletetemplate",component:"tool_lp",param:template.shortname},{key:"deletetemplatewithplans",component:"tool_lp"},{key:"deleteplans",component:"tool_lp"},{key:"unlinkplanstemplate",component:"tool_lp"},{key:"confirm",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){var actions=[{text:strings[2],value:"delete"},{text:strings[3],value:"unlink"}],actionselector=new Actionselector(strings[0],strings[1],actions,strings[4],strings[5]);actionselector.display(),actionselector.on("save",(function(e,data){"delete"!=data.action&&(deleteplans=!1),doDelete()}))})).fail(notification.exception):str.get_strings([{key:"confirm",component:"moodle"},{key:"deletetemplate",component:"tool_lp",param:template.shortname},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],doDelete)})).fail(notification.exception)})).fail(notification.exception)})).fail(notification.exception)},duplicateHandler:function(e){e.preventDefault(),templateid=$(this).attr("data-templateid"),ajax.call([{methodname:"core_competency_duplicate_template",args:{id:templateid}},{methodname:"tool_lp_data_for_templates_manage_page",args:{pagecontext:{contextid:pagecontextid}}}])[1].done(reloadList).fail(notification.exception)},init:function(contextid){pagecontextid=contextid}}})); /** * Implement an accessible aria tree widget, from a nested unordered list. * Based on http://oaa-accessibility.org/example/41/ * * To respond to selection changed events - use tree.on("selectionchanged", handler). * The handler will receive an array of nodes, which are the list items that are currently * selected. (Or a single node if multiselect is disabled). * * @module tool_lp/tree * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/tree",["jquery","core/url","core/log"],(function($,url,log){var expandedImage=$('<img alt="" src="'+url.imageUrl("t/expanded")+'"/>'),collapsedImage=$('<img alt="" src="'+url.imageUrl("t/collapsed")+'"/>'),Tree=function(selector,multiSelect){this.treeRoot=$(selector),this.multiSelect=void 0===multiSelect||!0===multiSelect,this.items=this.treeRoot.find("li"),this.expandAll=this.items.length<20,this.parents=this.treeRoot.find("li:has(ul)"),multiSelect&&this.treeRoot.attr("aria-multiselectable","true"),this.items.attr("aria-selected","false"),this.visibleItems=null,this.activeItem=null,this.lastActiveItem=null,this.keys={tab:9,enter:13,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,up:38,right:39,down:40,eight:56,asterisk:106},this.init(),this.bindEventHandlers()};return Tree.prototype.init=function(){this.parents.attr("aria-expanded","true"),this.parents.prepend(expandedImage.clone()),this.items.attr("role","tree-item"),this.items.attr("tabindex","-1"),this.parents.attr("role","group"),this.treeRoot.attr("role","tree"),this.visibleItems=this.treeRoot.find("li");var thisObj=this;this.expandAll||(this.parents.each((function(){thisObj.collapseGroup($(this))})),this.expandGroup(this.parents.first()))},Tree.prototype.expandGroup=function(item){item.children("ul").show().attr("aria-hidden","false"),item.attr("aria-expanded","true"),item.children("img").attr("src",expandedImage.attr("src")),this.visibleItems=this.treeRoot.find("li:visible")},Tree.prototype.collapseGroup=function(item){item.children("ul").hide().attr("aria-hidden","true"),item.attr("aria-expanded","false"),item.children("img").attr("src",collapsedImage.attr("src")),this.visibleItems=this.treeRoot.find("li:visible")},Tree.prototype.toggleGroup=function(item){"true"==item.attr("aria-expanded")?this.collapseGroup(item):this.expandGroup(item)},Tree.prototype.triggerChange=function(){var allSelected=this.items.filter("[aria-selected=true]");this.multiSelect||(allSelected=allSelected.first()),this.treeRoot.trigger("selectionchanged",{selected:allSelected})},Tree.prototype.multiSelectItem=function(item){if(this.multiSelect){if(null!==this.lastActiveItem){for(var lastIndex=this.visibleItems.index(this.lastActiveItem),currentIndex=this.visibleItems.index(this.activeItem);lastIndex<currentIndex;)$(this.visibleItems.get(lastIndex)).attr("aria-selected","true"),lastIndex++;for(;lastIndex>currentIndex;)$(this.visibleItems.get(lastIndex)).attr("aria-selected","true"),lastIndex--}}else this.items.attr("aria-selected","false");item.attr("aria-selected","true"),this.triggerChange()},Tree.prototype.selectItem=function(item){for(var walk=item.parent();"tree"!=walk.attr("role");)"false"==(walk=walk.parent()).attr("aria-expanded")&&this.expandGroup(walk),walk=walk.parent();this.items.attr("aria-selected","false"),item.attr("aria-selected","true"),this.triggerChange()},Tree.prototype.toggleItem=function(item){if(this.multiSelect){var current=item.attr("aria-selected");current="true"===current?"false":"true",item.attr("aria-selected",current),this.triggerChange()}else this.selectItem(item)},Tree.prototype.updateFocus=function(item){this.lastActiveItem=this.activeItem,this.activeItem=item;for(var walk=item.parent();"tree"!=walk.attr("role");)"false"==(walk=walk.parent()).attr("aria-expanded")&&this.expandGroup(walk),walk=walk.parent();this.items.attr("tabindex","-1"),item.attr("tabindex",0)},Tree.prototype.handleKeyDown=function(item,e){var currentIndex=this.visibleItems.index(item),newItem=null,hasKeyModifier=e.shiftKey||e.ctrlKey||e.metaKey||e.altKey,thisObj=this;switch(e.keyCode){case this.keys.home:return(newItem=this.parents.first()).focus(),e.shiftKey?this.multiSelectItem(newItem):hasKeyModifier||this.selectItem(newItem),e.stopPropagation(),!1;case this.keys.end:return(newItem=this.visibleItems.last()).focus(),e.shiftKey?this.multiSelectItem(newItem):hasKeyModifier||this.selectItem(newItem),e.stopPropagation(),!1;case this.keys.enter:case this.keys.space:return e.shiftKey?this.multiSelectItem(item):e.metaKey||e.ctrlKey?this.toggleItem(item):this.selectItem(item),e.stopPropagation(),!1;case this.keys.left:if(item.has("ul")&&"true"==item.attr("aria-expanded"))this.collapseGroup(item);else{var itemParent=item.parent().parent();itemParent.is("li")&&(itemParent.focus(),e.shiftKey?this.multiSelectItem(itemParent):hasKeyModifier||this.selectItem(itemParent))}return e.stopPropagation(),!1;case this.keys.right:return item.has("ul")&&"false"==item.attr("aria-expanded")?this.expandGroup(item):(newItem=item.children("ul").children("li").first()).length>0&&(newItem.focus(),e.shiftKey?this.multiSelectItem(newItem):hasKeyModifier||this.selectItem(newItem)),e.stopPropagation(),!1;case this.keys.up:if(currentIndex>0){var prev=this.visibleItems.eq(currentIndex-1);prev.focus(),e.shiftKey?this.multiSelectItem(prev):hasKeyModifier||this.selectItem(prev)}return e.stopPropagation(),!1;case this.keys.down:if(currentIndex<this.visibleItems.length-1){var next=this.visibleItems.eq(currentIndex+1);next.focus(),e.shiftKey?this.multiSelectItem(next):hasKeyModifier||this.selectItem(next)}return e.stopPropagation(),!1;case this.keys.asterisk:return this.parents.each((function(){thisObj.expandGroup($(this))})),e.stopPropagation(),!1;case this.keys.eight:return e.shiftKey&&(this.parents.each((function(){thisObj.expandGroup($(this))})),e.stopPropagation()),!1}return!0},Tree.prototype.handleKeyPress=function(item,e){if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey)return!0;switch(e.keyCode){case this.keys.tab:return!0;case this.keys.enter:case this.keys.home:case this.keys.end:case this.keys.left:case this.keys.right:case this.keys.up:case this.keys.down:return e.stopPropagation(),!1;default:var chr=String.fromCharCode(e.which),match=!1,itemIndex=this.visibleItems.index(item),itemCount=this.visibleItems.length,currentIndex=itemIndex+1;for(currentIndex==itemCount&&(currentIndex=0);currentIndex!=itemIndex;){var currentItem=this.visibleItems.eq(currentIndex),titleChr=currentItem.text().charAt(0);if(currentItem.has("ul")&&(titleChr=currentItem.find("span").text().charAt(0)),titleChr.toLowerCase()==chr){match=!0;break}(currentIndex+=1)==itemCount&&(currentIndex=0)}return!0===match&&this.updateFocus(this.visibleItems.eq(currentIndex)),e.stopPropagation(),!1}return!0},Tree.prototype.on=function(eventname,handler){"selectionchanged"!==eventname?log.warning('Invalid custom event name for tree. Only "selectionchanged" is supported.'):this.treeRoot.on(eventname,handler)},Tree.prototype.handleDblClick=function(item,e){return!!(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey)||(this.updateFocus(item),this.toggleGroup(item),e.stopPropagation(),!1)},Tree.prototype.handleExpandCollapseClick=function(item,e){return this.toggleGroup(item),e.stopPropagation(),!1},Tree.prototype.handleClick=function(item,e){return e.shiftKey?this.multiSelectItem(item):e.metaKey||e.ctrlKey?this.toggleItem(item):this.selectItem(item),this.updateFocus(item),e.stopPropagation(),!1},Tree.prototype.handleBlur=function(){return!0},Tree.prototype.handleFocus=function(item){return this.updateFocus(item),!0},Tree.prototype.bindEventHandlers=function(){var thisObj=this;this.parents.dblclick((function(e){return thisObj.handleDblClick($(this),e)})),this.items.click((function(e){return thisObj.handleClick($(this),e)})),this.items.children("img").click((function(e){return thisObj.handleExpandCollapseClick($(this).parent(),e)})),this.items.keydown((function(e){return thisObj.handleKeyDown($(this),e)})),this.items.keypress((function(e){return thisObj.handleKeyPress($(this),e)})),this.items.focus((function(e){return thisObj.handleFocus($(this),e)})),this.items.blur((function(e){return thisObj.handleBlur($(this),e)}))},Tree})); /** * Module to enable inline editing of a comptency grade. * * @module tool_lp/user_competency_course_navigation * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/user_competency_course_navigation",["jquery"],(function($){var UserCompetencyCourseNavigation=function(userSelector,competencySelector,baseUrl,userId,competencyId,courseId){this._baseUrl=baseUrl,this._userId=userId+"",this._competencyId=competencyId+"",this._courseId=courseId,$(userSelector).on("change",this._userChanged.bind(this)),$(competencySelector).on("change",this._competencyChanged.bind(this))};return UserCompetencyCourseNavigation.prototype._userChanged=function(e){var queryStr="?userid="+$(e.target).val()+"&courseid="+this._courseId+"&competencyid="+this._competencyId;document.location=this._baseUrl+queryStr},UserCompetencyCourseNavigation.prototype._competencyChanged=function(e){var newCompetencyId=$(e.target).val(),queryStr="?userid="+this._userId+"&courseid="+this._courseId+"&competencyid="+newCompetencyId;document.location=this._baseUrl+queryStr},UserCompetencyCourseNavigation.prototype._competencyId=null,UserCompetencyCourseNavigation.prototype._userId=null,UserCompetencyCourseNavigation.prototype._courseId=null,UserCompetencyCourseNavigation.prototype._baseUrl=null,UserCompetencyCourseNavigation.prototype._ignoreFirstCompetency=null,UserCompetencyCourseNavigation})); /** * Module to refresh a user competency summary in a page. * * @module tool_lp/user_competency_info * @copyright 2015 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/user_competency_info",["jquery","core/notification","core/ajax","core/templates"],(function($,notification,ajax,templates){var Info=function(rootElement,competencyId,userId,planId,courseId,displayuser){this._rootElement=rootElement,this._competencyId=competencyId,this._userId=userId,this._planId=planId,this._courseId=courseId,this._valid=!0,this._displayuser=void 0!==displayuser&&displayuser,this._planId?(this._methodName="tool_lp_data_for_user_competency_summary_in_plan",this._args={competencyid:this._competencyId,planid:this._planId},this._templateName="tool_lp/user_competency_summary_in_plan"):this._courseId?(this._methodName="tool_lp_data_for_user_competency_summary_in_course",this._args={userid:this._userId,competencyid:this._competencyId,courseid:this._courseId},this._templateName="tool_lp/user_competency_summary_in_course"):(this._methodName="tool_lp_data_for_user_competency_summary",this._args={userid:this._userId,competencyid:this._competencyId},this._templateName="tool_lp/user_competency_summary")};return Info.prototype.reload=function(){var self=this;this._valid&&ajax.call([{methodname:this._methodName,args:this._args}])[0].done((function(context){self._displayuser&&(context.displayuser=!0),templates.render(self._templateName,context).done((function(html,js){templates.replaceNode(self._rootElement,html,js)})).fail(notification.exception)})).fail(notification.exception)},Info.prototype._rootElement=null,Info.prototype._courseId=null,Info.prototype._valid=null,Info.prototype._planId=null,Info.prototype._competencyId=null,Info.prototype._userId=null,Info.prototype._methodName=null,Info.prototype._args=null,Info.prototype._templateName=null,Info.prototype._displayuser=!1,Info})); /** * Module to open user competency plan in popup * * @module tool_lp/user_competency_plan_popup * @copyright 2016 Issam Taboubi <issam.taboubi@umontreal.ca> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/user_competency_plan_popup",["jquery","core/notification","core/str","core/ajax","core/templates","tool_lp/dialogue"],(function($,notification,str,ajax,templates,Dialogue){var UserCompetencyPopup=function(regionSelector,userCompetencySelector,planId){this._regionSelector=regionSelector,this._userCompetencySelector=userCompetencySelector,this._planId=planId,$(this._regionSelector).on("click",this._userCompetencySelector,this._handleClick.bind(this))};return UserCompetencyPopup.prototype._handleClick=function(e){e.preventDefault();var tr=$(e.target).closest("tr"),competencyId=$(tr).data("competencyid"),userId=$(tr).data("userid"),planId=this._planId;ajax.call([{methodname:"tool_lp_data_for_user_competency_summary_in_plan",args:{competencyid:competencyId,planid:planId},done:this._contextLoaded.bind(this),fail:notification.exception}])[0].then((function(result){var eventMethodName="core_competency_user_competency_viewed_in_plan";return result.plan.iscompleted&&(eventMethodName="core_competency_user_competency_plan_viewed"),ajax.call([{methodname:eventMethodName,args:{competencyid:competencyId,userid:userId,planid:planId}}])[0]})).catch(notification.exception)},UserCompetencyPopup.prototype._contextLoaded=function(context){var self=this;templates.render("tool_lp/user_competency_summary_in_plan",context).done((function(html,js){str.get_string("usercompetencysummary","report_competency").done((function(title){new Dialogue(title,html,templates.runTemplateJS.bind(templates,js),self._refresh.bind(self),!0)})).fail(notification.exception)})).fail(notification.exception)},UserCompetencyPopup.prototype._refresh=function(){var planId=this._planId;ajax.call([{methodname:"tool_lp_data_for_plan_page",args:{planid:planId},done:this._pageContextLoaded.bind(this),fail:notification.exception}])},UserCompetencyPopup.prototype._pageContextLoaded=function(context){var self=this;templates.render("tool_lp/plan_page",context).done((function(html,js){templates.replaceNode(self._regionSelector,html,js)})).fail(notification.exception)},UserCompetencyPopup.prototype._regionSelector=null,UserCompetencyPopup.prototype._userCompetencySelector=null,UserCompetencyPopup.prototype._planId=null,UserCompetencyPopup})); /** * User competency workflow. * * @module tool_lp/user_competency_workflow * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/user_competency_workflow",["jquery","core/templates","core/ajax","core/notification","core/str","tool_lp/menubar","tool_lp/event_base"],(function($,Templates,Ajax,Notification,Str,Menubar,EventBase){var UserCompetencyWorkflow=function(){EventBase.prototype.constructor.apply(this,[])};return(UserCompetencyWorkflow.prototype=Object.create(EventBase.prototype))._nodeSelector='[data-node="user-competency"]',UserCompetencyWorkflow.prototype._cancelReviewRequest=function(data){var call={methodname:"core_competency_user_competency_cancel_review_request",args:{userid:data.userid,competencyid:data.competencyid}};Ajax.call([call])[0].then(function(){this._trigger("review-request-cancelled",data),this._trigger("status-changed",data)}.bind(this)).catch(function(){this._trigger("error-occured",data)}.bind(this))},UserCompetencyWorkflow.prototype.cancelReviewRequest=function(data){this._cancelReviewRequest(data)},UserCompetencyWorkflow.prototype._cancelReviewRequestHandler=function(e){e.preventDefault();var data=this._findUserCompetencyData($(e.target));this.cancelReviewRequest(data)},UserCompetencyWorkflow.prototype._requestReview=function(data){var call={methodname:"core_competency_user_competency_request_review",args:{userid:data.userid,competencyid:data.competencyid}};Ajax.call([call])[0].then(function(){this._trigger("review-requested",data),this._trigger("status-changed",data)}.bind(this)).catch(function(){this._trigger("error-occured",data)}.bind(this))},UserCompetencyWorkflow.prototype.requestReview=function(data){this._requestReview(data)},UserCompetencyWorkflow.prototype._requestReviewHandler=function(e){e.preventDefault();var data=this._findUserCompetencyData($(e.target));this.requestReview(data)},UserCompetencyWorkflow.prototype._startReview=function(data){var call={methodname:"core_competency_user_competency_start_review",args:{userid:data.userid,competencyid:data.competencyid}};Ajax.call([call])[0].then(function(){this._trigger("review-started",data),this._trigger("status-changed",data)}.bind(this)).catch(function(){this._trigger("error-occured",data)}.bind(this))},UserCompetencyWorkflow.prototype.startReview=function(data){this._startReview(data)},UserCompetencyWorkflow.prototype._startReviewHandler=function(e){e.preventDefault();var data=this._findUserCompetencyData($(e.target));this.startReview(data)},UserCompetencyWorkflow.prototype._stopReview=function(data){var call={methodname:"core_competency_user_competency_stop_review",args:{userid:data.userid,competencyid:data.competencyid}};Ajax.call([call])[0].then(function(){this._trigger("review-stopped",data),this._trigger("status-changed",data)}.bind(this)).catch(function(){this._trigger("error-occured",data)}.bind(this))},UserCompetencyWorkflow.prototype.stopReview=function(data){this._stopReview(data)},UserCompetencyWorkflow.prototype._stopReviewHandler=function(e){e.preventDefault();var data=this._findUserCompetencyData($(e.target));this.stopReview(data)},UserCompetencyWorkflow.prototype.enhanceMenubar=function(selector){Menubar.enhance(selector,{'[data-action="request-review"]':this._requestReviewHandler.bind(this),'[data-action="cancel-review-request"]':this._cancelReviewRequestHandler.bind(this)})},UserCompetencyWorkflow.prototype._findUserCompetencyData=function(node){var data,parent=node.parents(this._nodeSelector);if(1!=parent.length)throw new Error("The evidence node was not located.");if(void 0===(data=parent.data())||void 0===data.userid||void 0===data.competencyid)throw new Error("User competency data could not be found.");return data},UserCompetencyWorkflow.prototype.enhanceMenubar=function(selector){Menubar.enhance(selector,{'[data-action="request-review"]':this._requestReviewHandler.bind(this),'[data-action="cancel-review-request"]':this._cancelReviewRequestHandler.bind(this),'[data-action="start-review"]':this._startReviewHandler.bind(this),'[data-action="stop-review"]':this._stopReviewHandler.bind(this)})},UserCompetencyWorkflow.prototype.registerEvents=function(selector){var wrapper=$(selector);wrapper.find('[data-action="request-review"]').click(this._requestReviewHandler.bind(this)),wrapper.find('[data-action="cancel-review-request"]').click(this._cancelReviewRequestHandler.bind(this)),wrapper.find('[data-action="start-review"]').click(this._startReviewHandler.bind(this)),wrapper.find('[data-action="stop-review"]').click(this._stopReviewHandler.bind(this))},UserCompetencyWorkflow})); /** * User evidence actions. * * @module tool_lp/user_evidence_actions * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/user_evidence_actions",["jquery","core/templates","core/ajax","core/notification","core/str","tool_lp/menubar","tool_lp/competencypicker_user_plans"],(function($,templates,ajax,notification,str,Menubar,PickerUserPlans){var UserEvidenceActions=function(type){if(this._type=type,"evidence"===type)this._region='[data-region="user-evidence-page"]',this._evidenceNode='[data-region="user-evidence-page"]',this._template="tool_lp/user_evidence_page",this._contextMethod="tool_lp_data_for_user_evidence_page";else{if("list"!==type)throw new TypeError("Unexpected type.");this._region='[data-region="user-evidence-list"]',this._evidenceNode='[data-region="user-evidence-node"]',this._template="tool_lp/user_evidence_list_page",this._contextMethod="tool_lp_data_for_user_evidence_list_page"}};return UserEvidenceActions.prototype._contextMethod=null,UserEvidenceActions.prototype._evidenceNode=null,UserEvidenceActions.prototype._region=null,UserEvidenceActions.prototype._template=null,UserEvidenceActions.prototype._type=null,UserEvidenceActions.prototype._getContextArgs=function(evidenceData){var args={};return"evidence"===this._type?args={id:evidenceData.id}:"list"===this._type&&(args={userid:evidenceData.userid}),args},UserEvidenceActions.prototype._renderView=function(context){var self=this;return templates.render(self._template,context).then((function(newhtml,newjs){templates.replaceNode($(self._region),newhtml,newjs)}))},UserEvidenceActions.prototype._callAndRefresh=function(calls,evidenceData){var self=this;return calls.push({methodname:self._contextMethod,args:self._getContextArgs(evidenceData)}),$.when.apply($.when,ajax.call(calls)).then((function(){return self._renderView(arguments[arguments.length-1])})).fail(notification.exception)},UserEvidenceActions.prototype._doDelete=function(evidenceData){var calls=[{methodname:"core_competency_delete_user_evidence",args:{id:evidenceData.id}}];this._callAndRefresh(calls,evidenceData)},UserEvidenceActions.prototype.deleteEvidence=function(evidenceData){var self=this;ajax.call([{methodname:"core_competency_read_user_evidence",args:{id:evidenceData.id}}])[0].done((function(evidence){str.get_strings([{key:"confirm",component:"moodle"},{key:"deleteuserevidence",component:"tool_lp",param:evidence.name},{key:"delete",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doDelete(evidenceData)}))})).fail(notification.exception)})).fail(notification.exception)},UserEvidenceActions.prototype._deleteEvidenceHandler=function(e){e.preventDefault();var data=this._findEvidenceData($(e.target));this.deleteEvidence(data)},UserEvidenceActions.prototype._doCreateUserEvidenceCompetency=function(evidenceData,competencyIds){var calls=[];$.each(competencyIds,(function(index,competencyId){calls.push({methodname:"core_competency_create_user_evidence_competency",args:{userevidenceid:evidenceData.id,competencyid:competencyId}})})),this._callAndRefresh(calls,evidenceData)},UserEvidenceActions.prototype.createUserEvidenceCompetency=function(evidenceData){var self=this,picker=new PickerUserPlans(evidenceData.userid);picker.on("save",(function(e,data){var competencyIds=data.competencyIds;self._doCreateUserEvidenceCompetency(evidenceData,competencyIds,data.requestReview)})),picker.display()},UserEvidenceActions.prototype._createUserEvidenceCompetencyHandler=function(e){e.preventDefault();var data=this._findEvidenceData($(e.target));this.createUserEvidenceCompetency(data)},UserEvidenceActions.prototype._doDeleteUserEvidenceCompetency=function(evidenceData,competencyId){var calls=[];calls.push({methodname:"core_competency_delete_user_evidence_competency",args:{userevidenceid:evidenceData.id,competencyid:competencyId}}),this._callAndRefresh(calls,evidenceData)},UserEvidenceActions.prototype.deleteUserEvidenceCompetency=function(evidenceData,competencyId){this._doDeleteUserEvidenceCompetency(evidenceData,competencyId)},UserEvidenceActions.prototype._deleteUserEvidenceCompetencyHandler=function(e){var data=this._findEvidenceData($(e.currentTarget)),competencyId=$(e.currentTarget).data("id");e.preventDefault(),this.deleteUserEvidenceCompetency(data,competencyId)},UserEvidenceActions.prototype._doReviewUserEvidenceCompetencies=function(evidenceData){var calls=[{methodname:"core_competency_request_review_of_user_evidence_linked_competencies",args:{id:evidenceData.id}}];this._callAndRefresh(calls,evidenceData)},UserEvidenceActions.prototype.reviewUserEvidenceCompetencies=function(evidenceData){var self=this;ajax.call([{methodname:"core_competency_read_user_evidence",args:{id:evidenceData.id}}])[0].done((function(evidence){str.get_strings([{key:"confirm",component:"moodle"},{key:"sendallcompetenciestoreview",component:"tool_lp",param:evidence.name},{key:"confirm",component:"moodle"},{key:"cancel",component:"moodle"}]).done((function(strings){notification.confirm(strings[0],strings[1],strings[2],strings[3],(function(){self._doReviewUserEvidenceCompetencies(evidenceData)}))})).fail(notification.exception)})).fail(notification.exception)},UserEvidenceActions.prototype._reviewUserEvidenceCompetenciesHandler=function(e){e.preventDefault();var data=this._findEvidenceData($(e.target));this.reviewUserEvidenceCompetencies(data)},UserEvidenceActions.prototype._findEvidenceData=function(node){var data,parent=node.parentsUntil($(this._region).parent(),this._evidenceNode);if(1!=parent.length)throw new Error("The evidence node was not located.");if(void 0===(data=parent.data())||void 0===data.id)throw new Error("Evidence data could not be found.");return data},UserEvidenceActions.prototype.enhanceMenubar=function(selector){Menubar.enhance(selector,{'[data-action="user-evidence-delete"]':this._deleteEvidenceHandler.bind(this),'[data-action="link-competency"]':this._createUserEvidenceCompetencyHandler.bind(this),'[data-action="send-competencies-review"]':this._reviewUserEvidenceCompetenciesHandler.bind(this)})},UserEvidenceActions.prototype.registerEvents=function(){var wrapper=$(this._region);wrapper.find('[data-action="user-evidence-delete"]').click(this._deleteEvidenceHandler.bind(this)),wrapper.find('[data-action="link-competency"]').click(this._createUserEvidenceCompetencyHandler.bind(this)),wrapper.find('[data-action="delete-competency-link"]').click(this._deleteUserEvidenceCompetencyHandler.bind(this)),wrapper.find('[data-action="send-competencies-review"]').click(this._reviewUserEvidenceCompetenciesHandler.bind(this))},UserEvidenceActions})); /** * Competency rule base module. * * @module tool_lp/competencyrule * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competency_rule",["jquery"],(function($){var Rule=function(tree){this._eventNode=$("<div>"),this._ready=$.Deferred(),this._tree=tree};return Rule.prototype._competency=null,Rule.prototype._eventNode=null,Rule.prototype._ready=null,Rule.prototype._tree=null,Rule.prototype.canConfig=function(){return this._tree.hasChildren(this._competency.id)},Rule.prototype.getConfig=function(){return null},Rule.prototype.getType=function(){throw new Error("Not implemented")},Rule.prototype.init=function(){return this._load()},Rule.prototype.injectTemplate=function(){return $.Deferred().reject().promise()},Rule.prototype.isValid=function(){return!1},Rule.prototype._load=function(){return $.when()},Rule.prototype.on=function(type,handler){this._eventNode.on(type,handler)},Rule.prototype.setTargetCompetency=function(competency){this._competency=competency},Rule.prototype._trigger=function(type,data){this._eventNode.trigger(type,[data])},Rule.prototype._triggerChange=function(){this._trigger("change",this)},Rule})); /** * Competency rule points module. * * @module tool_lp/competency_rule_all * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competency_rule_points",["jquery","core/str","core/templates","tool_lp/competency_rule"],(function($,Str,Templates,RuleBase){var Rule=function(){RuleBase.apply(this,arguments)};return(Rule.prototype=Object.create(RuleBase.prototype))._container=null,Rule.prototype._templateLoaded=!1,Rule.prototype.getConfig=function(){return JSON.stringify({base:{points:this._getRequiredPoints()},competencies:this._getCompetenciesConfig()})},Rule.prototype._getCompetenciesConfig=function(){var competencies=[];return this._container.find("[data-competency]").each((function(){var node=$(this),id=node.data("competency"),points=parseInt(node.find('[name="points"]').val(),10),required=node.find('[name="required"]').prop("checked");competencies.push({id:id,points:points,required:required?1:0})})),competencies},Rule.prototype._getRequiredPoints=function(){return parseInt(this._container.find('[name="requiredpoints"]').val()||1,10)},Rule.prototype.getType=function(){return"core_competency\\competency_rule_points"},Rule.prototype.injectTemplate=function(container){var context,self=this,children=this._tree.getChildren(this._competency.id),config={base:{points:2},competencies:[]};if(this._templateLoaded=!1,self._competency.ruletype==self.getType())try{config=JSON.parse(self._competency.ruleconfig)}catch(e){}return context={requiredpoints:config&&config.base?config.base.points:2,competency:self._competency,children:[]},$.each(children,(function(index,child){var competency={id:child.id,shortname:child.shortname,required:!1,points:0};config&&$.each(config.competencies,(function(index,comp){comp.id==competency.id&&(competency.required=!!comp.required,competency.points=comp.points)})),context.children.push(competency)})),Templates.render("tool_lp/competency_rule_points",context).then((function(html){self._container=container,container.html(html),container.find("input").change((function(){self._triggerChange()})),self._templateLoaded=!0,self._triggerChange()}))},Rule.prototype.isValid=function(){if(!this._templateLoaded)return!1;var required=this._getRequiredPoints(),max=0,valid=!0;return $.each(this._getCompetenciesConfig(),(function(index,competency){competency.points<0&&(valid=!1),max+=competency.points})),valid=valid&&max>=required},Rule})); /** * Display Competency in dialogue box. * * @module tool_lp/Competencydialogue * @copyright 2015 Issam Taboubi <issam.taboubi@umontreal.ca> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencydialogue",["jquery","core/notification","core/ajax","core/templates","core/str","tool_lp/dialogue"],(function($,notification,ajax,templates,str,Dialogue){var instance,Competencydialogue=function(){};return Competencydialogue.prototype.triggerCompetencyViewedEvent=function(competencyId){ajax.call([{methodname:"core_competency_competency_viewed",args:{id:competencyId}}])},Competencydialogue.prototype.showDialogue=function(competencyid,options){var datapromise=this.getCompetencyDataPromise(competencyid,options),localthis=this;datapromise.done((function(data){templates.render("tool_lp/competency_summary",data).done((function(html){localthis.triggerCompetencyViewedEvent(competencyid),new Dialogue(data.competency.shortname,html)})).fail(notification.exception)})).fail(notification.exception)},Competencydialogue.prototype.showDialogueFromData=function(dataSource){var localthis=this;templates.render("tool_lp/competency_summary",dataSource).done((function(html){localthis.triggerCompetencyViewedEvent(dataSource.id),new Dialogue(dataSource.shortname,html,localthis.enhanceDialogue)})).fail(notification.exception)},Competencydialogue.prototype.clickEventHandler=function(e){var compdialogue=e.data.compdialogue,currentTarget=$(e.currentTarget),competencyid=currentTarget.data("id"),includerelated=!currentTarget.data("excluderelated"),includecourses=currentTarget.data("includecourses");compdialogue.showDialogue(competencyid,{includerelated:includerelated,includecourses:includecourses}),e.preventDefault()},Competencydialogue.prototype.getCompetencyDataPromise=function(competencyid,options){return ajax.call([{methodname:"tool_lp_data_for_competency_summary",args:{competencyid:competencyid,includerelated:options.includerelated||!1,includecourses:options.includecourses||!1}}])[0].then((function(context){return context})).fail(notification.exception)},{init:function(){void 0===instance&&(instance=new Competencydialogue,$("body").delegate('[data-action="competency-dialogue"]',"click",{compdialogue:instance},instance.clickEventHandler.bind(instance)))}}})); /** * Handle selection changes on the competency tree. * * @module tool_lp/competencyselect * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/competencytree",["core/ajax","core/notification","core/templates","tool_lp/tree","tool_lp/competency_outcomes","jquery"],(function(ajax,notification,templates,Ariatree,CompOutcomes,$){var competencies={},competencyFrameworkId=0,competencyFrameworkShortName="",treeSelector="",currentNodeId="",competencyFramworkCanManage=!1,addChildren=function(parent,all){var i=0,current=!1;for(parent.haschildren=!1,parent.children=[],i=0;i<all.length;i++)(current=all[i]).parentid==parent.id&&(parent.haschildren=!0,parent.children.push(current),addChildren(current,all))},loadCompetencies=function(searchtext){var deferred=$.Deferred();return templates.render("tool_lp/loading",{}).done((function(loadinghtml,loadingjs){templates.replaceNodeContents($(treeSelector),loadinghtml,loadingjs),ajax.call([{methodname:"core_competency_search_competencies",args:{searchtext:searchtext,competencyframeworkid:competencyFrameworkId}}])[0].done((function(result){competencies={};var i=0;for(i=0;i<result.length;i++)competencies[result[i].id]=result[i];var children=[],competency=!1;for(i=0;i<result.length;i++)competency=result[i],0===parseInt(competency.parentid,10)&&(children.push(competency),addChildren(competency,result));var context={shortname:competencyFrameworkShortName,canmanage:competencyFramworkCanManage,competencies:children};templates.render("tool_lp/competencies_tree_root",context).done((function(html,js){templates.replaceNodeContents($(treeSelector),$(html).html(),js);var tree=new Ariatree(treeSelector,!1);if(currentNodeId){var node=$(treeSelector).find("[data-id="+currentNodeId+"]");node.length&&(tree.selectItem(node),tree.updateFocus(node))}deferred.resolve(competencies)})).fail(deferred.reject)})).fail(deferred.reject)})),deferred.promise()},rememberCurrent=function(evt,params){var node=params.selected;currentNodeId=node.attr("data-id")};return{init:function(id,shortname,search,selector,canmanage,competencyid){competencyFrameworkId=id,competencyFrameworkShortName=shortname,competencyFramworkCanManage=canmanage,treeSelector=selector,loadCompetencies(search).fail(notification.exception),competencyid>0&&(currentNodeId=competencyid),this.on("selectionchanged",rememberCurrent)},on:function(eventname,handler){$(treeSelector).on(eventname,handler)},getChildren:function(id){var children=[];return $.each(competencies,(function(index,competency){competency.parentid==id&&children.push(competency)})),children},getCompetencyFrameworkId:function(){return competencyFrameworkId},getCompetency:function(id){return competencies[id]},getCompetencyLevel:function(id){return this.getCompetency(id).path.replace(/^\/|\/$/g,"").split("/").length},hasChildren:function(id){return this.getChildren(id).length>0},hasRule:function(id){var comp=this.getCompetency(id);return!!comp&&(comp.ruleoutcome!=CompOutcomes.OUTCOME_NONE&&comp.ruletype)},reloadCompetencies:function(){return loadCompetencies("").fail(notification.exception)},listCompetencies:function(){return competencies}}})); /** * Change the course competency settings in a popup. * * @module tool_lp/configurecoursecompetencysettings * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/course_competency_settings",["jquery","core/notification","tool_lp/dialogue","core/str","core/ajax","core/templates","core/pending"],(function($,notification,Dialogue,str,ajax,templates,Pending){var settingsMod=function(selector){$(selector).on("click",this.configureSettings.bind(this))};return settingsMod.prototype._dialogue=null,settingsMod.prototype.configureSettings=function(e){var pendingPromise=new Pending,context={courseid:$(e.target).closest("a").data("courseid"),settings:{pushratingstouserplans:$(e.target).closest("a").data("pushratingstouserplans")}};e.preventDefault(),$.when(str.get_string("configurecoursecompetencysettings","tool_lp"),templates.render("tool_lp/course_competency_settings",context)).then(function(title,templateResult){return this._dialogue=new Dialogue(title,templateResult[0],this.addListeners.bind(this)),this._dialogue}.bind(this)).then(pendingPromise.resolve).catch(notification.exception)},settingsMod.prototype.addListeners=function(){this._find('[data-action="save"]').on("click",this.saveSettings.bind(this)),this._find('[data-action="cancel"]').on("click",this.cancelChanges.bind(this))},settingsMod.prototype.cancelChanges=function(e){e.preventDefault(),this._dialogue.close()},settingsMod.prototype._find=function(selector){return $('[data-region="coursecompetencysettings"]').find(selector)},settingsMod.prototype.saveSettings=function(e){var pendingPromise=new Pending;e.preventDefault();var newValue=this._find('input[name="pushratingstouserplans"]:checked').val(),courseId=this._find('input[name="courseid"]').val(),settings={pushratingstouserplans:newValue};ajax.call([{methodname:"core_competency_update_course_competency_settings",args:{courseid:courseId,settings:settings}}])[0].then(function(){return this.refreshCourseCompetenciesPage()}.bind(this)).then(pendingPromise.resolve).catch(notification.exception)},settingsMod.prototype.refreshCourseCompetenciesPage=function(){var courseId=this._find('input[name="courseid"]').val(),pendingPromise=new Pending;ajax.call([{methodname:"tool_lp_data_for_course_competencies_page",args:{courseid:courseId,moduleid:0}}])[0].then((function(context){return templates.render("tool_lp/course_competencies_page",context)})).then(function(html,js){templates.replaceNode($('[data-region="coursecompetenciespage"]'),html,js),this._dialogue.close()}.bind(this)).then(pendingPromise.resolve).catch(notification.exception)},settingsMod})); /** * Cohort selector module. * * @module tool_lp/form-cohort-selector * @copyright 2015 Frédéric Massart - FMCorz.net * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_lp/form-cohort-selector",["jquery","core/ajax","core/templates"],(function($,Ajax,Templates){return{processResults:function(selector,results){var cohorts=[];return $.each(results,(function(index,cohort){cohorts.push({value:cohort.id,label:cohort._label})})),cohorts},transport:function(selector,query,success,failure){var contextid=parseInt($(selector).data("contextid"),10),includes=$(selector).data("includes");Ajax.call([{methodname:"tool_lp_search_cohorts",args:{query:query,context:{contextid:contextid},includes:includes}}])[0].then((function(results){var promises=[],i=0;return $.each(results.cohorts,(function(index,cohort){promises.push(Templates.render("tool_lp/form-cohort-selector-suggestion",cohort))})),$.when.apply($.when,promises).then((function(){var args=arguments;$.each(results.cohorts,(function(index,cohort){cohort._label=args[i],i++})),success(results.cohorts)}))})).catch(failure)}}})); /** * Our basic form manager for when a user either enters * their profile url or just wants to browse. * * This file is a mishmash of JS functions we need for both the standalone (M3.7, M3.8) * plugin & Moodle 3.9 functions. The 3.9 Functions have a base understanding that certain * things exist i.e. directory structures for templates. When this feature goes 3.9+ only * The goal is that we can quickly gut all AMD modules into bare JS files and use ES6 guidelines. * Till then this will have to do. * * @module tool_moodlenet/instance_form * @copyright 2020 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_moodlenet/instance_form",["tool_moodlenet/validator","tool_moodlenet/selectors","core/loadingicon","core/templates","core/notification","jquery"],(function(Validator,Selectors,LoadingIcon,Templates,Notification,$){var chooserNavigateToMnet=function(showMoodleNet,footerData,carousel,modal){showMoodleNet.innerHTML="";var page,spinnerPromise=LoadingIcon.addIconToContainer(showMoodleNet),transitionPromiseResolver=null,transitionPromise=new Promise((resolve=>{transitionPromiseResolver=resolve}));$.when(spinnerPromise,transitionPromise).then((function(){Templates.replaceNodeContents(showMoodleNet,footerData.customcarouseltemplate,"")})).catch(Notification.exception),(page=showMoodleNet).addEventListener("click",(function(e){if(e.target.matches(Selectors.action.submit)){var input=page.querySelector('[data-var="mnet-link"]'),overlay=page.querySelector(Selectors.region.spinner),validationArea=document.querySelector(Selectors.region.validationArea);overlay.classList.remove("d-none");var spinner=LoadingIcon.addIconToContainerWithPromise(overlay);Validator.validation(input).then((function(result){spinner.resolve(),overlay.classList.add("d-none"),result.result?(input.classList.remove("is-invalid"),input.classList.add("is-valid"),validationArea.innerText=result.message,validationArea.classList.remove("text-danger"),validationArea.classList.add("text-success"),setTimeout((function(){window.location=result.domain}),1e3)):(input.classList.add("is-invalid"),validationArea.innerText=result.message,validationArea.classList.add("text-danger"))})).catch()}})),carousel.one("slid.bs.carousel",(function(){transitionPromiseResolver()})),carousel.carousel(2),modal.setFooter(Templates.render("tool_moodlenet/chooser_footer_close_mnet",{}))};return{footerClickListener:function(e,footerData,modal){if(e.target.matches(Selectors.action.showMoodleNet)||e.target.closest(Selectors.action.showMoodleNet)){e.preventDefault();const carousel=$(modal.getBody()[0].querySelector(Selectors.region.carousel)),showMoodleNet=carousel.find(Selectors.region.moodleNet)[0];chooserNavigateToMnet(showMoodleNet,footerData,carousel,modal)}if(e.target.matches(Selectors.action.closeOption)){!function(carousel,modal,footerData){carousel.carousel(0),modal.setFooter(footerData.customfootertemplate)}($(modal.getBody()[0].querySelector(Selectors.region.carousel)),modal,footerData)}}}})); /** * When returning to Moodle let the user select which course to add the resource to. * * @module tool_moodlenet/select_page * @copyright 2020 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_moodlenet/select_page",["core/ajax","core/templates","tool_moodlenet/selectors","core/notification"],(function(Ajax,Templates,Selectors,Notification){var importId,searchCourses=function(inputValue,page,areaReplace){var searchIcon=page.querySelector(Selectors.region.searchIcon),clearIcon=page.querySelector(Selectors.region.clearIcon);""!==inputValue?(searchIcon.classList.add("d-none"),clearIcon.parentElement.classList.remove("d-none")):(searchIcon.classList.remove("d-none"),clearIcon.parentElement.classList.add("d-none"));var args={searchvalue:inputValue};Ajax.call([{methodname:"tool_moodlenet_search_courses",args:args}])[0].then((function(result){return 0===result.courses.length?function(areaReplace){return Templates.renderPix("courses","tool_moodlenet").then((function(img){return img})).then((function(img){var temp=document.createElement("div");return temp.innerHTML=img.trim(),Templates.render("core_course/no-courses",{nocoursesimg:temp.firstChild.src})})).then((function(html,js){Templates.replaceNodeContents(areaReplace,html,js),areaReplace.classList.add("mx-auto"),areaReplace.classList.add("w-25")}))}(areaReplace):(result.courses.forEach((function(course){course.viewurl+="&id="+importId})),function(areaReplace,courses){return Templates.render("tool_moodlenet/view-cards",{courses:courses}).then((function(html,js){Templates.replaceNodeContents(areaReplace,html,js),areaReplace.classList.remove("mx-auto"),areaReplace.classList.remove("w-25")}))}(areaReplace,result.courses))})).catch(Notification.exception)},registerListenerEvents=function(page){var input=page.querySelector(Selectors.region.searchInput),courseArea=page.querySelector(Selectors.region.courses);page.querySelector(Selectors.region.clearIcon).addEventListener("click",(function(){input.value="",searchCourses("",page,courseArea)})),input.addEventListener("input",debounce((function(){searchCourses(input.value,page,courseArea)}),300))},addCourses=function(page){var courseArea=page.querySelector(Selectors.region.courses);searchCourses("",page,courseArea)},debounce=function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}};return{init:function(importIdString){importId=importIdString;var page=document.querySelector(Selectors.region.selectPage);registerListenerEvents(page),addCourses(page)}}})); /** * Define all of the selectors we will be using within MoodleNet plugin. * * @module tool_moodlenet/selectors * @copyright 2020 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_moodlenet/selectors",[],(function(){return{action:{browse:'[data-action="browse"]',submit:'[data-action="submit"]',showMoodleNet:'[data-action="show-moodlenet"]',closeOption:'[data-action="close-chooser-option-summary"]'},region:{clearIcon:'[data-region="clear-icon"]',courses:'[data-region="mnet-courses"]',instancePage:'[data-region="moodle-net"]',searchInput:'[data-region="search-input"]',searchIcon:'[data-region="search-icon"]',selectPage:'[data-region="moodle-net-select"]',spinner:'[data-region="spinner"]',validationArea:'[data-region="validation-area"]',carousel:'[data-region="carousel"]',moodleNet:'[data-region="pluginCarousel"]'}}})); /** * Our validator that splits the user's input then fires off to a webservice * * @module tool_moodlenet/validator * @copyright 2020 Mathew May <mathew.solutions> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_moodlenet/validator",["jquery","core/ajax","core/str","core/notification"],(function($,Ajax,Str,Notification){return{validation:function(inputElement){var inputValue=inputElement.value;return""!==inputValue&&inputValue.includes("@")||$.when(Str.get_string("profilevalidationerror","tool_moodlenet")).then((function(strings){return Promise.reject().catch((function(){return{result:!1,message:strings[0]}}))})).fail(Notification.exception),Ajax.call([{methodname:"tool_moodlenet_verify_webfinger",args:{profileurl:inputValue,course:inputElement.dataset.courseid,section:inputElement.dataset.sectionid}}])[0].then((function(result){return result})).catch()}}})); /** * Unified filter page JS module for the course participants page. * * @module tool_policy/acceptances_filter * @copyright 2017 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_policy/acceptances_filter",["jquery","core/form-autocomplete","core/str","core/notification"],(function($,Autocomplete,Str,Notification){var SELECTORS_UNIFIED_FILTERS="#unified-filters";return{init:function(){!function(){M.util.js_pending("acceptances_filter_datasource"),Str.get_strings([{key:"filterplaceholder",component:"tool_policy"},{key:"nofiltersapplied",component:"tool_policy"}]).done((function(langstrings){var placeholder=langstrings[0],noSelectionString=langstrings[1];Autocomplete.enhance(SELECTORS_UNIFIED_FILTERS,!0,"tool_policy/acceptances_filter_datasource",placeholder,!1,!0,noSelectionString,!0).then((function(){M.util.js_complete("acceptances_filter_datasource")})).fail(Notification.exception)})).fail(Notification.exception);var last=$(SELECTORS_UNIFIED_FILTERS).val();$(SELECTORS_UNIFIED_FILTERS).on("change",(function(){var current=$(this).val(),listoffilters=[],textfilters=[],updatedselectedfilters=!1;if($.each(current,(function(index,catoption){var catandoption=catoption.split(":",2);if(2!==catandoption.length)return textfilters.push(catoption),!0;var category=catandoption[0],option=catandoption[1];return void 0!==listoffilters[category]&&(updatedselectedfilters=!0),listoffilters[category]=option,!0})),updatedselectedfilters){var updatefilters=[];for(var category in listoffilters)updatefilters.push(category+":"+listoffilters[category]);updatefilters=updatefilters.concat(textfilters),$(this).val(updatefilters)}last.join(",")!=current.join(",")&&this.form.submit()}))}()},getForm:function(){return $(SELECTORS_UNIFIED_FILTERS).closest("form")}}})); /** * Datasource for the tool_policy/acceptances_filter. * * This module is compatible with core/form-autocomplete. * * @copyright 2017 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_policy/acceptances_filter_datasource",["jquery","core/ajax","core/notification"],(function($,Ajax,Notification){return{list:function(selector,query){var filteredOptions=[],el=$(selector),originalOptions=$(selector).data("originaloptionsjson"),selectedFilters=el.val();$.each(originalOptions,(function(index,option){return""!==query.trim()&&-1===option.label.toLocaleLowerCase().indexOf(query.toLocaleLowerCase())||$.inArray(option.value,selectedFilters)>-1||filteredOptions.push(option),!0}));var deferred=new $.Deferred;return deferred.resolve(filteredOptions),deferred.promise()},processResults:function(selector,results){var options=[];return $.each(results,(function(index,data){options.push({value:data.value,label:data.label})})),options},transport:function(selector,query,callback){this.list(selector,query).then(callback).catch(Notification.exception)}}})); /** * Add policy consent modal to the page * * @module tool_policy/acceptmodal * @copyright 2018 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_policy/acceptmodal",["jquery","core/str","core/modal_factory","core/modal_events","core/notification","core/fragment","core/ajax","core_form/changechecker"],(function($,Str,ModalFactory,ModalEvents,Notification,Fragment,Ajax,FormChangeChecker){var AcceptOnBehalf=function(contextid){this.contextid=contextid,this.init()};return AcceptOnBehalf.prototype.modal=null,AcceptOnBehalf.prototype.contextid=-1,AcceptOnBehalf.prototype.currentTrigger=null,AcceptOnBehalf.prototype.triggers={SINGLE:"a[data-action=acceptmodal]",BULK:"input[data-action=acceptmodal]"},AcceptOnBehalf.prototype.init=function(){$(this.triggers.SINGLE).on("click",function(e){e.preventDefault(),this.currentTrigger=$(e.currentTarget);var href=$(e.currentTarget).attr("href"),formData=href.slice(href.indexOf("?")+1);this.showFormModal(formData)}.bind(this)),$(this.triggers.BULK).on("click",function(e){e.preventDefault(),this.currentTrigger=$(e.currentTarget);var form=$(e.currentTarget).closest("form");if(form.find('input[type=checkbox][name="userids[]"]:checked').length){var formData=form.serialize();this.showFormModal(formData)}else Str.get_strings([{key:"notice"},{key:"selectusersforconsent",component:"tool_policy"},{key:"ok"}]).then((function(strings){Notification.alert(strings[0],strings[1],strings[2])})).fail(Notification.exception)}.bind(this))},AcceptOnBehalf.prototype.showFormModal=function(formData){for(var action,params=formData.split("&"),i=0;i<params.length;i++){var pair=params[i].split("=");"action"==pair[0]&&(action=pair[1])}Str.get_strings([{key:"statusformtitleaccept",component:"tool_policy"},{key:"iagreetothepolicy",component:"tool_policy"},{key:"statusformtitlerevoke",component:"tool_policy"},{key:"irevokethepolicy",component:"tool_policy"},{key:"statusformtitledecline",component:"tool_policy"},{key:"declinethepolicy",component:"tool_policy"}]).then(function(strings){var title,saveText;return"accept"==action?(title=strings[0],saveText=strings[1]):"revoke"==action?(title=strings[2],saveText=strings[3]):"decline"==action&&(title=strings[4],saveText=strings[5]),ModalFactory.create({type:ModalFactory.types.SAVE_CANCEL,title:title,body:""}).done(function(modal){this.modal=modal,this.setupFormModal(formData,saveText)}.bind(this))}.bind(this)).catch(Notification.exception)},AcceptOnBehalf.prototype.setupFormModal=function(formData,saveText){var modal=this.modal;modal.setLarge(),modal.setSaveButtonText(saveText),modal.getRoot().on(ModalEvents.hidden,this.destroy.bind(this)),modal.setBody(this.getBody(formData)),modal.getRoot().on(ModalEvents.save,this.submitForm.bind(this)),modal.getRoot().on("submit","form",this.submitFormAjax.bind(this)),modal.show()},AcceptOnBehalf.prototype.getBody=function(formData){void 0===formData&&(formData={});var params={jsonformdata:JSON.stringify(formData)};return Fragment.loadFragment("tool_policy","accept_on_behalf",this.contextid,params)},AcceptOnBehalf.prototype.submitFormAjax=function(e){e.preventDefault();var formData=this.modal.getRoot().find("form").serialize();Ajax.call([{methodname:"tool_policy_submit_accept_on_behalf",args:{jsonformdata:JSON.stringify(formData)}}])[0].done(function(data){data.validationerrors?this.modal.setBody(this.getBody(formData)):this.close()}.bind(this)).fail(Notification.exception)},AcceptOnBehalf.prototype.submitForm=function(e){e.preventDefault(),this.modal.getRoot().find("form").submit()},AcceptOnBehalf.prototype.close=function(){this.destroy(),document.location.reload()},AcceptOnBehalf.prototype.destroy=function(){FormChangeChecker.resetAllFormDirtyStates(),this.modal.destroy(),this.currentTrigger.focus()},{getInstance:function(contextid){return new AcceptOnBehalf(contextid)}}})); define("tool_policy/jquery-eu-cookie-law-popup",["jquery"],(function($){window.console||(window.console={}),window.console.log||(window.console.log=function(){}),$.fn.euCookieLawPopup=function(){var _self=this;_self.params={cookiePolicyUrl:"/?cookie-policy",popupPosition:"top",colorStyle:"default",compactStyle:!1,popupTitle:"This website is using cookies",popupText:"We use cookies to ensure that we give you the best experience on our website. If you continue without changing your settings, we'll assume that you are happy to receive all cookies on this website.",buttonContinueTitle:"Continue",buttonLearnmoreTitle:"Learn more",buttonLearnmoreOpenInNewWindow:!0,agreementExpiresInDays:30,autoAcceptCookiePolicy:!1,htmlMarkup:null},_self.vars={INITIALISED:!1,HTML_MARKUP:null,COOKIE_NAME:"EU_COOKIE_LAW_CONSENT"};var setUserAcceptsCookies=function(consent){var d=new Date,expiresInDays=24*_self.params.agreementExpiresInDays*60*60*1e3;d.setTime(d.getTime()+expiresInDays);var expires="expires="+d.toGMTString();document.cookie=_self.vars.COOKIE_NAME+"="+consent+"; "+expires+";path=/",$(document).trigger("user_cookie_consent_changed",{consent:consent})},hideContainer=function(){$(".eupopup-container").animate({opacity:0,height:0},200,(function(){$(".eupopup-container").hide(0)}))};return{init:function(settings){!function(object,markup,settings){if(object){var className=$(object).attr("class")?$(object).attr("class"):"";className.indexOf("eupopup-top")>-1?_self.params.popupPosition="top":className.indexOf("eupopup-fixedtop")>-1?_self.params.popupPosition="fixedtop":className.indexOf("eupopup-bottomright")>-1?_self.params.popupPosition="bottomright":className.indexOf("eupopup-bottomleft")>-1?_self.params.popupPosition="bottomleft":className.indexOf("eupopup-bottom")>-1?_self.params.popupPosition="bottom":className.indexOf("eupopup-block")>-1&&(_self.params.popupPosition="block"),className.indexOf("eupopup-color-default")>-1?_self.params.colorStyle="default":className.indexOf("eupopup-color-inverse")>-1&&(_self.params.colorStyle="inverse"),className.indexOf("eupopup-style-compact")>-1&&(_self.params.compactStyle=!0)}markup&&(_self.params.htmlMarkup=markup),settings&&(void 0!==settings.cookiePolicyUrl&&(_self.params.cookiePolicyUrl=settings.cookiePolicyUrl),void 0!==settings.popupPosition&&(_self.params.popupPosition=settings.popupPosition),void 0!==settings.colorStyle&&(_self.params.colorStyle=settings.colorStyle),void 0!==settings.popupTitle&&(_self.params.popupTitle=settings.popupTitle),void 0!==settings.popupText&&(_self.params.popupText=settings.popupText),void 0!==settings.buttonContinueTitle&&(_self.params.buttonContinueTitle=settings.buttonContinueTitle),void 0!==settings.buttonLearnmoreTitle&&(_self.params.buttonLearnmoreTitle=settings.buttonLearnmoreTitle),void 0!==settings.buttonLearnmoreOpenInNewWindow&&(_self.params.buttonLearnmoreOpenInNewWindow=settings.buttonLearnmoreOpenInNewWindow),void 0!==settings.agreementExpiresInDays&&(_self.params.agreementExpiresInDays=settings.agreementExpiresInDays),void 0!==settings.autoAcceptCookiePolicy&&(_self.params.autoAcceptCookiePolicy=settings.autoAcceptCookiePolicy),void 0!==settings.htmlMarkup&&(_self.params.htmlMarkup=settings.htmlMarkup))}($(".eupopup").first(),$(".eupopup-markup").html(),settings),function(){for(var userAcceptedCookies=!1,cookies=document.cookie.split(";"),i=0;i<cookies.length;i++){var c=cookies[i].trim();-1!==c.indexOf(_self.vars.COOKIE_NAME)&&(userAcceptedCookies=c.substring(_self.vars.COOKIE_NAME.length+1,c.length))}return userAcceptedCookies}()?$(document).trigger("user_cookie_already_accepted",{consent:!0}):_self.vars.INITIALISED||(_self.vars.INITIALISED=!0,_self.vars.HTML_MARKUP=_self.params.htmlMarkup?_self.params.htmlMarkup:'<div class="eupopup-container eupopup-container-'+_self.params.popupPosition+(_self.params.compactStyle?" eupopup-style-compact":"")+" eupopup-color-"+_self.params.colorStyle+'"><div class="eupopup-head">'+_self.params.popupTitle+'</div><div class="eupopup-body">'+_self.params.popupText+'</div><div class="eupopup-buttons"><a href="#" class="eupopup-button eupopup-button_1">'+_self.params.buttonContinueTitle+'</a><a href="'+_self.params.cookiePolicyUrl+'"'+(_self.params.buttonLearnmoreOpenInNewWindow?" target=_blank ":"")+' class="eupopup-button eupopup-button_2">'+_self.params.buttonLearnmoreTitle+'</a><div class="clearfix"></div></div><a href="#" class="eupopup-closebutton">x</a></div>',$(".eupopup-block").length>0?$(".eupopup-block").append(_self.vars.HTML_MARKUP):$("BODY").append(_self.vars.HTML_MARKUP),$(".eupopup-button_1").click((function(){return setUserAcceptsCookies(!0),hideContainer(),!1})),$(".eupopup-closebutton").click((function(){return setUserAcceptsCookies(!0),hideContainer(),!1})),$(".eupopup-container").show(),_self.params.autoAcceptCookiePolicy&&setUserAcceptsCookies(!0))}}}})); /** * Adds support for confirmation via JS modal for some management actions at the Manage policies page. * * @module tool_policy/managedocsactions * @copyright 2018 David Mudrák <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_policy/managedocsactions",["jquery","core/log","core/config","core/str","core/modal_factory","core/modal_events"],(function($,Log,Config,Str,ModalFactory,ModalEvents){var ACTION_LINKS="[data-action]",ACTION_MAKE_CURRENT='[data-action="makecurrent"]',ACTION_INACTIVATE='[data-action="inactivate"]',ACTION_DELETE='[data-action="delete"]';function ManageDocsActions(base){this.base=base,this.initEvents()}return ManageDocsActions.prototype.initEvents=function(){this.base.on("click",ACTION_LINKS,(function(e){e.stopPropagation();var promise,strings,link=$(e.currentTarget);if(link.is(ACTION_MAKE_CURRENT))promise=Str.get_strings([{key:"activating",component:"tool_policy"},{key:"activateconfirm",component:"tool_policy",param:{name:link.closest("[data-policy-name]").attr("data-policy-name"),revision:link.closest("[data-policy-revision]").attr("data-policy-revision")}},{key:"activateconfirmyes",component:"tool_policy"}]);else if(link.is(ACTION_INACTIVATE))promise=Str.get_strings([{key:"inactivating",component:"tool_policy"},{key:"inactivatingconfirm",component:"tool_policy",param:{name:link.closest("[data-policy-name]").attr("data-policy-name"),revision:link.closest("[data-policy-revision]").attr("data-policy-revision")}},{key:"inactivatingconfirmyes",component:"tool_policy"}]);else{if(!link.is(ACTION_DELETE))return void Log.error("unknown action type detected","tool_policy/managedocsactions");promise=Str.get_strings([{key:"deleting",component:"tool_policy"},{key:"deleteconfirm",component:"tool_policy",param:{name:link.closest("[data-policy-name]").attr("data-policy-name"),revision:link.closest("[data-policy-revision]").attr("data-policy-revision")}},{key:"delete",component:"core"}])}e.preventDefault(),promise.then((function(strs){return strings=strs,ModalFactory.create({title:strings[0],body:strings[1],type:ModalFactory.types.SAVE_CANCEL})})).then((function(modal){return modal.setSaveButtonText(strings[2]),modal.getRoot().on(ModalEvents.save,(function(){window.location.href=link.attr("href")+"&sesskey="+Config.sesskey+"&confirm=1"})),modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal.show(),!0})).catch((function(e){return Log.error(e),!1}))}))},{init:function(baseid){var base=$(document.getElementById(baseid));if(base.length)return new ManageDocsActions(base);throw new Error("managedocsactions: Invalid base element identifier")}}})); /** * Policy actions. * * @module tool_policy/policyactions * @copyright 2018 Sara Arjona (sara@moodle.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_policy/policyactions",["jquery","core/ajax","core/notification","core/modal_factory","core/modal_events"],(function($,Ajax,Notification,ModalFactory,ModalEvents){var PolicyActions=function(root){this.registerEvents(root)};return PolicyActions.prototype.registerEvents=function(root){root.on("click",(function(e){e.preventDefault();var request={methodname:"tool_policy_get_policy_version",args:{versionid:$(this).data("versionid"),behalfid:$(this).data("behalfid")}},modalTitle=$.Deferred(),modalBody=$.Deferred(),modal=ModalFactory.create({title:modalTitle,body:modalBody,large:!0}).then((function(modal){return modal.getRoot().on(ModalEvents.hidden,(function(){modal.destroy()})),modal})).then((function(modal){return modal.show(),modal})).catch(Notification.exception),promises=Ajax.call([request]);$.when(promises[0]).then((function(data){if(data.result.policy)return modalTitle.resolve(data.result.policy.name),modalBody.resolve(data.result.policy.content),data;throw new Error(data.warnings[0].message)})).catch((function(message){return modal.then((function(modal){return modal.hide(),modal.destroy(),modal})).catch(Notification.exception),Notification.addNotification({message:message,type:"error"})}))}))},{init:function(root){return root=$(root),new PolicyActions(root)}}})); /** * This module adds ajax display functions to the template library page. * * @module tool_templatelibrary/display * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_templatelibrary/display",["jquery","core/ajax","core/log","core/notification","core/templates","core/config","core/str"],(function($,ajax,log,notification,templates,config,str){var findDocsSection=function(templateSource,templateName){if(!templateSource)return!1;var sections,marker="@template "+templateName,i=0;if(null!==(sections=templateSource.match(/{{!([\s\S]*?)}}/g)))for(i=0;i<sections.length;i++){var section=sections[i],start=section.indexOf(marker);if(-1!==start){var offset=start+marker.length+1;return section=section.substr(offset,section.length-2-offset)}}return!1},loadTemplate=function(templateName){var parts=templateName.split("/"),component=parts.shift(),name=parts.join("/"),promises=ajax.call([{methodname:"core_output_load_template",args:{component:component,template:name,themename:config.theme,includecomments:!0}},{methodname:"tool_templatelibrary_load_canonical_template",args:{component:component,template:name}}],!0,!1);$.when.apply($,promises).done((function(source,originalSource){!function(templateName,source,originalSource){str.get_string("templateselected","tool_templatelibrary",templateName).done((function(s){$('[data-region="displaytemplateheader"]').text(s)})).fail(notification.exception);var docs=findDocsSection(source,templateName);!1===docs&&(docs=findDocsSection(originalSource,templateName)),docs&&(source=docs),$('[data-region="displaytemplatesource"]').text(source);var example=source.match(/Example context \(json\):([\s\S]*)/),context=!1;if(example){var rawJSON=example[1].trim();try{context=$.parseJSON(rawJSON)}catch(e){log.debug("Could not parse json example context for template."),log.debug(e)}}context?templates.render(templateName,context).done((function(html,js){templates.replaceNodeContents($('[data-region="displaytemplateexample"]'),html,js)})).fail(notification.exception):str.get_string("templatehasnoexample","tool_templatelibrary").done((function(s){$('[data-region="displaytemplateexample"]').text(s)})).fail(notification.exception)}(templateName,source,originalSource)})).fail(notification.exception)};return $('[data-region="list-templates"]').on("click","[data-templatename]",(function(e){var templatename=$(this).data("templatename");e.preventDefault(),loadTemplate(templatename)})),{}})); /** * This module adds ajax search functions to the template library page. * * @module tool_templatelibrary/search * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("tool_templatelibrary/search",["jquery","core/ajax","core/log","core/notification","core/templates","core/config"],(function($,ajax,log,notification,templates,config){var reloadListTemplate=function(templateList){templates.render("tool_templatelibrary/search_results",{templates:templateList}).done((function(result,js){templates.replaceNode($('[data-region="searchresults"]'),result,js)})).fail(notification.exception)},refreshSearch=function(themename){var componentStr=$('[data-field="component"]').val(),searchStr=$('[data-region="list-templates"] [data-region="input"]').val();""!==searchStr?$('[data-region="list-templates"] [data-action="clearsearch"]').removeClass("d-none"):$('[data-region="list-templates"] [data-action="clearsearch"]').addClass("d-none"),ajax.call([{methodname:"tool_templatelibrary_list_templates",args:{component:componentStr,search:searchStr,themename:themename},done:reloadListTemplate,fail:notification.exception}],!0,!1)},throttle=null,changeHandler=function(){var callback,delay;callback=refreshSearch.bind(this,config.theme),delay=400,null!==throttle&&window.clearTimeout(throttle),throttle=window.setTimeout((function(){callback(),throttle=null}),delay)};return $('[data-region="list-templates"]').on("change",'[data-field="component"]',changeHandler),$('[data-region="list-templates"]').on("input",'[data-region="input"]',changeHandler),$('[data-action="clearsearch"]').on("click",(function(){$('[data-region="input"]').val(""),refreshSearch(config.theme),$(this).addClass("d-none")})),refreshSearch(config.theme),{}})); define("tool_usertours/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.eventTypes=void 0;_exports.eventTypes={stepRender:"tool_usertours/stepRender",stepRendered:"tool_usertours/stepRendered",tourStart:"tool_usertours/tourStart",tourStarted:"tool_usertours/tourStarted",tourEnd:"tool_usertours/tourEnd",tourEnded:"tool_usertours/tourEnded",stepHide:"tool_usertours/stepHide",stepHidden:"tool_usertours/stepHidden"}})); define("tool_usertours/filter_cssselector",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.filterMatches=void 0;_exports.filterMatches=function(tourConfig){let filterValues=tourConfig.filtervalues.cssselector;return!filterValues[0]||!!document.querySelector(filterValues[0])}})); define("tool_usertours/repository",["exports","core/ajax","core/config"],(function(_exports,_ajax,_config){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.resetTourState=_exports.markTourComplete=_exports.markStepShown=_exports.fetchTour=void 0,_config=(obj=_config)&&obj.__esModule?obj:{default:obj};_exports.resetTourState=tourid=>(0,_ajax.call)([{methodname:"tool_usertours_reset_tour",args:{tourid:tourid,context:_config.default.contextid,pageurl:window.location.href}}])[0];_exports.markTourComplete=(stepid,tourid,stepindex)=>(0,_ajax.call)([{methodname:"tool_usertours_complete_tour",args:{stepid:stepid,stepindex:stepindex,tourid:tourid,context:_config.default.contextid,pageurl:window.location.href}}])[0];_exports.fetchTour=tourid=>(0,_ajax.call)([{methodname:"tool_usertours_fetch_and_start_tour",args:{tourid:tourid,context:_config.default.contextid,pageurl:window.location.href}}])[0];_exports.markStepShown=(stepid,tourid,stepindex)=>(0,_ajax.call)([{methodname:"tool_usertours_step_shown",args:{tourid:tourid,stepid:stepid,stepindex:stepindex,context:_config.default.contextid,pageurl:window.location.href}}])[0]})); define("tool_usertours/usertours",["exports","./tour","core/templates","core/log","core/notification","./repository","core/pending","./events"],(function(_exports,_tour,_templates,_log,_notification,tourRepository,_pending,_events){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.resetTourState=_exports.init=void 0,_tour=_interopRequireDefault(_tour),_templates=_interopRequireDefault(_templates),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification),tourRepository=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(tourRepository),_pending=_interopRequireDefault(_pending);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let currentTour=null,tourId=null,restartTourAndKeepProgress=!1,currentStepNo=null;_exports.init=async(tourDetails,filters)=>{const requirements=[];filters.forEach((filter=>{requirements.push("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["tool_usertours/filter_".concat(filter)],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("tool_usertours/filter_".concat(filter))):Promise.resolve(_systemImportTransformerGlobalIdentifier["tool_usertours/filter_".concat(filter)]))}));const matchingTour=((tourDetails,filters)=>tourDetails.find((tour=>filters.some((filter=>!filter||!filter.filterMatches||filter.filterMatches(tour))))))(tourDetails,await Promise.all(requirements));if(!matchingTour)return;tourId=matchingTour.tourId;let startTour=matchingTour.startTour;void 0===startTour&&(startTour=!0),startTour&&fetchTour(tourId),addResetLink(),document.querySelector("body").addEventListener("click",(e=>{e.target.closest("#resetpagetour")&&(e.preventDefault(),resetTourState(tourId))})),window.addEventListener("resize",(()=>{currentTour&¤tTour.tourRunning&&(clearTimeout(window.resizedFinished),window.resizedFinished=setTimeout((()=>{currentStepNo=currentTour.getCurrentStepNumber(),restartTourAndKeepProgress=!0,resetTourState(tourId)}),250))}))};const fetchTour=async tourId=>{const pendingPromise=new _pending.default("admin_usertour_fetchTour:".concat(tourId));try{const response=await tourRepository.fetchTour(tourId);if(response.hasOwnProperty("tourconfig")){const{html:html}=await _templates.default.renderForPromise("tool_usertours/tourstep",response.tourconfig);startBootstrapTour(tourId,html,response.tourconfig)}pendingPromise.resolve()}catch(error){pendingPromise.resolve(),_notification.default.exception(error)}},addResetLink=()=>{const pendingPromise=new _pending.default("admin_usertour_addResetLink");_templates.default.render("tool_usertours/resettour",{}).then((function(html,js){_templates.default.appendNodeContents((()=>{let location=document.querySelector(".tool_usertours-resettourcontainer");return location||(location=document.querySelector(".logininfo"),location||(location=document.querySelector("footer"),location||document.body))})(),html,js)})).catch().then(pendingPromise.resolve).catch()},startBootstrapTour=(tourId,template,tourConfig)=>{currentTour&¤tTour.tourRunning&&(currentTour.endTour(),currentTour=null),document.addEventListener(_events.eventTypes.tourEnded,markTourComplete),document.addEventListener(_events.eventTypes.stepRenderer,markStepShown),tourConfig.tourName=tourConfig.name,delete tourConfig.name,tourConfig.template=template,tourConfig.steps=tourConfig.steps.map((function(step){return void 0!==step.element&&(step.target=step.element,delete step.element),void 0!==step.reflex&&(step.moveOnClick=!!step.reflex,delete step.reflex),void 0!==step.content&&(step.body=step.content,delete step.content),step})),currentTour=new _tour.default(tourConfig);let startAt=0;return restartTourAndKeepProgress&¤tStepNo&&(startAt=currentStepNo,restartTourAndKeepProgress=!1,currentStepNo=null),currentTour.startTour(startAt)},markStepShown=e=>{const tour=e.detail.tour,stepConfig=tour.getStepConfig(tour.getCurrentStepNumber());tourRepository.markStepShown(stepConfig.stepid,tourId,tour.getCurrentStepNumber()).catch(_log.default.error)},markTourComplete=e=>{document.removeEventListener(_events.eventTypes.tourEnded,markTourComplete),document.removeEventListener(_events.eventTypes.stepRenderer,markStepShown);const tour=e.detail.tour,stepConfig=tour.getStepConfig(tour.getCurrentStepNumber());tourRepository.markTourComplete(stepConfig.stepid,tourId,tour.getCurrentStepNumber()).catch(_log.default.error)},resetTourState=tourId=>tourRepository.resetTourState(tourId).then((response=>{response.startTour&&fetchTour(response.startTour)})).catch(_notification.default.exception);_exports.resetTourState=resetTourState})); define("tool_usertours/managesteps",["exports","core/prefetch","core/str","core/notification"],(function(_exports,_prefetch,_str,_notification){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setup=void 0;const removeStepHandler=e=>{const deleteButton=e.target.closest('[data-action="delete"]');deleteButton&&(e.preventDefault(),removeStepFromLink(deleteButton.href))},removeStepFromLink=targetUrl=>{(0,_notification.confirm)((0,_str.get_string)("confirmstepremovaltitle","tool_usertours"),(0,_str.get_string)("confirmstepremovalquestion","tool_usertours"),(0,_str.get_string)("yes","core"),(0,_str.get_string)("no","core"),(()=>{window.location=targetUrl}))};_exports.setup=()=>{(0,_prefetch.prefetchStrings)("tool_usertours",["confirmstepremovaltitle","confirmstepremovalquestion"]),(0,_prefetch.prefetchStrings)("core",["yes","no"]),document.querySelector("body").addEventListener("click",removeStepHandler)}})); define("tool_usertours/managetours",["exports","core/prefetch","core/str","core/notification"],(function(_exports,_prefetch,_str,_notification){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setup=void 0;const removeTourHandler=e=>{const deleteButton=e.target.closest('[data-action="delete"]');deleteButton&&(e.preventDefault(),removeTourFromLink(deleteButton.href))},removeTourFromLink=targetUrl=>{(0,_notification.confirm)((0,_str.get_string)("confirmtourremovaltitle","tool_usertours"),(0,_str.get_string)("confirmtourremovalquestion","tool_usertours"),(0,_str.get_string)("yes","core"),(0,_str.get_string)("no","core"),(()=>{window.location=targetUrl}))};_exports.setup=()=>{(0,_prefetch.prefetchStrings)("tool_usertours",["confirmtourremovaltitle","confirmtourremovalquestion"]),(0,_prefetch.prefetchStrings)("core",["yes","no"]),document.querySelector("body").addEventListener("click",removeTourHandler)}})); define("tool_usertours/tour",["exports","jquery","core/aria","core/popper","core/event_dispatcher","./events","core/str","core/prefetch"],(function(_exports,_jquery,Aria,_popper,_event_dispatcher,_events,_str,_prefetch){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),Aria=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Aria),_popper=_interopRequireDefault(_popper);var _default=class{constructor(config){var obj,key,value;value=!1,(key="tourRunning")in(obj=this)?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,this.init(config)}init(config){this.eventHandlers={},this.reset(),this.originalConfiguration=config||{},this.configure.apply(this,arguments),this.possitionNeedToBeRecalculated=!1,this.recalculatedNo=0;try{this.storage=window.sessionStorage,this.storageKey="tourstate_"+this.tourName}catch(e){this.storage=!1,this.storageKey=""}return(0,_prefetch.prefetchStrings)("tool_usertours",["nextstep_sequence","skip_tour"]),this}reset(){return this.hide(),this.eventHandlers=[],this.resetStepListeners(),this.originalConfiguration={},this.steps=[],this.currentStepNumber=0,this}configure(config){if("object"==typeof config){if(void 0!==config.tourName&&(this.tourName=config.tourName),config.eventHandlers)for(let eventName in config.eventHandlers)config.eventHandlers[eventName].forEach((function(handler){this.addEventHandler(eventName,handler)}),this);this.resetStepDefaults(!0),"object"==typeof config.steps&&(this.steps=config.steps),void 0!==config.template&&(this.templateContent=config.template)}return this.checkMinimumRequirements(),this}checkMinimumRequirements(){if(!this.tourName)throw new Error("Tour Name required");if(!this.steps||!this.steps.length)throw new Error("Steps must be specified")}resetStepDefaults(loadOriginalConfiguration){return void 0===loadOriginalConfiguration&&(loadOriginalConfiguration=!0),this.stepDefaults={},loadOriginalConfiguration&&void 0!==this.originalConfiguration.stepDefaults?this.setStepDefaults(this.originalConfiguration.stepDefaults):this.setStepDefaults({}),this}setStepDefaults(stepDefaults){return this.stepDefaults||(this.stepDefaults={}),_jquery.default.extend(this.stepDefaults,{element:"",placement:"top",delay:0,moveOnClick:!1,moveAfterTime:0,orphan:!1,direction:1},stepDefaults),this}getCurrentStepNumber(){return parseInt(this.currentStepNumber,10)}setCurrentStepNumber(stepNumber){if(this.currentStepNumber=stepNumber,this.storage)try{this.storage.setItem(this.storageKey,stepNumber)}catch(e){e.code===DOMException.QUOTA_EXCEEDED_ERR&&this.storage.removeItem(this.storageKey)}}getNextStepNumber(stepNumber){void 0===stepNumber&&(stepNumber=this.getCurrentStepNumber());let nextStepNumber=stepNumber+1;for(;nextStepNumber<=this.steps.length;){if(this.isStepPotentiallyVisible(this.getStepConfig(nextStepNumber)))return nextStepNumber;nextStepNumber++}return null}getPreviousStepNumber(stepNumber){void 0===stepNumber&&(stepNumber=this.getCurrentStepNumber());let previousStepNumber=stepNumber-1;for(;previousStepNumber>=0;){if(this.isStepPotentiallyVisible(this.getStepConfig(previousStepNumber)))return previousStepNumber;previousStepNumber--}return null}isLastStep(stepNumber){return null===this.getNextStepNumber(stepNumber)}isStepPotentiallyVisible(stepConfig){return!!stepConfig&&(!!this.isStepActuallyVisible(stepConfig)||(!(void 0===stepConfig.orphan||!stepConfig.orphan)||!(void 0===stepConfig.delay||!stepConfig.delay)))}getPotentiallyVisibleSteps(){let position=1,result=[];for(let stepNumber=0;stepNumber<this.steps.length;stepNumber++){const stepConfig=this.getStepConfig(stepNumber);this.isStepPotentiallyVisible(stepConfig)&&(result[stepNumber]={stepId:stepConfig.stepid,position:position},position++)}return result}isStepActuallyVisible(stepConfig){if(!stepConfig)return!1;if(!this.isCSSAllowed())return!1;let target=this.getStepTarget(stepConfig);return!!(target&&target.length&&target.is(":visible"))&&!!target.length}isCSSAllowed(){const testCSSElement=document.createElement("div");testCSSElement.classList.add("hide"),document.body.appendChild(testCSSElement);const isAllowed="none"===window.getComputedStyle(testCSSElement).display;return testCSSElement.remove(),isAllowed}next(){return this.gotoStep(this.getNextStepNumber())}previous(){return this.gotoStep(this.getPreviousStepNumber(),-1)}gotoStep(stepNumber,direction){if(stepNumber<0)return this.endTour();let stepConfig=this.getStepConfig(stepNumber);return null===stepConfig?this.endTour():this._gotoStep(stepConfig,direction)}_gotoStep(stepConfig,direction){if(!stepConfig)return this.endTour();if(void 0!==stepConfig.delay&&stepConfig.delay&&!stepConfig.delayed)return stepConfig.delayed=!0,window.setTimeout(this._gotoStep.bind(this),stepConfig.delay,stepConfig,direction),this;if(!stepConfig.orphan&&!this.isStepActuallyVisible(stepConfig)){let fn=-1==direction?"getPreviousStepNumber":"getNextStepNumber";return this.gotoStep(this[fn](stepConfig.stepNumber),direction)}this.hide();return this.dispatchEvent(_events.eventTypes.stepRender,{stepConfig:stepConfig},!0).defaultPrevented||(this.renderStep(stepConfig),this.dispatchEvent(_events.eventTypes.stepRendered,{stepConfig:stepConfig})),this}getStepConfig(stepNumber){if(null===stepNumber||stepNumber<0||stepNumber>=this.steps.length)return null;let stepConfig=this.normalizeStepConfig(this.steps[stepNumber]);return stepConfig=_jquery.default.extend(stepConfig,{stepNumber:stepNumber}),stepConfig}normalizeStepConfig(stepConfig){return void 0!==stepConfig.reflex&&void 0===stepConfig.moveAfterClick&&(stepConfig.moveAfterClick=stepConfig.reflex),void 0!==stepConfig.element&&void 0===stepConfig.target&&(stepConfig.target=stepConfig.element),void 0!==stepConfig.content&&void 0===stepConfig.body&&(stepConfig.body=stepConfig.content),stepConfig=_jquery.default.extend({},this.stepDefaults,stepConfig),(stepConfig=_jquery.default.extend({},{attachTo:stepConfig.target,attachPoint:"after"},stepConfig)).attachTo&&(stepConfig.attachTo=(0,_jquery.default)(stepConfig.attachTo).first()),stepConfig}getStepTarget(stepConfig){return stepConfig.target?(0,_jquery.default)(stepConfig.target):null}dispatchEvent(eventName){let detail=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},cancelable=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return(0,_event_dispatcher.dispatchEvent)(eventName,{tour:this,...detail},document,{cancelable:cancelable})}addEventHandler(eventName,handler){return void 0===this.eventHandlers[eventName]&&(this.eventHandlers[eventName]=[]),this.eventHandlers[eventName].push(handler),this}processStepListeners(stepConfig){if(this.listeners.push({node:this.currentStepNode,args:["click",'[data-role="next"]',_jquery.default.proxy(this.next,this)]},{node:this.currentStepNode,args:["click",'[data-role="end"]',_jquery.default.proxy(this.endTour,this)]},{node:(0,_jquery.default)('[data-flexitour="backdrop"]'),args:["click",_jquery.default.proxy(this.hide,this)]},{node:(0,_jquery.default)("body"),args:["keydown",_jquery.default.proxy(this.handleKeyDown,this)]}),stepConfig.moveOnClick){var targetNode=this.getStepTarget(stepConfig);this.listeners.push({node:targetNode,args:["click",_jquery.default.proxy((function(e){0===(0,_jquery.default)(e.target).parents('[data-flexitour="container"]').length&&window.setTimeout(_jquery.default.proxy(this.next,this),500)}),this)]})}return this.listeners.forEach((function(listener){listener.node.on.apply(listener.node,listener.args)})),this}resetStepListeners(){return this.listeners&&this.listeners.forEach((function(listener){listener.node.off.apply(listener.node,listener.args)})),this.listeners=[],this}renderStep(stepConfig){this.currentStepConfig=stepConfig,this.setCurrentStepNumber(stepConfig.stepNumber);let template=(0,_jquery.default)(this.getTemplateContent());template.find('[data-placeholder="title"]').html(stepConfig.title),template.find('[data-placeholder="body"]').html(stepConfig.body);const nextBtn=template.find('[data-role="next"]'),endBtn=template.find('[data-role="end"]');if(this.isLastStep(stepConfig.stepNumber)?(nextBtn.hide(),endBtn.removeClass("btn-secondary").addClass("btn-primary")):(nextBtn.prop("disabled",!1),(0,_str.get_string)("skip_tour","tool_usertours").then((value=>{endBtn.html(value)})).catch()),nextBtn.attr("role","button"),endBtn.attr("role","button"),this.originalConfiguration.displaystepnumbers){const stepsPotentiallyVisible=this.getPotentiallyVisibleSteps(),totalStepsPotentiallyVisible=stepsPotentiallyVisible.length,position=stepsPotentiallyVisible[stepConfig.stepNumber].position;totalStepsPotentiallyVisible>1&&(0,_str.get_string)("nextstep_sequence","tool_usertours",{position:position,total:totalStepsPotentiallyVisible}).then((value=>{nextBtn.html(value)})).catch()}return stepConfig.template=template,this.addStepToPage(stepConfig),this.processStepListeners(stepConfig),this}getTemplateContent(){return(0,_jquery.default)(this.templateContent).clone()}addStepToPage(stepConfig){let currentStepNode=(0,_jquery.default)('<span data-flexitour="container"></span>').html(stepConfig.template).hide(),animationTarget=(0,_jquery.default)("body, html").stop(!0,!0);if(this.isStepActuallyVisible(stepConfig)){let targetNode=this.getStepTarget(stepConfig);targetNode.parents('[data-usertour="scroller"]').length&&(animationTarget=targetNode.parents('[data-usertour="scroller"]')),targetNode.data("flexitour","target");let zIndex=this.calculateZIndex(targetNode);zIndex&&(stepConfig.zIndex=zIndex+1),stepConfig.zIndex&¤tStepNode.css("zIndex",stepConfig.zIndex+1),this.positionBackdrop(stepConfig),(0,_jquery.default)(document.body).append(currentStepNode),this.currentStepNode=currentStepNode,this.currentStepNode.css({top:0,left:0}),animationTarget.animate({scrollTop:this.calculateScrollTop(stepConfig)}).promise().then(function(){this.positionStep(stepConfig),this.revealStep(stepConfig)}.bind(this)).catch((function(){}))}else stepConfig.orphan&&(stepConfig.isOrphan=!0,stepConfig.attachTo=(0,_jquery.default)("body").first(),stepConfig.attachPoint="append",this.positionBackdrop(stepConfig),currentStepNode.addClass("orphan"),(0,_jquery.default)(document.body).append(currentStepNode),this.currentStepNode=currentStepNode,this.currentStepNode.css("position","fixed"),this.currentStepPopper=new _popper.default((0,_jquery.default)("body"),this.currentStepNode[0],{removeOnDestroy:!0,placement:stepConfig.placement+"-start",arrowElement:'[data-role="arrow"]',modifiers:{hide:{enabled:!1},applyStyle:{onLoad:null,enabled:!1}},onCreate:()=>{const images=this.currentStepNode.find("img");images.length&&images.on("load",(()=>{this.calculateStepPositionInPage(currentStepNode)})),this.calculateStepPositionInPage(currentStepNode)}}),this.revealStep(stepConfig));return this}revealStep(stepConfig){return this.currentStepNode.fadeIn("",_jquery.default.proxy((function(){this.announceStep(stepConfig),this.currentStepNode.focus(),window.setTimeout(_jquery.default.proxy((function(){this.currentStepNode&&this.currentStepNode.focus()}),this),100)}),this)),this}announceStep(stepConfig){let stepId="tour-step-"+this.tourName+"-"+stepConfig.stepNumber;this.currentStepNode.attr("id",stepId);let bodyRegion=this.currentStepNode.find('[data-placeholder="body"]').first();bodyRegion.attr("id",stepId+"-body"),bodyRegion.attr("role","document");let headerRegion=this.currentStepNode.find('[data-placeholder="title"]').first();headerRegion.attr("id",stepId+"-title"),headerRegion.attr("aria-labelledby",stepId+"-body"),this.currentStepNode.attr("role","dialog"),this.currentStepNode.attr("tabindex",0),this.currentStepNode.attr("aria-labelledby",stepId+"-title"),this.currentStepNode.attr("aria-describedby",stepId+"-body");let target=this.getStepTarget(stepConfig);return target&&(target.data("original-tabindex",target.attr("tabindex")),target.attr("tabindex")||target.attr("tabindex",0),target.data("original-describedby",target.attr("aria-describedby")).attr("aria-describedby",stepId+"-body")),this.accessibilityShow(stepConfig),this}handleKeyDown(e){let tabbableSelector="a[href], link[href], [draggable=true], [contenteditable=true], ";switch(tabbableSelector+=":input:enabled, [tabindex], button:enabled",e.keyCode){case 27:this.endTour();break;case 9:(function(){if(!this.currentStepConfig.hasBackdrop)return;let currentIndex,nextIndex,nextNode,focusRelevant,activeElement=(0,_jquery.default)(document.activeElement),stepTarget=this.getStepTarget(this.currentStepConfig),tabbableNodes=(0,_jquery.default)(tabbableSelector),dialogContainer=(0,_jquery.default)('span[data-flexitour="container"]');if(stepTarget&&(tabbableNodes=tabbableNodes.filter((function(index,element){return null!==stepTarget&&(stepTarget.has(element).length||dialogContainer.has(element).length||stepTarget.is(element)||dialogContainer.is(element))}))),tabbableNodes.each((function(index,element){return!activeElement.is(element)||(currentIndex=index,!1)})),null!=currentIndex){let direction=1;e.shiftKey&&(direction=-1),nextIndex=currentIndex;do{nextIndex+=direction,nextNode=(0,_jquery.default)(tabbableNodes[nextIndex])}while(nextNode.length&&nextNode.is(":disabled")||nextNode.is(":hidden"));nextNode.length?(focusRelevant=nextNode.closest(stepTarget).length,focusRelevant=focusRelevant||nextNode.closest(this.currentStepNode).length):focusRelevant=!1}focusRelevant?nextNode.focus():e.shiftKey?this.currentStepNode.find(tabbableSelector).last().focus():this.currentStepConfig.isOrphan?this.currentStepNode.focus():stepTarget.focus(),e.preventDefault()}).call(this)}}startTour(startAt){if(this.storage&&void 0===startAt){let storageStartValue=this.storage.getItem(this.storageKey);if(storageStartValue){let storageStartAt=parseInt(storageStartValue,10);storageStartAt<=this.steps.length&&(startAt=storageStartAt)}}void 0===startAt&&(startAt=this.getCurrentStepNumber());return this.dispatchEvent(_events.eventTypes.tourStart,{startAt:startAt},!0).defaultPrevented||(this.gotoStep(startAt),this.tourRunning=!0,this.dispatchEvent(_events.eventTypes.tourStarted,{startAt:startAt})),this}restartTour(){return this.startTour(0)}endTour(){if(this.dispatchEvent(_events.eventTypes.tourEnd,{},!0).defaultPrevented)return this;if(this.currentStepConfig){let previousTarget=this.getStepTarget(this.currentStepConfig);previousTarget&&(previousTarget.attr("tabindex")||previousTarget.attr("tabindex","-1"),previousTarget.focus())}return this.hide(!0),this.tourRunning=!1,this.dispatchEvent(_events.eventTypes.tourEnded),this}hide(transition){if(this.dispatchEvent(_events.eventTypes.stepHide,{},!0).defaultPrevented)return this;if(this.currentStepNode&&this.currentStepNode.length&&(this.currentStepNode.hide(),this.currentStepPopper&&this.currentStepPopper.destroy()),this.currentStepConfig){let target=this.getStepTarget(this.currentStepConfig);target&&(target.data("original-labelledby")&&target.attr("aria-labelledby",target.data("original-labelledby")),target.data("original-describedby")&&target.attr("aria-describedby",target.data("original-describedby")),target.data("original-tabindex")?target.attr("tabindex",target.data("tabindex")):window.setTimeout((()=>{target.removeAttr("tabindex")}),400)),this.currentStepConfig=null}let fadeTime=0;if(transition&&(fadeTime=400),(0,_jquery.default)('[data-flexitour="step-background"]').remove(),(0,_jquery.default)('[data-flexitour="step-backdrop"]').removeAttr("data-flexitour"),(0,_jquery.default)('[data-flexitour="backdrop"]').fadeOut(fadeTime,(function(){(0,_jquery.default)(this).remove()})),this.currentStepNode&&this.currentStepNode.length){let stepId=this.currentStepNode.attr("id");if(stepId){let currentStepElement='[aria-describedby="'+stepId+'-body"]';(0,_jquery.default)(currentStepElement).removeAttr("tabindex"),(0,_jquery.default)(currentStepElement).removeAttr("aria-describedby")}}return this.resetStepListeners(),this.accessibilityHide(),this.dispatchEvent(_events.eventTypes.stepHidden),this.currentStepNode=null,this.currentStepPopper=null,this}show(){let startAt=this.getCurrentStepNumber();return this.gotoStep(startAt)}getStepContainer(){return(0,_jquery.default)(this.currentStepNode)}calculateScrollTop(stepConfig){let viewportHeight=(0,_jquery.default)(window).height(),targetNode=this.getStepTarget(stepConfig),scrollParent=(0,_jquery.default)(window);targetNode.parents('[data-usertour="scroller"]').length&&(scrollParent=targetNode.parents('[data-usertour="scroller"]'));let scrollTop=scrollParent.scrollTop();return scrollTop="top"===stepConfig.placement?targetNode.offset().top-viewportHeight/2:"bottom"===stepConfig.placement?targetNode.offset().top+targetNode.height()+scrollTop-viewportHeight/2:targetNode.height()<=.8*viewportHeight?targetNode.offset().top-(viewportHeight-targetNode.height())/2:targetNode.offset().top-.2*viewportHeight,scrollTop=Math.max(0,scrollTop),scrollTop=Math.min((0,_jquery.default)(document).height()-viewportHeight,scrollTop),Math.ceil(scrollTop)}calculateStepPositionInPage(currentStepNode){let top=10;const viewportHeight=(0,_jquery.default)(window).height(),stepHeight=currentStepNode.height(),viewportWidth=(0,_jquery.default)(window).width(),stepWidth=currentStepNode.width();if(viewportHeight>=stepHeight+20)top=Math.ceil((viewportHeight-stepHeight)/2);else{var _currentStepNode$find,_currentStepNode$find2;const maxHeight=viewportHeight-20-(null!==(_currentStepNode$find=currentStepNode.find(".modal-header").first().outerHeight())&&void 0!==_currentStepNode$find?_currentStepNode$find:0)-(null!==(_currentStepNode$find2=currentStepNode.find(".modal-footer").first().outerHeight())&&void 0!==_currentStepNode$find2?_currentStepNode$find2:0);currentStepNode.find('[data-placeholder="body"]').first().css({"max-height":maxHeight+"px",overflow:"auto"})}currentStepNode.offset({top:top,left:Math.ceil((viewportWidth-stepWidth)/2)})}positionStep(stepConfig){let flipBehavior,content=this.currentStepNode,thisT=this;if(!content||!content.length)return this;switch(stepConfig.placement=this.recalculatePlacement(stepConfig),stepConfig.placement){case"left":flipBehavior=["left","right","top","bottom"];break;case"right":flipBehavior=["right","left","top","bottom"];break;case"top":flipBehavior=["top","bottom","right","left"];break;case"bottom":flipBehavior=["bottom","top","right","left"];break;default:flipBehavior="flip"}let target=this.getStepTarget(stepConfig);var config={placement:stepConfig.placement+"-start",removeOnDestroy:!0,modifiers:{flip:{behaviour:flipBehavior},arrow:{element:'[data-role="arrow"]'}},onCreate:function(data){recalculateArrowPosition(data),recalculateStepPosition(data)},onUpdate:function(data){recalculateArrowPosition(data),thisT.possitionNeedToBeRecalculated&&(thisT.recalculatedNo++,thisT.possitionNeedToBeRecalculated=!1,recalculateStepPosition(data))}};let recalculateArrowPosition=function(data){let placement=data.placement.split("-")[0];const isVertical=-1!==["left","right"].indexOf(placement),arrowElement=data.instance.popper.querySelector('[data-role="arrow"]'),stepElement=(0,_jquery.default)(data.instance.popper.querySelector('[data-role="flexitour-step"]'));if(isVertical){let arrowHeight=parseFloat(window.getComputedStyle(arrowElement).height),arrowOffset=parseFloat(window.getComputedStyle(arrowElement).top),popperHeight=parseFloat(window.getComputedStyle(data.instance.popper).height),popperOffset=parseFloat(window.getComputedStyle(data.instance.popper).top),popperBorderWidth=parseFloat(stepElement.css("borderTopWidth")),popperBorderRadiusWidth=2*parseFloat(stepElement.css("borderTopLeftRadius")),arrowPos=arrowOffset+arrowHeight/2,maxPos=popperHeight+popperOffset-popperBorderWidth-popperBorderRadiusWidth,minPos=popperOffset+popperBorderWidth+popperBorderRadiusWidth;if(arrowPos>=maxPos||arrowPos<=minPos){let newArrowPos=0;newArrowPos=arrowPos>popperHeight/2?maxPos-arrowHeight:minPos+arrowHeight,(0,_jquery.default)(arrowElement).css("top",newArrowPos)}}else{let arrowWidth=parseFloat(window.getComputedStyle(arrowElement).width),arrowOffset=parseFloat(window.getComputedStyle(arrowElement).left),popperWidth=parseFloat(window.getComputedStyle(data.instance.popper).width),popperOffset=parseFloat(window.getComputedStyle(data.instance.popper).left),popperBorderWidth=parseFloat(stepElement.css("borderTopWidth")),popperBorderRadiusWidth=2*parseFloat(stepElement.css("borderTopLeftRadius")),arrowPos=arrowOffset+arrowWidth/2,maxPos=popperWidth+popperOffset-popperBorderWidth-popperBorderRadiusWidth,minPos=popperOffset+popperBorderWidth+popperBorderRadiusWidth;if(arrowPos>=maxPos||arrowPos<=minPos){let newArrowPos=0;newArrowPos=arrowPos>popperWidth/2?maxPos-arrowWidth:minPos+arrowWidth,(0,_jquery.default)(arrowElement).css("left",newArrowPos)}}};const recalculateStepPosition=function(data){var _headerEle$outerHeigh,_footerEle$outerHeigh;const placement=data.placement.split("-")[0],isVertical=-1!==["left","right"].indexOf(placement),popperElement=(0,_jquery.default)(data.instance.popper),targetElement=(0,_jquery.default)(data.instance.reference),arrowElement=popperElement.find('[data-role="arrow"]'),stepElement=popperElement.find('[data-role="flexitour-step"]'),viewportHeight=(0,_jquery.default)(window).height(),viewportWidth=(0,_jquery.default)(window).width(),arrowHeight=parseFloat(arrowElement.outerHeight(!0)),popperHeight=parseFloat(popperElement.outerHeight(!0)),targetHeight=parseFloat(targetElement.outerHeight(!0)),arrowWidth=parseFloat(arrowElement.outerWidth(!0)),popperWidth=parseFloat(popperElement.outerWidth(!0)),targetWidth=parseFloat(targetElement.outerWidth(!0));let maxHeight;if(thisT.recalculatedNo>1&&(thisT.currentStepPopper.options.placement=isVertical?"auto-left":"auto-bottom"),thisT.recalculatedNo>2)return;if(isVertical){const leftSpace=targetElement.offset().left>0?targetElement.offset().left:0,rightSpace=viewportWidth-leftSpace-targetWidth,remainingSpace=leftSpace>=rightSpace?leftSpace:rightSpace;if(maxHeight=viewportHeight-20,remainingSpace<popperWidth+arrowWidth){const maxWidth=remainingSpace-10-arrowWidth;maxWidth>0&&(popperElement.css({"max-width":maxWidth+"px"}),thisT.possitionNeedToBeRecalculated=!0)}else maxHeight<popperHeight&&popperElement.css({"max-height":maxHeight+"px"})}else{const topSpace=targetElement.offset().top>0?targetElement.offset().top:0,bottomSpace=viewportHeight-topSpace-targetHeight,remainingSpace=topSpace>=bottomSpace?topSpace:bottomSpace;maxHeight=remainingSpace-10-arrowHeight,remainingSpace<popperHeight+arrowHeight&&(thisT.possitionNeedToBeRecalculated=!0)}const currentStepBody=stepElement.find('[data-placeholder="body"]').first(),headerEle=stepElement.find(".modal-header").first(),footerEle=stepElement.find(".modal-footer").first();maxHeight=maxHeight-(null!==(_headerEle$outerHeigh=headerEle.outerHeight(!0))&&void 0!==_headerEle$outerHeigh?_headerEle$outerHeigh:0)-(null!==(_footerEle$outerHeigh=footerEle.outerHeight(!0))&&void 0!==_footerEle$outerHeigh?_footerEle$outerHeigh:0),maxHeight>0?(headerEle.removeClass("minimal"),footerEle.removeClass("minimal"),currentStepBody.css({"max-height":maxHeight+"px",overflow:"auto"})):(headerEle.addClass("minimal"),footerEle.addClass("minimal")),thisT.currentStepPopper.update()};let background=(0,_jquery.default)('[data-flexitour="step-background"]');return background.length&&(target=background),this.currentStepPopper=new _popper.default(target,content[0],config),this}recalculatePlacement(stepConfig){let target=this.getStepTarget(stepConfig),widthContent=this.currentStepNode.width()+16,targetOffsetLeft=target.offset().left-10,targetOffsetRight=target.offset().left+target.width()+10,placement=stepConfig.placement;return-1!==["left","right"].indexOf(placement)&&targetOffsetLeft<widthContent+10&&targetOffsetRight+widthContent+10>document.documentElement.clientWidth&&(placement="top"),placement}positionBackdrop(stepConfig){if(stepConfig.backdrop){this.currentStepConfig.hasBackdrop=!0;let backdrop=(0,_jquery.default)('<div data-flexitour="backdrop"></div>');if(stepConfig.zIndex?"append"===stepConfig.attachPoint?stepConfig.attachTo.append(backdrop):backdrop.insertAfter(stepConfig.attachTo):(0,_jquery.default)("body").append(backdrop),this.isStepActuallyVisible(stepConfig)){let background=(0,_jquery.default)('[data-flexitour="step-background"]');background.length||(background=(0,_jquery.default)('<div data-flexitour="step-background"></div>'));let targetNode=this.getStepTarget(stepConfig),buffer=10,colorNode=targetNode;buffer&&(colorNode=(0,_jquery.default)("body"));let drawertop=0;if(targetNode.parents('[data-usertour="scroller"]').length){const scrollerElement=targetNode.parents('[data-usertour="scroller"]'),navigationBuffer=scrollerElement.offset().top;scrollerElement.scrollTop()>=navigationBuffer&&(drawertop=scrollerElement.scrollTop()-navigationBuffer,background.css({position:"fixed"}))}background.css({width:targetNode.outerWidth()+buffer+buffer,height:targetNode.outerHeight()+buffer+buffer,left:targetNode.offset().left-buffer,top:targetNode.offset().top+drawertop-buffer,backgroundColor:this.calculateInherittedBackgroundColor(colorNode)}),targetNode.offset().left<buffer&&background.css({width:targetNode.outerWidth()+targetNode.offset().left+buffer,left:targetNode.offset().left}),targetNode.offset().top+drawertop<buffer&&background.css({height:targetNode.outerHeight()+targetNode.offset().top+buffer,top:targetNode.offset().top});let targetRadius=targetNode.css("borderRadius");targetRadius&&targetRadius!==(0,_jquery.default)("body").css("borderRadius")&&background.css("borderRadius",targetRadius),"absolute"===this.calculatePosition(targetNode)&&background.css("position","fixed");let fader=background.clone();if(fader.css({backgroundColor:backdrop.css("backgroundColor"),opacity:backdrop.css("opacity")}),fader.attr("data-flexitour","step-background-fader"),targetNode.parents('[data-region="fixed-drawer"]').length){let targetClone=targetNode.clone();background.append(targetClone)}stepConfig.zIndex?"append"===stepConfig.attachPoint?stepConfig.attachTo.append(background):(fader.insertAfter(stepConfig.attachTo),background.insertAfter(stepConfig.attachTo)):((0,_jquery.default)("body").append(fader),(0,_jquery.default)("body").append(background)),targetNode.attr("data-flexitour","step-backdrop"),stepConfig.zIndex&&(backdrop.css("zIndex",stepConfig.zIndex),background.css("zIndex",stepConfig.zIndex+1),targetNode.css("zIndex",stepConfig.zIndex+2)),fader.fadeOut("2000",(function(){(0,_jquery.default)(this).remove()}))}}return this}calculateZIndex(elem){for(elem=(0,_jquery.default)(elem);elem.length&&elem[0]!==document;){let position=elem.css("position");if("absolute"===position||"relative"===position||"fixed"===position){let value=parseInt(elem.css("zIndex"),10);if(!isNaN(value)&&0!==value)return value}elem=elem.parent()}return 0}calculateInherittedBackgroundColor(elem){let fakeNode=(0,_jquery.default)("<div>").hide();(0,_jquery.default)("body").append(fakeNode);let fakeElemColor=fakeNode.css("backgroundColor");for(fakeNode.remove(),elem=(0,_jquery.default)(elem);elem.length&&elem[0]!==document;){let color=elem.css("backgroundColor");if(color!==fakeElemColor)return color;elem=elem.parent()}return null}calculatePosition(elem){for(elem=(0,_jquery.default)(elem);elem.length&&elem[0]!==document;){let position=elem.css("position");if("static"!==position)return position;elem=elem.parent()}return null}accessibilityShow(){let hideFunction=function(child){let flexitourRole=child.data("flexitour");if(flexitourRole)switch(flexitourRole){case"container":case"target":return}child.attr("aria-hidden")||(child.attr("data-has-hidden",!0),Aria.hide(child))};this.currentStepNode.siblings().each((function(index,node){hideFunction((0,_jquery.default)(node))})),this.currentStepNode.parentsUntil("body").siblings().each((function(index,node){hideFunction((0,_jquery.default)(node))}))}accessibilityHide(){(0,_jquery.default)("[data-has-hidden]").each((function(index,node){var child;void 0!==(child=(0,_jquery.default)(node)).attr("data-has-hidden")&&(child.removeAttr("data-has-hidden"),Aria.unhide(child))}))}};return _exports.default=_default,_exports.default})); define("tool_xmldb/move",["jquery","core/sortable_list","core/ajax","core/notification"],(function($,SortableList,Ajax,Notification){return{init:function(tableid,moveaction){var origIndex;new SortableList("#"+tableid+" tbody").getElementName=function(element){return $.Deferred().resolve(element.attr("data-name"))},$("#"+tableid+" tbody tr").on(SortableList.EVENTS.DRAGSTART,(function(_,info){origIndex=info.sourceList.children().index(info.element),setTimeout((function(){$(".sortable-list-is-dragged").width(info.element.width())}),501)})).on(SortableList.EVENTS.DROP,(function(_,info){var newIndex=info.targetList.children().index(info.element),t=info.element.find("[data-action="+moveaction+"]");if(info.positionChanged&&t.length){var request={methodname:"tool_xmldb_invoke_move_action",args:{action:moveaction,dir:t.attr("data-dir"),table:t.attr("data-table"),field:t.attr("data-field"),key:t.attr("data-key"),index:t.attr("data-index"),position:newIndex-origIndex}};Ajax.call([request])[0].fail(Notification.exception)}}))}}})); define("theme_boost/bootstrap/alert",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const EVENT_KEY=".".concat("bs.alert"),JQUERY_NO_CONFLICT=_jquery.default.fn.alert,EVENT_CLOSE="close".concat(EVENT_KEY),EVENT_CLOSED="closed".concat(EVENT_KEY),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api");class Alert{constructor(element){this._element=element}static get VERSION(){return"4.6.2"}close(element){let rootElement=this._element;element&&(rootElement=this._getRootElement(element));this._triggerCloseEvent(rootElement).isDefaultPrevented()||this._removeElement(rootElement)}dispose(){_jquery.default.removeData(this._element,"bs.alert"),this._element=null}_getRootElement(element){const selector=_util.default.getSelectorFromElement(element);let parent=!1;return selector&&(parent=document.querySelector(selector)),parent||(parent=(0,_jquery.default)(element).closest(".".concat("alert"))[0]),parent}_triggerCloseEvent(element){const closeEvent=_jquery.default.Event(EVENT_CLOSE);return(0,_jquery.default)(element).trigger(closeEvent),closeEvent}_removeElement(element){if((0,_jquery.default)(element).removeClass("show"),!(0,_jquery.default)(element).hasClass("fade"))return void this._destroyElement(element);const transitionDuration=_util.default.getTransitionDurationFromElement(element);(0,_jquery.default)(element).one(_util.default.TRANSITION_END,(event=>this._destroyElement(element,event))).emulateTransitionEnd(transitionDuration)}_destroyElement(element){(0,_jquery.default)(element).detach().trigger(EVENT_CLOSED).remove()}static _jQueryInterface(config){return this.each((function(){const $element=(0,_jquery.default)(this);let data=$element.data("bs.alert");data||(data=new Alert(this),$element.data("bs.alert",data)),"close"===config&&data[config](this)}))}static _handleDismiss(alertInstance){return function(event){event&&event.preventDefault(),alertInstance.close(this)}}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,'[data-dismiss="alert"]',Alert._handleDismiss(new Alert)),_jquery.default.fn.alert=Alert._jQueryInterface,_jquery.default.fn.alert.Constructor=Alert,_jquery.default.fn.alert.noConflict=()=>(_jquery.default.fn.alert=JQUERY_NO_CONFLICT,Alert._jQueryInterface);var _default=Alert;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/button",["exports","jquery"],(function(_exports,_jquery){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};const NAME="button",EVENT_KEY=".".concat("bs.button"),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api"),EVENT_FOCUS_BLUR_DATA_API="focus".concat(EVENT_KEY).concat(".data-api"," ")+"blur".concat(EVENT_KEY).concat(".data-api"),EVENT_LOAD_DATA_API="load".concat(EVENT_KEY).concat(".data-api");class Button{constructor(element){this._element=element,this.shouldAvoidTriggerChange=!1}static get VERSION(){return"4.6.2"}toggle(){let triggerChangeEvent=!0,addAriaPressed=!0;const rootElement=(0,_jquery.default)(this._element).closest('[data-toggle="buttons"]')[0];if(rootElement){const input=this._element.querySelector('input:not([type="hidden"])');if(input){if("radio"===input.type)if(input.checked&&this._element.classList.contains("active"))triggerChangeEvent=!1;else{const activeElement=rootElement.querySelector(".active");activeElement&&(0,_jquery.default)(activeElement).removeClass("active")}triggerChangeEvent&&("checkbox"!==input.type&&"radio"!==input.type||(input.checked=!this._element.classList.contains("active")),this.shouldAvoidTriggerChange||(0,_jquery.default)(input).trigger("change")),input.focus(),addAriaPressed=!1}}this._element.hasAttribute("disabled")||this._element.classList.contains("disabled")||(addAriaPressed&&this._element.setAttribute("aria-pressed",!this._element.classList.contains("active")),triggerChangeEvent&&(0,_jquery.default)(this._element).toggleClass("active"))}dispose(){_jquery.default.removeData(this._element,"bs.button"),this._element=null}static _jQueryInterface(config,avoidTriggerChange){return this.each((function(){const $element=(0,_jquery.default)(this);let data=$element.data("bs.button");data||(data=new Button(this),$element.data("bs.button",data)),data.shouldAvoidTriggerChange=avoidTriggerChange,"toggle"===config&&data[config]()}))}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,'[data-toggle^="button"]',(event=>{let button=event.target;const initialButton=button;if((0,_jquery.default)(button).hasClass("btn")||(button=(0,_jquery.default)(button).closest(".btn")[0]),!button||button.hasAttribute("disabled")||button.classList.contains("disabled"))event.preventDefault();else{const inputBtn=button.querySelector('input:not([type="hidden"])');if(inputBtn&&(inputBtn.hasAttribute("disabled")||inputBtn.classList.contains("disabled")))return void event.preventDefault();"INPUT"!==initialButton.tagName&&"LABEL"===button.tagName||Button._jQueryInterface.call((0,_jquery.default)(button),"toggle","INPUT"===initialButton.tagName)}})).on(EVENT_FOCUS_BLUR_DATA_API,'[data-toggle^="button"]',(event=>{const button=(0,_jquery.default)(event.target).closest(".btn")[0];(0,_jquery.default)(button).toggleClass("focus",/^focus(in)?$/.test(event.type))})),(0,_jquery.default)(window).on(EVENT_LOAD_DATA_API,(()=>{let buttons=[].slice.call(document.querySelectorAll('[data-toggle="buttons"] .btn'));for(let i=0,len=buttons.length;i<len;i++){const button=buttons[i],input=button.querySelector('input:not([type="hidden"])');input.checked||input.hasAttribute("checked")?button.classList.add("active"):button.classList.remove("active")}buttons=[].slice.call(document.querySelectorAll('[data-toggle="button"]'));for(let i=0,len=buttons.length;i<len;i++){const button=buttons[i];"true"===button.getAttribute("aria-pressed")?button.classList.add("active"):button.classList.remove("active")}})),_jquery.default.fn[NAME]=Button._jQueryInterface,_jquery.default.fn[NAME].Constructor=Button,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Button._jQueryInterface);var _default=Button;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/carousel",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const NAME="carousel",DATA_KEY="bs.carousel",EVENT_KEY=".".concat(DATA_KEY),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],EVENT_SLIDE="slide".concat(EVENT_KEY),EVENT_SLID="slid".concat(EVENT_KEY),EVENT_KEYDOWN="keydown".concat(EVENT_KEY),EVENT_MOUSEENTER="mouseenter".concat(EVENT_KEY),EVENT_MOUSELEAVE="mouseleave".concat(EVENT_KEY),EVENT_TOUCHSTART="touchstart".concat(EVENT_KEY),EVENT_TOUCHMOVE="touchmove".concat(EVENT_KEY),EVENT_TOUCHEND="touchend".concat(EVENT_KEY),EVENT_POINTERDOWN="pointerdown".concat(EVENT_KEY),EVENT_POINTERUP="pointerup".concat(EVENT_KEY),EVENT_DRAG_START="dragstart".concat(EVENT_KEY),EVENT_LOAD_DATA_API="load".concat(EVENT_KEY).concat(".data-api"),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api"),Default={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0,touch:!0},DefaultType={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean",touch:"boolean"},PointerType={TOUCH:"touch",PEN:"pen"};class Carousel{constructor(element,config){this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this.touchStartX=0,this.touchDeltaX=0,this._config=this._getConfig(config),this._element=element,this._indicatorsElement=this._element.querySelector(".carousel-indicators"),this._touchSupported="ontouchstart"in document.documentElement||navigator.maxTouchPoints>0,this._pointerEvent=Boolean(window.PointerEvent||window.MSPointerEvent),this._addEventListeners()}static get VERSION(){return"4.6.2"}static get Default(){return Default}next(){this._isSliding||this._slide("next")}nextWhenVisible(){const $element=(0,_jquery.default)(this._element);!document.hidden&&$element.is(":visible")&&"hidden"!==$element.css("visibility")&&this.next()}prev(){this._isSliding||this._slide("prev")}pause(event){event||(this._isPaused=!0),this._element.querySelector(".carousel-item-next, .carousel-item-prev")&&(_util.default.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null}cycle(event){event||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._updateInterval(),this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))}to(index){this._activeElement=this._element.querySelector(".active.carousel-item");const activeIndex=this._getItemIndex(this._activeElement);if(index>this._items.length-1||index<0)return;if(this._isSliding)return void(0,_jquery.default)(this._element).one(EVENT_SLID,(()=>this.to(index)));if(activeIndex===index)return this.pause(),void this.cycle();const direction=index>activeIndex?"next":"prev";this._slide(direction,this._items[index])}dispose(){(0,_jquery.default)(this._element).off(EVENT_KEY),_jquery.default.removeData(this._element,DATA_KEY),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null}_getConfig(config){return config={...Default,...config},_util.default.typeCheckConfig(NAME,config,DefaultType),config}_handleSwipe(){const absDeltax=Math.abs(this.touchDeltaX);if(absDeltax<=40)return;const direction=absDeltax/this.touchDeltaX;this.touchDeltaX=0,direction>0&&this.prev(),direction<0&&this.next()}_addEventListeners(){this._config.keyboard&&(0,_jquery.default)(this._element).on(EVENT_KEYDOWN,(event=>this._keydown(event))),"hover"===this._config.pause&&(0,_jquery.default)(this._element).on(EVENT_MOUSEENTER,(event=>this.pause(event))).on(EVENT_MOUSELEAVE,(event=>this.cycle(event))),this._config.touch&&this._addTouchEventListeners()}_addTouchEventListeners(){if(!this._touchSupported)return;const start=event=>{this._pointerEvent&&PointerType[event.originalEvent.pointerType.toUpperCase()]?this.touchStartX=event.originalEvent.clientX:this._pointerEvent||(this.touchStartX=event.originalEvent.touches[0].clientX)},move=event=>{this.touchDeltaX=event.originalEvent.touches&&event.originalEvent.touches.length>1?0:event.originalEvent.touches[0].clientX-this.touchStartX},end=event=>{this._pointerEvent&&PointerType[event.originalEvent.pointerType.toUpperCase()]&&(this.touchDeltaX=event.originalEvent.clientX-this.touchStartX),this._handleSwipe(),"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((event=>this.cycle(event)),500+this._config.interval))};(0,_jquery.default)(this._element.querySelectorAll(".carousel-item img")).on(EVENT_DRAG_START,(e=>e.preventDefault())),this._pointerEvent?((0,_jquery.default)(this._element).on(EVENT_POINTERDOWN,(event=>start(event))),(0,_jquery.default)(this._element).on(EVENT_POINTERUP,(event=>end(event))),this._element.classList.add("pointer-event")):((0,_jquery.default)(this._element).on(EVENT_TOUCHSTART,(event=>start(event))),(0,_jquery.default)(this._element).on(EVENT_TOUCHMOVE,(event=>move(event))),(0,_jquery.default)(this._element).on(EVENT_TOUCHEND,(event=>end(event))))}_keydown(event){if(!/input|textarea/i.test(event.target.tagName))switch(event.which){case 37:event.preventDefault(),this.prev();break;case 39:event.preventDefault(),this.next()}}_getItemIndex(element){return this._items=element&&element.parentNode?[].slice.call(element.parentNode.querySelectorAll(".carousel-item")):[],this._items.indexOf(element)}_getItemByDirection(direction,activeElement){const isNextDirection="next"===direction,isPrevDirection="prev"===direction,activeIndex=this._getItemIndex(activeElement),lastItemIndex=this._items.length-1;if((isPrevDirection&&0===activeIndex||isNextDirection&&activeIndex===lastItemIndex)&&!this._config.wrap)return activeElement;const itemIndex=(activeIndex+("prev"===direction?-1:1))%this._items.length;return-1===itemIndex?this._items[this._items.length-1]:this._items[itemIndex]}_triggerSlideEvent(relatedTarget,eventDirectionName){const targetIndex=this._getItemIndex(relatedTarget),fromIndex=this._getItemIndex(this._element.querySelector(".active.carousel-item")),slideEvent=_jquery.default.Event(EVENT_SLIDE,{relatedTarget:relatedTarget,direction:eventDirectionName,from:fromIndex,to:targetIndex});return(0,_jquery.default)(this._element).trigger(slideEvent),slideEvent}_setActiveIndicatorElement(element){if(this._indicatorsElement){const indicators=[].slice.call(this._indicatorsElement.querySelectorAll(".active"));(0,_jquery.default)(indicators).removeClass("active");const nextIndicator=this._indicatorsElement.children[this._getItemIndex(element)];nextIndicator&&(0,_jquery.default)(nextIndicator).addClass("active")}}_updateInterval(){const element=this._activeElement||this._element.querySelector(".active.carousel-item");if(!element)return;const elementInterval=parseInt(element.getAttribute("data-interval"),10);elementInterval?(this._config.defaultInterval=this._config.defaultInterval||this._config.interval,this._config.interval=elementInterval):this._config.interval=this._config.defaultInterval||this._config.interval}_slide(direction,element){const activeElement=this._element.querySelector(".active.carousel-item"),activeElementIndex=this._getItemIndex(activeElement),nextElement=element||activeElement&&this._getItemByDirection(direction,activeElement),nextElementIndex=this._getItemIndex(nextElement),isCycling=Boolean(this._interval);let directionalClassName,orderClassName,eventDirectionName;if("next"===direction?(directionalClassName="carousel-item-left",orderClassName="carousel-item-next",eventDirectionName="left"):(directionalClassName="carousel-item-right",orderClassName="carousel-item-prev",eventDirectionName="right"),nextElement&&(0,_jquery.default)(nextElement).hasClass("active"))return void(this._isSliding=!1);if(this._triggerSlideEvent(nextElement,eventDirectionName).isDefaultPrevented())return;if(!activeElement||!nextElement)return;this._isSliding=!0,isCycling&&this.pause(),this._setActiveIndicatorElement(nextElement),this._activeElement=nextElement;const slidEvent=_jquery.default.Event(EVENT_SLID,{relatedTarget:nextElement,direction:eventDirectionName,from:activeElementIndex,to:nextElementIndex});if((0,_jquery.default)(this._element).hasClass("slide")){(0,_jquery.default)(nextElement).addClass(orderClassName),_util.default.reflow(nextElement),(0,_jquery.default)(activeElement).addClass(directionalClassName),(0,_jquery.default)(nextElement).addClass(directionalClassName);const transitionDuration=_util.default.getTransitionDurationFromElement(activeElement);(0,_jquery.default)(activeElement).one(_util.default.TRANSITION_END,(()=>{(0,_jquery.default)(nextElement).removeClass("".concat(directionalClassName," ").concat(orderClassName)).addClass("active"),(0,_jquery.default)(activeElement).removeClass("".concat("active"," ").concat(orderClassName," ").concat(directionalClassName)),this._isSliding=!1,setTimeout((()=>(0,_jquery.default)(this._element).trigger(slidEvent)),0)})).emulateTransitionEnd(transitionDuration)}else(0,_jquery.default)(activeElement).removeClass("active"),(0,_jquery.default)(nextElement).addClass("active"),this._isSliding=!1,(0,_jquery.default)(this._element).trigger(slidEvent);isCycling&&this.cycle()}static _jQueryInterface(config){return this.each((function(){let data=(0,_jquery.default)(this).data(DATA_KEY),_config={...Default,...(0,_jquery.default)(this).data()};"object"==typeof config&&(_config={..._config,...config});const action="string"==typeof config?config:_config.slide;if(data||(data=new Carousel(this,_config),(0,_jquery.default)(this).data(DATA_KEY,data)),"number"==typeof config)data.to(config);else if("string"==typeof action){if(void 0===data[action])throw new TypeError('No method named "'.concat(action,'"'));data[action]()}else _config.interval&&_config.ride&&(data.pause(),data.cycle())}))}static _dataApiClickHandler(event){const selector=_util.default.getSelectorFromElement(this);if(!selector)return;const target=(0,_jquery.default)(selector)[0];if(!target||!(0,_jquery.default)(target).hasClass("carousel"))return;const config={...(0,_jquery.default)(target).data(),...(0,_jquery.default)(this).data()},slideIndex=this.getAttribute("data-slide-to");slideIndex&&(config.interval=!1),Carousel._jQueryInterface.call((0,_jquery.default)(target),config),slideIndex&&(0,_jquery.default)(target).data(DATA_KEY).to(slideIndex),event.preventDefault()}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,"[data-slide], [data-slide-to]",Carousel._dataApiClickHandler),(0,_jquery.default)(window).on(EVENT_LOAD_DATA_API,(()=>{const carousels=[].slice.call(document.querySelectorAll('[data-ride="carousel"]'));for(let i=0,len=carousels.length;i<len;i++){const $carousel=(0,_jquery.default)(carousels[i]);Carousel._jQueryInterface.call($carousel,$carousel.data())}})),_jquery.default.fn[NAME]=Carousel._jQueryInterface,_jquery.default.fn[NAME].Constructor=Carousel,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Carousel._jQueryInterface);var _default=Carousel;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/collapse",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const NAME="collapse",DATA_KEY="bs.collapse",EVENT_KEY=".".concat(DATA_KEY),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],EVENT_SHOW="show".concat(EVENT_KEY),EVENT_SHOWN="shown".concat(EVENT_KEY),EVENT_HIDE="hide".concat(EVENT_KEY),EVENT_HIDDEN="hidden".concat(EVENT_KEY),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api"),Default={toggle:!0,parent:""},DefaultType={toggle:"boolean",parent:"(string|element)"};class Collapse{constructor(element,config){this._isTransitioning=!1,this._element=element,this._config=this._getConfig(config),this._triggerArray=[].slice.call(document.querySelectorAll('[data-toggle="collapse"][href="#'.concat(element.id,'"],')+'[data-toggle="collapse"][data-target="#'.concat(element.id,'"]')));const toggleList=[].slice.call(document.querySelectorAll('[data-toggle="collapse"]'));for(let i=0,len=toggleList.length;i<len;i++){const elem=toggleList[i],selector=_util.default.getSelectorFromElement(elem),filterElement=[].slice.call(document.querySelectorAll(selector)).filter((foundElem=>foundElem===element));null!==selector&&filterElement.length>0&&(this._selector=selector,this._triggerArray.push(elem))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}static get VERSION(){return"4.6.2"}static get Default(){return Default}toggle(){(0,_jquery.default)(this._element).hasClass("show")?this.hide():this.show()}show(){if(this._isTransitioning||(0,_jquery.default)(this._element).hasClass("show"))return;let actives,activesData;if(this._parent&&(actives=[].slice.call(this._parent.querySelectorAll(".show, .collapsing")).filter((elem=>"string"==typeof this._config.parent?elem.getAttribute("data-parent")===this._config.parent:elem.classList.contains("collapse"))),0===actives.length&&(actives=null)),actives&&(activesData=(0,_jquery.default)(actives).not(this._selector).data(DATA_KEY),activesData&&activesData._isTransitioning))return;const startEvent=_jquery.default.Event(EVENT_SHOW);if((0,_jquery.default)(this._element).trigger(startEvent),startEvent.isDefaultPrevented())return;actives&&(Collapse._jQueryInterface.call((0,_jquery.default)(actives).not(this._selector),"hide"),activesData||(0,_jquery.default)(actives).data(DATA_KEY,null));const dimension=this._getDimension();(0,_jquery.default)(this._element).removeClass("collapse").addClass("collapsing"),this._element.style[dimension]=0,this._triggerArray.length&&(0,_jquery.default)(this._triggerArray).removeClass("collapsed").attr("aria-expanded",!0),this.setTransitioning(!0);const capitalizedDimension=dimension[0].toUpperCase()+dimension.slice(1),scrollSize="scroll".concat(capitalizedDimension),transitionDuration=_util.default.getTransitionDurationFromElement(this._element);(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,(()=>{(0,_jquery.default)(this._element).removeClass("collapsing").addClass("".concat("collapse"," ").concat("show")),this._element.style[dimension]="",this.setTransitioning(!1),(0,_jquery.default)(this._element).trigger(EVENT_SHOWN)})).emulateTransitionEnd(transitionDuration),this._element.style[dimension]="".concat(this._element[scrollSize],"px")}hide(){if(this._isTransitioning||!(0,_jquery.default)(this._element).hasClass("show"))return;const startEvent=_jquery.default.Event(EVENT_HIDE);if((0,_jquery.default)(this._element).trigger(startEvent),startEvent.isDefaultPrevented())return;const dimension=this._getDimension();this._element.style[dimension]="".concat(this._element.getBoundingClientRect()[dimension],"px"),_util.default.reflow(this._element),(0,_jquery.default)(this._element).addClass("collapsing").removeClass("".concat("collapse"," ").concat("show"));const triggerArrayLength=this._triggerArray.length;if(triggerArrayLength>0)for(let i=0;i<triggerArrayLength;i++){const trigger=this._triggerArray[i],selector=_util.default.getSelectorFromElement(trigger);if(null!==selector){(0,_jquery.default)([].slice.call(document.querySelectorAll(selector))).hasClass("show")||(0,_jquery.default)(trigger).addClass("collapsed").attr("aria-expanded",!1)}}this.setTransitioning(!0);this._element.style[dimension]="";const transitionDuration=_util.default.getTransitionDurationFromElement(this._element);(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,(()=>{this.setTransitioning(!1),(0,_jquery.default)(this._element).removeClass("collapsing").addClass("collapse").trigger(EVENT_HIDDEN)})).emulateTransitionEnd(transitionDuration)}setTransitioning(isTransitioning){this._isTransitioning=isTransitioning}dispose(){_jquery.default.removeData(this._element,DATA_KEY),this._config=null,this._parent=null,this._element=null,this._triggerArray=null,this._isTransitioning=null}_getConfig(config){return(config={...Default,...config}).toggle=Boolean(config.toggle),_util.default.typeCheckConfig(NAME,config,DefaultType),config}_getDimension(){return(0,_jquery.default)(this._element).hasClass("width")?"width":"height"}_getParent(){let parent;_util.default.isElement(this._config.parent)?(parent=this._config.parent,void 0!==this._config.parent.jquery&&(parent=this._config.parent[0])):parent=document.querySelector(this._config.parent);const selector='[data-toggle="collapse"][data-parent="'.concat(this._config.parent,'"]'),children=[].slice.call(parent.querySelectorAll(selector));return(0,_jquery.default)(children).each(((i,element)=>{this._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element),[element])})),parent}_addAriaAndCollapsedClass(element,triggerArray){const isOpen=(0,_jquery.default)(element).hasClass("show");triggerArray.length&&(0,_jquery.default)(triggerArray).toggleClass("collapsed",!isOpen).attr("aria-expanded",isOpen)}static _getTargetFromElement(element){const selector=_util.default.getSelectorFromElement(element);return selector?document.querySelector(selector):null}static _jQueryInterface(config){return this.each((function(){const $element=(0,_jquery.default)(this);let data=$element.data(DATA_KEY);const _config={...Default,...$element.data(),..."object"==typeof config&&config?config:{}};if(!data&&_config.toggle&&"string"==typeof config&&/show|hide/.test(config)&&(_config.toggle=!1),data||(data=new Collapse(this,_config),$element.data(DATA_KEY,data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,'[data-toggle="collapse"]',(function(event){"A"===event.currentTarget.tagName&&event.preventDefault();const $trigger=(0,_jquery.default)(this),selector=_util.default.getSelectorFromElement(this),selectors=[].slice.call(document.querySelectorAll(selector));(0,_jquery.default)(selectors).each((function(){const $target=(0,_jquery.default)(this),config=$target.data(DATA_KEY)?"toggle":$trigger.data();Collapse._jQueryInterface.call($target,config)}))})),_jquery.default.fn[NAME]=Collapse._jQueryInterface,_jquery.default.fn[NAME].Constructor=Collapse,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Collapse._jQueryInterface);var _default=Collapse;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/dropdown",["exports","jquery","core/popper","./util"],(function(_exports,_jquery,_popper,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_popper=_interopRequireDefault(_popper),_util=_interopRequireDefault(_util);const NAME="dropdown",DATA_KEY="bs.dropdown",EVENT_KEY=".".concat(DATA_KEY),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],REGEXP_KEYDOWN=new RegExp("".concat(38,"|").concat(40,"|").concat(27)),EVENT_HIDE="hide".concat(EVENT_KEY),EVENT_HIDDEN="hidden".concat(EVENT_KEY),EVENT_SHOW="show".concat(EVENT_KEY),EVENT_SHOWN="shown".concat(EVENT_KEY),EVENT_CLICK="click".concat(EVENT_KEY),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api"),EVENT_KEYDOWN_DATA_API="keydown".concat(EVENT_KEY).concat(".data-api"),EVENT_KEYUP_DATA_API="keyup".concat(EVENT_KEY).concat(".data-api"),Default={offset:0,flip:!0,boundary:"scrollParent",reference:"toggle",display:"dynamic",popperConfig:null},DefaultType={offset:"(number|string|function)",flip:"boolean",boundary:"(string|element)",reference:"(string|element)",display:"string",popperConfig:"(null|object)"};class Dropdown{constructor(element,config){this._element=element,this._popper=null,this._config=this._getConfig(config),this._menu=this._getMenuElement(),this._inNavbar=this._detectNavbar(),this._addEventListeners()}static get VERSION(){return"4.6.2"}static get Default(){return Default}static get DefaultType(){return DefaultType}toggle(){if(this._element.disabled||(0,_jquery.default)(this._element).hasClass("disabled"))return;const isActive=(0,_jquery.default)(this._menu).hasClass("show");Dropdown._clearMenus(),isActive||this.show(!0)}show(){let usePopper=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._element.disabled||(0,_jquery.default)(this._element).hasClass("disabled")||(0,_jquery.default)(this._menu).hasClass("show"))return;const relatedTarget={relatedTarget:this._element},showEvent=_jquery.default.Event(EVENT_SHOW,relatedTarget),parent=Dropdown._getParentFromElement(this._element);if((0,_jquery.default)(parent).trigger(showEvent),!showEvent.isDefaultPrevented()){if(!this._inNavbar&&usePopper){if(void 0===_popper.default)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let referenceElement=this._element;"parent"===this._config.reference?referenceElement=parent:_util.default.isElement(this._config.reference)&&(referenceElement=this._config.reference,void 0!==this._config.reference.jquery&&(referenceElement=this._config.reference[0])),"scrollParent"!==this._config.boundary&&(0,_jquery.default)(parent).addClass("position-static"),this._popper=new _popper.default(referenceElement,this._menu,this._getPopperConfig())}"ontouchstart"in document.documentElement&&0===(0,_jquery.default)(parent).closest(".navbar-nav").length&&(0,_jquery.default)(document.body).children().on("mouseover",null,_jquery.default.noop),this._element.focus(),this._element.setAttribute("aria-expanded",!0),(0,_jquery.default)(this._menu).toggleClass("show"),(0,_jquery.default)(parent).toggleClass("show").trigger(_jquery.default.Event(EVENT_SHOWN,relatedTarget))}}hide(){if(this._element.disabled||(0,_jquery.default)(this._element).hasClass("disabled")||!(0,_jquery.default)(this._menu).hasClass("show"))return;const relatedTarget={relatedTarget:this._element},hideEvent=_jquery.default.Event(EVENT_HIDE,relatedTarget),parent=Dropdown._getParentFromElement(this._element);(0,_jquery.default)(parent).trigger(hideEvent),hideEvent.isDefaultPrevented()||(this._popper&&this._popper.destroy(),(0,_jquery.default)(this._menu).toggleClass("show"),(0,_jquery.default)(parent).toggleClass("show").trigger(_jquery.default.Event(EVENT_HIDDEN,relatedTarget)))}dispose(){_jquery.default.removeData(this._element,DATA_KEY),(0,_jquery.default)(this._element).off(EVENT_KEY),this._element=null,this._menu=null,null!==this._popper&&(this._popper.destroy(),this._popper=null)}update(){this._inNavbar=this._detectNavbar(),null!==this._popper&&this._popper.scheduleUpdate()}_addEventListeners(){(0,_jquery.default)(this._element).on(EVENT_CLICK,(event=>{event.preventDefault(),event.stopPropagation(),this.toggle()}))}_getConfig(config){return config={...this.constructor.Default,...(0,_jquery.default)(this._element).data(),...config},_util.default.typeCheckConfig(NAME,config,this.constructor.DefaultType),config}_getMenuElement(){if(!this._menu){const parent=Dropdown._getParentFromElement(this._element);parent&&(this._menu=parent.querySelector(".dropdown-menu"))}return this._menu}_getPlacement(){const $parentDropdown=(0,_jquery.default)(this._element.parentNode);let placement="bottom-start";return $parentDropdown.hasClass("dropup")?placement=(0,_jquery.default)(this._menu).hasClass("dropdown-menu-right")?"top-end":"top-start":$parentDropdown.hasClass("dropright")?placement="right-start":$parentDropdown.hasClass("dropleft")?placement="left-start":(0,_jquery.default)(this._menu).hasClass("dropdown-menu-right")&&(placement="bottom-end"),placement}_detectNavbar(){return(0,_jquery.default)(this._element).closest(".navbar").length>0}_getOffset(){const offset={};return"function"==typeof this._config.offset?offset.fn=data=>(data.offsets={...data.offsets,...this._config.offset(data.offsets,this._element)},data):offset.offset=this._config.offset,offset}_getPopperConfig(){const popperConfig={placement:this._getPlacement(),modifiers:{offset:this._getOffset(),flip:{enabled:this._config.flip},preventOverflow:{boundariesElement:this._config.boundary}}};return"static"===this._config.display&&(popperConfig.modifiers.applyStyle={enabled:!1}),{...popperConfig,...this._config.popperConfig}}static _jQueryInterface(config){return this.each((function(){let data=(0,_jquery.default)(this).data(DATA_KEY);if(data||(data=new Dropdown(this,"object"==typeof config?config:null),(0,_jquery.default)(this).data(DATA_KEY,data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}static _clearMenus(event){if(event&&(3===event.which||"keyup"===event.type&&9!==event.which))return;const toggles=[].slice.call(document.querySelectorAll('[data-toggle="dropdown"]'));for(let i=0,len=toggles.length;i<len;i++){const parent=Dropdown._getParentFromElement(toggles[i]),context=(0,_jquery.default)(toggles[i]).data(DATA_KEY),relatedTarget={relatedTarget:toggles[i]};if(event&&"click"===event.type&&(relatedTarget.clickEvent=event),!context)continue;const dropdownMenu=context._menu;if(!(0,_jquery.default)(parent).hasClass("show"))continue;if(event&&("click"===event.type&&/input|textarea/i.test(event.target.tagName)||"keyup"===event.type&&9===event.which)&&_jquery.default.contains(parent,event.target))continue;const hideEvent=_jquery.default.Event(EVENT_HIDE,relatedTarget);(0,_jquery.default)(parent).trigger(hideEvent),hideEvent.isDefaultPrevented()||("ontouchstart"in document.documentElement&&(0,_jquery.default)(document.body).children().off("mouseover",null,_jquery.default.noop),toggles[i].setAttribute("aria-expanded","false"),context._popper&&context._popper.destroy(),(0,_jquery.default)(dropdownMenu).removeClass("show"),(0,_jquery.default)(parent).removeClass("show").trigger(_jquery.default.Event(EVENT_HIDDEN,relatedTarget)))}}static _getParentFromElement(element){let parent;const selector=_util.default.getSelectorFromElement(element);return selector&&(parent=document.querySelector(selector)),parent||element.parentNode}static _dataApiKeydownHandler(event){if(/input|textarea/i.test(event.target.tagName)?32===event.which||27!==event.which&&(40!==event.which&&38!==event.which||(0,_jquery.default)(event.target).closest(".dropdown-menu").length):!REGEXP_KEYDOWN.test(event.which))return;if(this.disabled||(0,_jquery.default)(this).hasClass("disabled"))return;const parent=Dropdown._getParentFromElement(this),isActive=(0,_jquery.default)(parent).hasClass("show");if(!isActive&&27===event.which)return;if(event.preventDefault(),event.stopPropagation(),!isActive||27===event.which||32===event.which)return 27===event.which&&(0,_jquery.default)(parent.querySelector('[data-toggle="dropdown"]')).trigger("focus"),void(0,_jquery.default)(this).trigger("click");const items=[].slice.call(parent.querySelectorAll(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)")).filter((item=>(0,_jquery.default)(item).is(":visible")));if(0===items.length)return;let index=items.indexOf(event.target);38===event.which&&index>0&&index--,40===event.which&&index<items.length-1&&index++,index<0&&(index=0),items[index].focus()}}(0,_jquery.default)(document).on(EVENT_KEYDOWN_DATA_API,'[data-toggle="dropdown"]',Dropdown._dataApiKeydownHandler).on(EVENT_KEYDOWN_DATA_API,".dropdown-menu",Dropdown._dataApiKeydownHandler).on("".concat(EVENT_CLICK_DATA_API," ").concat(EVENT_KEYUP_DATA_API),Dropdown._clearMenus).on(EVENT_CLICK_DATA_API,'[data-toggle="dropdown"]',(function(event){event.preventDefault(),event.stopPropagation(),Dropdown._jQueryInterface.call((0,_jquery.default)(this),"toggle")})).on(EVENT_CLICK_DATA_API,".dropdown form",(e=>{e.stopPropagation()})),_jquery.default.fn[NAME]=Dropdown._jQueryInterface,_jquery.default.fn[NAME].Constructor=Dropdown,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Dropdown._jQueryInterface);var _default=Dropdown;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/modal",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const NAME="modal",EVENT_KEY=".".concat("bs.modal"),JQUERY_NO_CONFLICT=_jquery.default.fn.modal,EVENT_HIDE="hide".concat(EVENT_KEY),EVENT_HIDE_PREVENTED="hidePrevented".concat(EVENT_KEY),EVENT_HIDDEN="hidden".concat(EVENT_KEY),EVENT_SHOW="show".concat(EVENT_KEY),EVENT_SHOWN="shown".concat(EVENT_KEY),EVENT_FOCUSIN="focusin".concat(EVENT_KEY),EVENT_RESIZE="resize".concat(EVENT_KEY),EVENT_CLICK_DISMISS="click.dismiss".concat(EVENT_KEY),EVENT_KEYDOWN_DISMISS="keydown.dismiss".concat(EVENT_KEY),EVENT_MOUSEUP_DISMISS="mouseup.dismiss".concat(EVENT_KEY),EVENT_MOUSEDOWN_DISMISS="mousedown.dismiss".concat(EVENT_KEY),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api"),Default={backdrop:!0,keyboard:!0,focus:!0,show:!0},DefaultType={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean",show:"boolean"};class Modal{constructor(element,config){this._config=this._getConfig(config),this._element=element,this._dialog=element.querySelector(".modal-dialog"),this._backdrop=null,this._isShown=!1,this._isBodyOverflowing=!1,this._ignoreBackdropClick=!1,this._isTransitioning=!1,this._scrollbarWidth=0}static get VERSION(){return"4.6.2"}static get Default(){return Default}toggle(relatedTarget){return this._isShown?this.hide():this.show(relatedTarget)}show(relatedTarget){if(this._isShown||this._isTransitioning)return;const showEvent=_jquery.default.Event(EVENT_SHOW,{relatedTarget:relatedTarget});(0,_jquery.default)(this._element).trigger(showEvent),showEvent.isDefaultPrevented()||(this._isShown=!0,(0,_jquery.default)(this._element).hasClass("fade")&&(this._isTransitioning=!0),this._checkScrollbar(),this._setScrollbar(),this._adjustDialog(),this._setEscapeEvent(),this._setResizeEvent(),(0,_jquery.default)(this._element).on(EVENT_CLICK_DISMISS,'[data-dismiss="modal"]',(event=>this.hide(event))),(0,_jquery.default)(this._dialog).on(EVENT_MOUSEDOWN_DISMISS,(()=>{(0,_jquery.default)(this._element).one(EVENT_MOUSEUP_DISMISS,(event=>{(0,_jquery.default)(event.target).is(this._element)&&(this._ignoreBackdropClick=!0)}))})),this._showBackdrop((()=>this._showElement(relatedTarget))))}hide(event){if(event&&event.preventDefault(),!this._isShown||this._isTransitioning)return;const hideEvent=_jquery.default.Event(EVENT_HIDE);if((0,_jquery.default)(this._element).trigger(hideEvent),!this._isShown||hideEvent.isDefaultPrevented())return;this._isShown=!1;const transition=(0,_jquery.default)(this._element).hasClass("fade");if(transition&&(this._isTransitioning=!0),this._setEscapeEvent(),this._setResizeEvent(),(0,_jquery.default)(document).off(EVENT_FOCUSIN),(0,_jquery.default)(this._element).removeClass("show"),(0,_jquery.default)(this._element).off(EVENT_CLICK_DISMISS),(0,_jquery.default)(this._dialog).off(EVENT_MOUSEDOWN_DISMISS),transition){const transitionDuration=_util.default.getTransitionDurationFromElement(this._element);(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,(event=>this._hideModal(event))).emulateTransitionEnd(transitionDuration)}else this._hideModal()}dispose(){[window,this._element,this._dialog].forEach((htmlElement=>(0,_jquery.default)(htmlElement).off(EVENT_KEY))),(0,_jquery.default)(document).off(EVENT_FOCUSIN),_jquery.default.removeData(this._element,"bs.modal"),this._config=null,this._element=null,this._dialog=null,this._backdrop=null,this._isShown=null,this._isBodyOverflowing=null,this._ignoreBackdropClick=null,this._isTransitioning=null,this._scrollbarWidth=null}handleUpdate(){this._adjustDialog()}_getConfig(config){return config={...Default,...config},_util.default.typeCheckConfig(NAME,config,DefaultType),config}_triggerBackdropTransition(){const hideEventPrevented=_jquery.default.Event(EVENT_HIDE_PREVENTED);if((0,_jquery.default)(this._element).trigger(hideEventPrevented),hideEventPrevented.isDefaultPrevented())return;const isModalOverflowing=this._element.scrollHeight>document.documentElement.clientHeight;isModalOverflowing||(this._element.style.overflowY="hidden"),this._element.classList.add("modal-static");const modalTransitionDuration=_util.default.getTransitionDurationFromElement(this._dialog);(0,_jquery.default)(this._element).off(_util.default.TRANSITION_END),(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,(()=>{this._element.classList.remove("modal-static"),isModalOverflowing||(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,(()=>{this._element.style.overflowY=""})).emulateTransitionEnd(this._element,modalTransitionDuration)})).emulateTransitionEnd(modalTransitionDuration),this._element.focus()}_showElement(relatedTarget){const transition=(0,_jquery.default)(this._element).hasClass("fade"),modalBody=this._dialog?this._dialog.querySelector(".modal-body"):null;this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),(0,_jquery.default)(this._dialog).hasClass("modal-dialog-scrollable")&&modalBody?modalBody.scrollTop=0:this._element.scrollTop=0,transition&&_util.default.reflow(this._element),(0,_jquery.default)(this._element).addClass("show"),this._config.focus&&this._enforceFocus();const shownEvent=_jquery.default.Event(EVENT_SHOWN,{relatedTarget:relatedTarget}),transitionComplete=()=>{this._config.focus&&this._element.focus(),this._isTransitioning=!1,(0,_jquery.default)(this._element).trigger(shownEvent)};if(transition){const transitionDuration=_util.default.getTransitionDurationFromElement(this._dialog);(0,_jquery.default)(this._dialog).one(_util.default.TRANSITION_END,transitionComplete).emulateTransitionEnd(transitionDuration)}else transitionComplete()}_enforceFocus(){(0,_jquery.default)(document).off(EVENT_FOCUSIN).on(EVENT_FOCUSIN,(event=>{document!==event.target&&this._element!==event.target&&0===(0,_jquery.default)(this._element).has(event.target).length&&this._element.focus()}))}_setEscapeEvent(){this._isShown?(0,_jquery.default)(this._element).on(EVENT_KEYDOWN_DISMISS,(event=>{this._config.keyboard&&27===event.which?(event.preventDefault(),this.hide()):this._config.keyboard||27!==event.which||this._triggerBackdropTransition()})):this._isShown||(0,_jquery.default)(this._element).off(EVENT_KEYDOWN_DISMISS)}_setResizeEvent(){this._isShown?(0,_jquery.default)(window).on(EVENT_RESIZE,(event=>this.handleUpdate(event))):(0,_jquery.default)(window).off(EVENT_RESIZE)}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._showBackdrop((()=>{(0,_jquery.default)(document.body).removeClass("modal-open"),this._resetAdjustments(),this._resetScrollbar(),(0,_jquery.default)(this._element).trigger(EVENT_HIDDEN)}))}_removeBackdrop(){this._backdrop&&((0,_jquery.default)(this._backdrop).remove(),this._backdrop=null)}_showBackdrop(callback){const animate=(0,_jquery.default)(this._element).hasClass("fade")?"fade":"";if(this._isShown&&this._config.backdrop){if(this._backdrop=document.createElement("div"),this._backdrop.className="modal-backdrop",animate&&this._backdrop.classList.add(animate),(0,_jquery.default)(this._backdrop).appendTo(document.body),(0,_jquery.default)(this._element).on(EVENT_CLICK_DISMISS,(event=>{this._ignoreBackdropClick?this._ignoreBackdropClick=!1:event.target===event.currentTarget&&("static"===this._config.backdrop?this._triggerBackdropTransition():this.hide())})),animate&&_util.default.reflow(this._backdrop),(0,_jquery.default)(this._backdrop).addClass("show"),!callback)return;if(!animate)return void callback();const backdropTransitionDuration=_util.default.getTransitionDurationFromElement(this._backdrop);(0,_jquery.default)(this._backdrop).one(_util.default.TRANSITION_END,callback).emulateTransitionEnd(backdropTransitionDuration)}else if(!this._isShown&&this._backdrop){(0,_jquery.default)(this._backdrop).removeClass("show");const callbackRemove=()=>{this._removeBackdrop(),callback&&callback()};if((0,_jquery.default)(this._element).hasClass("fade")){const backdropTransitionDuration=_util.default.getTransitionDurationFromElement(this._backdrop);(0,_jquery.default)(this._backdrop).one(_util.default.TRANSITION_END,callbackRemove).emulateTransitionEnd(backdropTransitionDuration)}else callbackRemove()}else callback&&callback()}_adjustDialog(){const isModalOverflowing=this._element.scrollHeight>document.documentElement.clientHeight;!this._isBodyOverflowing&&isModalOverflowing&&(this._element.style.paddingLeft="".concat(this._scrollbarWidth,"px")),this._isBodyOverflowing&&!isModalOverflowing&&(this._element.style.paddingRight="".concat(this._scrollbarWidth,"px"))}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}_checkScrollbar(){const rect=document.body.getBoundingClientRect();this._isBodyOverflowing=Math.round(rect.left+rect.right)<window.innerWidth,this._scrollbarWidth=this._getScrollbarWidth()}_setScrollbar(){if(this._isBodyOverflowing){const fixedContent=[].slice.call(document.querySelectorAll(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top")),stickyContent=[].slice.call(document.querySelectorAll(".sticky-top"));(0,_jquery.default)(fixedContent).each(((index,element)=>{const actualPadding=element.style.paddingRight,calculatedPadding=(0,_jquery.default)(element).css("padding-right");(0,_jquery.default)(element).data("padding-right",actualPadding).css("padding-right","".concat(parseFloat(calculatedPadding)+this._scrollbarWidth,"px"))})),(0,_jquery.default)(stickyContent).each(((index,element)=>{const actualMargin=element.style.marginRight,calculatedMargin=(0,_jquery.default)(element).css("margin-right");(0,_jquery.default)(element).data("margin-right",actualMargin).css("margin-right","".concat(parseFloat(calculatedMargin)-this._scrollbarWidth,"px"))}));const actualPadding=document.body.style.paddingRight,calculatedPadding=(0,_jquery.default)(document.body).css("padding-right");(0,_jquery.default)(document.body).data("padding-right",actualPadding).css("padding-right","".concat(parseFloat(calculatedPadding)+this._scrollbarWidth,"px"))}(0,_jquery.default)(document.body).addClass("modal-open")}_resetScrollbar(){const fixedContent=[].slice.call(document.querySelectorAll(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top"));(0,_jquery.default)(fixedContent).each(((index,element)=>{const padding=(0,_jquery.default)(element).data("padding-right");(0,_jquery.default)(element).removeData("padding-right"),element.style.paddingRight=padding||""}));const elements=[].slice.call(document.querySelectorAll("".concat(".sticky-top")));(0,_jquery.default)(elements).each(((index,element)=>{const margin=(0,_jquery.default)(element).data("margin-right");void 0!==margin&&(0,_jquery.default)(element).css("margin-right",margin).removeData("margin-right")}));const padding=(0,_jquery.default)(document.body).data("padding-right");(0,_jquery.default)(document.body).removeData("padding-right"),document.body.style.paddingRight=padding||""}_getScrollbarWidth(){const scrollDiv=document.createElement("div");scrollDiv.className="modal-scrollbar-measure",document.body.appendChild(scrollDiv);const scrollbarWidth=scrollDiv.getBoundingClientRect().width-scrollDiv.clientWidth;return document.body.removeChild(scrollDiv),scrollbarWidth}static _jQueryInterface(config,relatedTarget){return this.each((function(){let data=(0,_jquery.default)(this).data("bs.modal");const _config={...Default,...(0,_jquery.default)(this).data(),..."object"==typeof config&&config?config:{}};if(data||(data=new Modal(this,_config),(0,_jquery.default)(this).data("bs.modal",data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config](relatedTarget)}else _config.show&&data.show(relatedTarget)}))}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,'[data-toggle="modal"]',(function(event){let target;const selector=_util.default.getSelectorFromElement(this);selector&&(target=document.querySelector(selector));const config=(0,_jquery.default)(target).data("bs.modal")?"toggle":{...(0,_jquery.default)(target).data(),...(0,_jquery.default)(this).data()};"A"!==this.tagName&&"AREA"!==this.tagName||event.preventDefault();const $target=(0,_jquery.default)(target).one(EVENT_SHOW,(showEvent=>{showEvent.isDefaultPrevented()||$target.one(EVENT_HIDDEN,(()=>{(0,_jquery.default)(this).is(":visible")&&this.focus()}))}));Modal._jQueryInterface.call((0,_jquery.default)(target),config,this)})),_jquery.default.fn.modal=Modal._jQueryInterface,_jquery.default.fn.modal.Constructor=Modal,_jquery.default.fn.modal.noConflict=()=>(_jquery.default.fn.modal=JQUERY_NO_CONFLICT,Modal._jQueryInterface);var _default=Modal;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/popover",["exports","jquery","./tooltip"],(function(_exports,_jquery,_tooltip){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_tooltip=_interopRequireDefault(_tooltip);const NAME="popover",EVENT_KEY=".".concat("bs.popover"),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],BSCLS_PREFIX_REGEX=new RegExp("(^|\\s)".concat("bs-popover","\\S+"),"g"),Default={..._tooltip.default.Default,placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'},DefaultType={..._tooltip.default.DefaultType,content:"(string|element|function)"},Event={HIDE:"hide".concat(EVENT_KEY),HIDDEN:"hidden".concat(EVENT_KEY),SHOW:"show".concat(EVENT_KEY),SHOWN:"shown".concat(EVENT_KEY),INSERTED:"inserted".concat(EVENT_KEY),CLICK:"click".concat(EVENT_KEY),FOCUSIN:"focusin".concat(EVENT_KEY),FOCUSOUT:"focusout".concat(EVENT_KEY),MOUSEENTER:"mouseenter".concat(EVENT_KEY),MOUSELEAVE:"mouseleave".concat(EVENT_KEY)};class Popover extends _tooltip.default{static get VERSION(){return"4.6.2"}static get Default(){return Default}static get NAME(){return NAME}static get DATA_KEY(){return"bs.popover"}static get Event(){return Event}static get EVENT_KEY(){return EVENT_KEY}static get DefaultType(){return DefaultType}isWithContent(){return this.getTitle()||this._getContent()}addAttachmentClass(attachment){(0,_jquery.default)(this.getTipElement()).addClass("".concat("bs-popover","-").concat(attachment))}getTipElement(){return this.tip=this.tip||(0,_jquery.default)(this.config.template)[0],this.tip}setContent(){const $tip=(0,_jquery.default)(this.getTipElement());this.setElementContent($tip.find(".popover-header"),this.getTitle());let content=this._getContent();"function"==typeof content&&(content=content.call(this.element)),this.setElementContent($tip.find(".popover-body"),content),$tip.removeClass("".concat("fade"," ").concat("show"))}_getContent(){return this.element.getAttribute("data-content")||this.config.content}_cleanTipClass(){const $tip=(0,_jquery.default)(this.getTipElement()),tabClass=$tip.attr("class").match(BSCLS_PREFIX_REGEX);null!==tabClass&&tabClass.length>0&&$tip.removeClass(tabClass.join(""))}static _jQueryInterface(config){return this.each((function(){let data=(0,_jquery.default)(this).data("bs.popover");const _config="object"==typeof config?config:null;if((data||!/dispose|hide/.test(config))&&(data||(data=new Popover(this,_config),(0,_jquery.default)(this).data("bs.popover",data)),"string"==typeof config)){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}}_jquery.default.fn[NAME]=Popover._jQueryInterface,_jquery.default.fn[NAME].Constructor=Popover,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Popover._jQueryInterface);var _default=Popover;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/scrollspy",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const NAME="scrollspy",EVENT_KEY=".".concat("bs.scrollspy"),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],EVENT_ACTIVATE="activate".concat(EVENT_KEY),EVENT_SCROLL="scroll".concat(EVENT_KEY),EVENT_LOAD_DATA_API="load".concat(EVENT_KEY).concat(".data-api"),Default={offset:10,method:"auto",target:""},DefaultType={offset:"number",method:"string",target:"(string|element)"};class ScrollSpy{constructor(element,config){this._element=element,this._scrollElement="BODY"===element.tagName?window:element,this._config=this._getConfig(config),this._selector="".concat(this._config.target," ").concat(".nav-link",",")+"".concat(this._config.target," ").concat(".list-group-item",",")+"".concat(this._config.target," ").concat(".dropdown-item"),this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,(0,_jquery.default)(this._scrollElement).on(EVENT_SCROLL,(event=>this._process(event))),this.refresh(),this._process()}static get VERSION(){return"4.6.2"}static get Default(){return Default}refresh(){const autoMethod=this._scrollElement===this._scrollElement.window?"offset":"position",offsetMethod="auto"===this._config.method?autoMethod:this._config.method,offsetBase="position"===offsetMethod?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight();[].slice.call(document.querySelectorAll(this._selector)).map((element=>{let target;const targetSelector=_util.default.getSelectorFromElement(element);if(targetSelector&&(target=document.querySelector(targetSelector)),target){const targetBCR=target.getBoundingClientRect();if(targetBCR.width||targetBCR.height)return[(0,_jquery.default)(target)[offsetMethod]().top+offsetBase,targetSelector]}return null})).filter(Boolean).sort(((a,b)=>a[0]-b[0])).forEach((item=>{this._offsets.push(item[0]),this._targets.push(item[1])}))}dispose(){_jquery.default.removeData(this._element,"bs.scrollspy"),(0,_jquery.default)(this._scrollElement).off(EVENT_KEY),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null}_getConfig(config){if("string"!=typeof(config={...Default,..."object"==typeof config&&config?config:{}}).target&&_util.default.isElement(config.target)){let id=(0,_jquery.default)(config.target).attr("id");id||(id=_util.default.getUID(NAME),(0,_jquery.default)(config.target).attr("id",id)),config.target="#".concat(id)}return _util.default.typeCheckConfig(NAME,config,DefaultType),config}_getScrollTop(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop}_getScrollHeight(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}_getOffsetHeight(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height}_process(){const scrollTop=this._getScrollTop()+this._config.offset,scrollHeight=this._getScrollHeight(),maxScroll=this._config.offset+scrollHeight-this._getOffsetHeight();if(this._scrollHeight!==scrollHeight&&this.refresh(),scrollTop>=maxScroll){const target=this._targets[this._targets.length-1];this._activeTarget!==target&&this._activate(target)}else{if(this._activeTarget&&scrollTop<this._offsets[0]&&this._offsets[0]>0)return this._activeTarget=null,void this._clear();for(let i=this._offsets.length;i--;){this._activeTarget!==this._targets[i]&&scrollTop>=this._offsets[i]&&(void 0===this._offsets[i+1]||scrollTop<this._offsets[i+1])&&this._activate(this._targets[i])}}}_activate(target){this._activeTarget=target,this._clear();const queries=this._selector.split(",").map((selector=>"".concat(selector,'[data-target="').concat(target,'"],').concat(selector,'[href="').concat(target,'"]'))),$link=(0,_jquery.default)([].slice.call(document.querySelectorAll(queries.join(","))));$link.hasClass("dropdown-item")?($link.closest(".dropdown").find(".dropdown-toggle").addClass("active"),$link.addClass("active")):($link.addClass("active"),$link.parents(".nav, .list-group").prev("".concat(".nav-link",", ").concat(".list-group-item")).addClass("active"),$link.parents(".nav, .list-group").prev(".nav-item").children(".nav-link").addClass("active")),(0,_jquery.default)(this._scrollElement).trigger(EVENT_ACTIVATE,{relatedTarget:target})}_clear(){[].slice.call(document.querySelectorAll(this._selector)).filter((node=>node.classList.contains("active"))).forEach((node=>node.classList.remove("active")))}static _jQueryInterface(config){return this.each((function(){let data=(0,_jquery.default)(this).data("bs.scrollspy");if(data||(data=new ScrollSpy(this,"object"==typeof config&&config),(0,_jquery.default)(this).data("bs.scrollspy",data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}}(0,_jquery.default)(window).on(EVENT_LOAD_DATA_API,(()=>{const scrollSpys=[].slice.call(document.querySelectorAll('[data-spy="scroll"]'));for(let i=scrollSpys.length;i--;){const $spy=(0,_jquery.default)(scrollSpys[i]);ScrollSpy._jQueryInterface.call($spy,$spy.data())}})),_jquery.default.fn[NAME]=ScrollSpy._jQueryInterface,_jquery.default.fn[NAME].Constructor=ScrollSpy,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,ScrollSpy._jQueryInterface);var _default=ScrollSpy;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/tab",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const EVENT_KEY=".".concat("bs.tab"),JQUERY_NO_CONFLICT=_jquery.default.fn.tab,EVENT_HIDE="hide".concat(EVENT_KEY),EVENT_HIDDEN="hidden".concat(EVENT_KEY),EVENT_SHOW="show".concat(EVENT_KEY),EVENT_SHOWN="shown".concat(EVENT_KEY),EVENT_CLICK_DATA_API="click".concat(EVENT_KEY).concat(".data-api");class Tab{constructor(element){this._element=element}static get VERSION(){return"4.6.2"}show(){if(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&(0,_jquery.default)(this._element).hasClass("active")||(0,_jquery.default)(this._element).hasClass("disabled")||this._element.hasAttribute("disabled"))return;let target,previous;const listElement=(0,_jquery.default)(this._element).closest(".nav, .list-group")[0],selector=_util.default.getSelectorFromElement(this._element);if(listElement){const itemSelector="UL"===listElement.nodeName||"OL"===listElement.nodeName?"> li > .active":".active";previous=_jquery.default.makeArray((0,_jquery.default)(listElement).find(itemSelector)),previous=previous[previous.length-1]}const hideEvent=_jquery.default.Event(EVENT_HIDE,{relatedTarget:this._element}),showEvent=_jquery.default.Event(EVENT_SHOW,{relatedTarget:previous});if(previous&&(0,_jquery.default)(previous).trigger(hideEvent),(0,_jquery.default)(this._element).trigger(showEvent),showEvent.isDefaultPrevented()||hideEvent.isDefaultPrevented())return;selector&&(target=document.querySelector(selector)),this._activate(this._element,listElement);const complete=()=>{const hiddenEvent=_jquery.default.Event(EVENT_HIDDEN,{relatedTarget:this._element}),shownEvent=_jquery.default.Event(EVENT_SHOWN,{relatedTarget:previous});(0,_jquery.default)(previous).trigger(hiddenEvent),(0,_jquery.default)(this._element).trigger(shownEvent)};target?this._activate(target,target.parentNode,complete):complete()}dispose(){_jquery.default.removeData(this._element,"bs.tab"),this._element=null}_activate(element,container,callback){const active=(!container||"UL"!==container.nodeName&&"OL"!==container.nodeName?(0,_jquery.default)(container).children(".active"):(0,_jquery.default)(container).find("> li > .active"))[0],isTransitioning=callback&&active&&(0,_jquery.default)(active).hasClass("fade"),complete=()=>this._transitionComplete(element,active,callback);if(active&&isTransitioning){const transitionDuration=_util.default.getTransitionDurationFromElement(active);(0,_jquery.default)(active).removeClass("show").one(_util.default.TRANSITION_END,complete).emulateTransitionEnd(transitionDuration)}else complete()}_transitionComplete(element,active,callback){if(active){(0,_jquery.default)(active).removeClass("active");const dropdownChild=(0,_jquery.default)(active.parentNode).find("> .dropdown-menu .active")[0];dropdownChild&&(0,_jquery.default)(dropdownChild).removeClass("active"),"tab"===active.getAttribute("role")&&active.setAttribute("aria-selected",!1)}(0,_jquery.default)(element).addClass("active"),"tab"===element.getAttribute("role")&&element.setAttribute("aria-selected",!0),_util.default.reflow(element),element.classList.contains("fade")&&element.classList.add("show");let parent=element.parentNode;if(parent&&"LI"===parent.nodeName&&(parent=parent.parentNode),parent&&(0,_jquery.default)(parent).hasClass("dropdown-menu")){const dropdownElement=(0,_jquery.default)(element).closest(".dropdown")[0];if(dropdownElement){const dropdownToggleList=[].slice.call(dropdownElement.querySelectorAll(".dropdown-toggle"));(0,_jquery.default)(dropdownToggleList).addClass("active")}element.setAttribute("aria-expanded",!0)}callback&&callback()}static _jQueryInterface(config){return this.each((function(){const $this=(0,_jquery.default)(this);let data=$this.data("bs.tab");if(data||(data=new Tab(this),$this.data("bs.tab",data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}}(0,_jquery.default)(document).on(EVENT_CLICK_DATA_API,'[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',(function(event){event.preventDefault(),Tab._jQueryInterface.call((0,_jquery.default)(this),"show")})),_jquery.default.fn.tab=Tab._jQueryInterface,_jquery.default.fn.tab.Constructor=Tab,_jquery.default.fn.tab.noConflict=()=>(_jquery.default.fn.tab=JQUERY_NO_CONFLICT,Tab._jQueryInterface);var _default=Tab;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/toast",["exports","jquery","./util"],(function(_exports,_jquery,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_util=_interopRequireDefault(_util);const NAME="toast",EVENT_KEY=".".concat("bs.toast"),JQUERY_NO_CONFLICT=_jquery.default.fn.toast,EVENT_CLICK_DISMISS="click.dismiss".concat(EVENT_KEY),EVENT_HIDE="hide".concat(EVENT_KEY),EVENT_HIDDEN="hidden".concat(EVENT_KEY),EVENT_SHOW="show".concat(EVENT_KEY),EVENT_SHOWN="shown".concat(EVENT_KEY),Default={animation:!0,autohide:!0,delay:500},DefaultType={animation:"boolean",autohide:"boolean",delay:"number"};class Toast{constructor(element,config){this._element=element,this._config=this._getConfig(config),this._timeout=null,this._setListeners()}static get VERSION(){return"4.6.2"}static get DefaultType(){return DefaultType}static get Default(){return Default}show(){const showEvent=_jquery.default.Event(EVENT_SHOW);if((0,_jquery.default)(this._element).trigger(showEvent),showEvent.isDefaultPrevented())return;this._clearTimeout(),this._config.animation&&this._element.classList.add("fade");const complete=()=>{this._element.classList.remove("showing"),this._element.classList.add("show"),(0,_jquery.default)(this._element).trigger(EVENT_SHOWN),this._config.autohide&&(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay))};if(this._element.classList.remove("hide"),_util.default.reflow(this._element),this._element.classList.add("showing"),this._config.animation){const transitionDuration=_util.default.getTransitionDurationFromElement(this._element);(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,complete).emulateTransitionEnd(transitionDuration)}else complete()}hide(){if(!this._element.classList.contains("show"))return;const hideEvent=_jquery.default.Event(EVENT_HIDE);(0,_jquery.default)(this._element).trigger(hideEvent),hideEvent.isDefaultPrevented()||this._close()}dispose(){this._clearTimeout(),this._element.classList.contains("show")&&this._element.classList.remove("show"),(0,_jquery.default)(this._element).off(EVENT_CLICK_DISMISS),_jquery.default.removeData(this._element,"bs.toast"),this._element=null,this._config=null}_getConfig(config){return config={...Default,...(0,_jquery.default)(this._element).data(),..."object"==typeof config&&config?config:{}},_util.default.typeCheckConfig(NAME,config,this.constructor.DefaultType),config}_setListeners(){(0,_jquery.default)(this._element).on(EVENT_CLICK_DISMISS,'[data-dismiss="toast"]',(()=>this.hide()))}_close(){const complete=()=>{this._element.classList.add("hide"),(0,_jquery.default)(this._element).trigger(EVENT_HIDDEN)};if(this._element.classList.remove("show"),this._config.animation){const transitionDuration=_util.default.getTransitionDurationFromElement(this._element);(0,_jquery.default)(this._element).one(_util.default.TRANSITION_END,complete).emulateTransitionEnd(transitionDuration)}else complete()}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static _jQueryInterface(config){return this.each((function(){const $element=(0,_jquery.default)(this);let data=$element.data("bs.toast");if(data||(data=new Toast(this,"object"==typeof config&&config),$element.data("bs.toast",data)),"string"==typeof config){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config](this)}}))}}_jquery.default.fn.toast=Toast._jQueryInterface,_jquery.default.fn.toast.Constructor=Toast,_jquery.default.fn.toast.noConflict=()=>(_jquery.default.fn.toast=JQUERY_NO_CONFLICT,Toast._jQueryInterface);var _default=Toast;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/tools/sanitizer",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.DefaultWhitelist=void 0,_exports.sanitizeHtml=function(unsafeHtml,whiteList,sanitizeFn){if(0===unsafeHtml.length)return unsafeHtml;if(sanitizeFn&&"function"==typeof sanitizeFn)return sanitizeFn(unsafeHtml);const createdDocument=(new window.DOMParser).parseFromString(unsafeHtml,"text/html"),whitelistKeys=Object.keys(whiteList),elements=[].slice.call(createdDocument.body.querySelectorAll("*"));for(let i=0,len=elements.length;i<len;i++){const el=elements[i],elName=el.nodeName.toLowerCase();if(-1===whitelistKeys.indexOf(el.nodeName.toLowerCase())){el.parentNode.removeChild(el);continue}const attributeList=[].slice.call(el.attributes),whitelistedAttributes=[].concat(whiteList["*"]||[],whiteList[elName]||[]);attributeList.forEach((attr=>{allowedAttribute(attr,whitelistedAttributes)||el.removeAttribute(attr.nodeName)}))}return createdDocument.body.innerHTML};const uriAttrs=["background","cite","href","itemtype","longdesc","poster","src","xlink:href"],DefaultWhitelist={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]};_exports.DefaultWhitelist=DefaultWhitelist;const SAFE_URL_PATTERN=/^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i,DATA_URL_PATTERN=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i;function allowedAttribute(attr,allowedAttributeList){const attrName=attr.nodeName.toLowerCase();if(-1!==allowedAttributeList.indexOf(attrName))return-1===uriAttrs.indexOf(attrName)||Boolean(SAFE_URL_PATTERN.test(attr.nodeValue)||DATA_URL_PATTERN.test(attr.nodeValue));const regExp=allowedAttributeList.filter((attrRegex=>attrRegex instanceof RegExp));for(let i=0,len=regExp.length;i<len;i++)if(regExp[i].test(attrName))return!0;return!1}})); define("theme_boost/bootstrap/tooltip",["exports","./tools/sanitizer","jquery","core/popper","./util"],(function(_exports,_sanitizer,_jquery,_popper,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_popper=_interopRequireDefault(_popper),_util=_interopRequireDefault(_util);const NAME="tooltip",EVENT_KEY=".".concat("bs.tooltip"),JQUERY_NO_CONFLICT=_jquery.default.fn[NAME],BSCLS_PREFIX_REGEX=new RegExp("(^|\\s)".concat("bs-tooltip","\\S+"),"g"),DISALLOWED_ATTRIBUTES=["sanitize","whiteList","sanitizeFn"],AttachmentMap={AUTO:"auto",TOP:"top",RIGHT:"right",BOTTOM:"bottom",LEFT:"left"},Default={animation:!0,template:'<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent",customClass:"",sanitize:!0,sanitizeFn:null,whiteList:_sanitizer.DefaultWhitelist,popperConfig:null},DefaultType={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(number|string|function)",container:"(string|element|boolean)",fallbackPlacement:"(string|array)",boundary:"(string|element)",customClass:"(string|function)",sanitize:"boolean",sanitizeFn:"(null|function)",whiteList:"object",popperConfig:"(null|object)"},Event={HIDE:"hide".concat(EVENT_KEY),HIDDEN:"hidden".concat(EVENT_KEY),SHOW:"show".concat(EVENT_KEY),SHOWN:"shown".concat(EVENT_KEY),INSERTED:"inserted".concat(EVENT_KEY),CLICK:"click".concat(EVENT_KEY),FOCUSIN:"focusin".concat(EVENT_KEY),FOCUSOUT:"focusout".concat(EVENT_KEY),MOUSEENTER:"mouseenter".concat(EVENT_KEY),MOUSELEAVE:"mouseleave".concat(EVENT_KEY)};class Tooltip{constructor(element,config){if(void 0===_popper.default)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=element,this.config=this._getConfig(config),this.tip=null,this._setListeners()}static get VERSION(){return"4.6.2"}static get Default(){return Default}static get NAME(){return NAME}static get DATA_KEY(){return"bs.tooltip"}static get Event(){return Event}static get EVENT_KEY(){return EVENT_KEY}static get DefaultType(){return DefaultType}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(event){if(this._isEnabled)if(event){const dataKey=this.constructor.DATA_KEY;let context=(0,_jquery.default)(event.currentTarget).data(dataKey);context||(context=new this.constructor(event.currentTarget,this._getDelegateConfig()),(0,_jquery.default)(event.currentTarget).data(dataKey,context)),context._activeTrigger.click=!context._activeTrigger.click,context._isWithActiveTrigger()?context._enter(null,context):context._leave(null,context)}else{if((0,_jquery.default)(this.getTipElement()).hasClass("show"))return void this._leave(null,this);this._enter(null,this)}}dispose(){clearTimeout(this._timeout),_jquery.default.removeData(this.element,this.constructor.DATA_KEY),(0,_jquery.default)(this.element).off(this.constructor.EVENT_KEY),(0,_jquery.default)(this.element).closest(".modal").off("hide.bs.modal",this._hideModalHandler),this.tip&&(0,_jquery.default)(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null}show(){if("none"===(0,_jquery.default)(this.element).css("display"))throw new Error("Please use show on visible elements");const showEvent=_jquery.default.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){(0,_jquery.default)(this.element).trigger(showEvent);const shadowRoot=_util.default.findShadowRoot(this.element),isInTheDom=_jquery.default.contains(null!==shadowRoot?shadowRoot:this.element.ownerDocument.documentElement,this.element);if(showEvent.isDefaultPrevented()||!isInTheDom)return;const tip=this.getTipElement(),tipId=_util.default.getUID(this.constructor.NAME);tip.setAttribute("id",tipId),this.element.setAttribute("aria-describedby",tipId),this.setContent(),this.config.animation&&(0,_jquery.default)(tip).addClass("fade");const placement="function"==typeof this.config.placement?this.config.placement.call(this,tip,this.element):this.config.placement,attachment=this._getAttachment(placement);this.addAttachmentClass(attachment);const container=this._getContainer();(0,_jquery.default)(tip).data(this.constructor.DATA_KEY,this),_jquery.default.contains(this.element.ownerDocument.documentElement,this.tip)||(0,_jquery.default)(tip).appendTo(container),(0,_jquery.default)(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new _popper.default(this.element,tip,this._getPopperConfig(attachment)),(0,_jquery.default)(tip).addClass("show"),(0,_jquery.default)(tip).addClass(this.config.customClass),"ontouchstart"in document.documentElement&&(0,_jquery.default)(document.body).children().on("mouseover",null,_jquery.default.noop);const complete=()=>{this.config.animation&&this._fixTransition();const prevHoverState=this._hoverState;this._hoverState=null,(0,_jquery.default)(this.element).trigger(this.constructor.Event.SHOWN),"out"===prevHoverState&&this._leave(null,this)};if((0,_jquery.default)(this.tip).hasClass("fade")){const transitionDuration=_util.default.getTransitionDurationFromElement(this.tip);(0,_jquery.default)(this.tip).one(_util.default.TRANSITION_END,complete).emulateTransitionEnd(transitionDuration)}else complete()}}hide(callback){const tip=this.getTipElement(),hideEvent=_jquery.default.Event(this.constructor.Event.HIDE),complete=()=>{"show"!==this._hoverState&&tip.parentNode&&tip.parentNode.removeChild(tip),this._cleanTipClass(),this.element.removeAttribute("aria-describedby"),(0,_jquery.default)(this.element).trigger(this.constructor.Event.HIDDEN),null!==this._popper&&this._popper.destroy(),callback&&callback()};if((0,_jquery.default)(this.element).trigger(hideEvent),!hideEvent.isDefaultPrevented()){if((0,_jquery.default)(tip).removeClass("show"),"ontouchstart"in document.documentElement&&(0,_jquery.default)(document.body).children().off("mouseover",null,_jquery.default.noop),this._activeTrigger.click=!1,this._activeTrigger.focus=!1,this._activeTrigger.hover=!1,(0,_jquery.default)(this.tip).hasClass("fade")){const transitionDuration=_util.default.getTransitionDurationFromElement(tip);(0,_jquery.default)(tip).one(_util.default.TRANSITION_END,complete).emulateTransitionEnd(transitionDuration)}else complete();this._hoverState=""}}update(){null!==this._popper&&this._popper.scheduleUpdate()}isWithContent(){return Boolean(this.getTitle())}addAttachmentClass(attachment){(0,_jquery.default)(this.getTipElement()).addClass("".concat("bs-tooltip","-").concat(attachment))}getTipElement(){return this.tip=this.tip||(0,_jquery.default)(this.config.template)[0],this.tip}setContent(){const tip=this.getTipElement();this.setElementContent((0,_jquery.default)(tip.querySelectorAll(".tooltip-inner")),this.getTitle()),(0,_jquery.default)(tip).removeClass("".concat("fade"," ").concat("show"))}setElementContent($element,content){"object"!=typeof content||!content.nodeType&&!content.jquery?this.config.html?(this.config.sanitize&&(content=(0,_sanitizer.sanitizeHtml)(content,this.config.whiteList,this.config.sanitizeFn)),$element.html(content)):$element.text(content):this.config.html?(0,_jquery.default)(content).parent().is($element)||$element.empty().append(content):$element.text((0,_jquery.default)(content).text())}getTitle(){let title=this.element.getAttribute("data-original-title");return title||(title="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),title}_getPopperConfig(attachment){return{...{placement:attachment,modifiers:{offset:this._getOffset(),flip:{behavior:this.config.fallbackPlacement},arrow:{element:".arrow"},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:data=>{data.originalPlacement!==data.placement&&this._handlePopperPlacementChange(data)},onUpdate:data=>this._handlePopperPlacementChange(data)},...this.config.popperConfig}}_getOffset(){const offset={};return"function"==typeof this.config.offset?offset.fn=data=>(data.offsets={...data.offsets,...this.config.offset(data.offsets,this.element)},data):offset.offset=this.config.offset,offset}_getContainer(){return!1===this.config.container?document.body:_util.default.isElement(this.config.container)?(0,_jquery.default)(this.config.container):(0,_jquery.default)(document).find(this.config.container)}_getAttachment(placement){return AttachmentMap[placement.toUpperCase()]}_setListeners(){this.config.trigger.split(" ").forEach((trigger=>{if("click"===trigger)(0,_jquery.default)(this.element).on(this.constructor.Event.CLICK,this.config.selector,(event=>this.toggle(event)));else if("manual"!==trigger){const eventIn="hover"===trigger?this.constructor.Event.MOUSEENTER:this.constructor.Event.FOCUSIN,eventOut="hover"===trigger?this.constructor.Event.MOUSELEAVE:this.constructor.Event.FOCUSOUT;(0,_jquery.default)(this.element).on(eventIn,this.config.selector,(event=>this._enter(event))).on(eventOut,this.config.selector,(event=>this._leave(event)))}})),this._hideModalHandler=()=>{this.element&&this.hide()},(0,_jquery.default)(this.element).closest(".modal").on("hide.bs.modal",this._hideModalHandler),this.config.selector?this.config={...this.config,trigger:"manual",selector:""}:this._fixTitle()}_fixTitle(){const titleType=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==titleType)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))}_enter(event,context){const dataKey=this.constructor.DATA_KEY;(context=context||(0,_jquery.default)(event.currentTarget).data(dataKey))||(context=new this.constructor(event.currentTarget,this._getDelegateConfig()),(0,_jquery.default)(event.currentTarget).data(dataKey,context)),event&&(context._activeTrigger["focusin"===event.type?"focus":"hover"]=!0),(0,_jquery.default)(context.getTipElement()).hasClass("show")||"show"===context._hoverState?context._hoverState="show":(clearTimeout(context._timeout),context._hoverState="show",context.config.delay&&context.config.delay.show?context._timeout=setTimeout((()=>{"show"===context._hoverState&&context.show()}),context.config.delay.show):context.show())}_leave(event,context){const dataKey=this.constructor.DATA_KEY;(context=context||(0,_jquery.default)(event.currentTarget).data(dataKey))||(context=new this.constructor(event.currentTarget,this._getDelegateConfig()),(0,_jquery.default)(event.currentTarget).data(dataKey,context)),event&&(context._activeTrigger["focusout"===event.type?"focus":"hover"]=!1),context._isWithActiveTrigger()||(clearTimeout(context._timeout),context._hoverState="out",context.config.delay&&context.config.delay.hide?context._timeout=setTimeout((()=>{"out"===context._hoverState&&context.hide()}),context.config.delay.hide):context.hide())}_isWithActiveTrigger(){for(const trigger in this._activeTrigger)if(this._activeTrigger[trigger])return!0;return!1}_getConfig(config){const dataAttributes=(0,_jquery.default)(this.element).data();return Object.keys(dataAttributes).forEach((dataAttr=>{-1!==DISALLOWED_ATTRIBUTES.indexOf(dataAttr)&&delete dataAttributes[dataAttr]})),"number"==typeof(config={...this.constructor.Default,...dataAttributes,..."object"==typeof config&&config?config:{}}).delay&&(config.delay={show:config.delay,hide:config.delay}),"number"==typeof config.title&&(config.title=config.title.toString()),"number"==typeof config.content&&(config.content=config.content.toString()),_util.default.typeCheckConfig(NAME,config,this.constructor.DefaultType),config.sanitize&&(config.template=(0,_sanitizer.sanitizeHtml)(config.template,config.whiteList,config.sanitizeFn)),config}_getDelegateConfig(){const config={};if(this.config)for(const key in this.config)this.constructor.Default[key]!==this.config[key]&&(config[key]=this.config[key]);return config}_cleanTipClass(){const $tip=(0,_jquery.default)(this.getTipElement()),tabClass=$tip.attr("class").match(BSCLS_PREFIX_REGEX);null!==tabClass&&tabClass.length&&$tip.removeClass(tabClass.join(""))}_handlePopperPlacementChange(popperData){this.tip=popperData.instance.popper,this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(popperData.placement))}_fixTransition(){const tip=this.getTipElement(),initConfigAnimation=this.config.animation;null===tip.getAttribute("x-placement")&&((0,_jquery.default)(tip).removeClass("fade"),this.config.animation=!1,this.hide(),this.show(),this.config.animation=initConfigAnimation)}static _jQueryInterface(config){return this.each((function(){const $element=(0,_jquery.default)(this);let data=$element.data("bs.tooltip");const _config="object"==typeof config&&config;if((data||!/dispose|hide/.test(config))&&(data||(data=new Tooltip(this,_config),$element.data("bs.tooltip",data)),"string"==typeof config)){if(void 0===data[config])throw new TypeError('No method named "'.concat(config,'"'));data[config]()}}))}}_jquery.default.fn[NAME]=Tooltip._jQueryInterface,_jquery.default.fn[NAME].Constructor=Tooltip,_jquery.default.fn[NAME].noConflict=()=>(_jquery.default.fn[NAME]=JQUERY_NO_CONFLICT,Tooltip._jQueryInterface);var _default=Tooltip;return _exports.default=_default,_exports.default})); define("theme_boost/bootstrap/util",["exports","jquery"],(function(_exports,_jquery){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=(obj=_jquery)&&obj.__esModule?obj:{default:obj};function toType(obj){return null==obj?"".concat(obj):{}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase()}function transitionEndEmulator(duration){let called=!1;return(0,_jquery.default)(this).one(Util.TRANSITION_END,(()=>{called=!0})),setTimeout((()=>{called||Util.triggerTransitionEnd(this)}),duration),this}const Util={TRANSITION_END:"bsTransitionEnd",getUID(prefix){do{prefix+=~~(1e6*Math.random())}while(document.getElementById(prefix));return prefix},getSelectorFromElement(element){let selector=element.getAttribute("data-target");if(!selector||"#"===selector){const hrefAttr=element.getAttribute("href");selector=hrefAttr&&"#"!==hrefAttr?hrefAttr.trim():""}try{return document.querySelector(selector)?selector:null}catch(_){return null}},getTransitionDurationFromElement(element){if(!element)return 0;let transitionDuration=(0,_jquery.default)(element).css("transition-duration"),transitionDelay=(0,_jquery.default)(element).css("transition-delay");const floatTransitionDuration=parseFloat(transitionDuration),floatTransitionDelay=parseFloat(transitionDelay);return floatTransitionDuration||floatTransitionDelay?(transitionDuration=transitionDuration.split(",")[0],transitionDelay=transitionDelay.split(",")[0],1e3*(parseFloat(transitionDuration)+parseFloat(transitionDelay))):0},reflow:element=>element.offsetHeight,triggerTransitionEnd(element){(0,_jquery.default)(element).trigger("transitionend")},supportsTransitionEnd:()=>Boolean("transitionend"),isElement:obj=>(obj[0]||obj).nodeType,typeCheckConfig(componentName,config,configTypes){for(const property in configTypes)if(Object.prototype.hasOwnProperty.call(configTypes,property)){const expectedTypes=configTypes[property],value=config[property],valueType=value&&Util.isElement(value)?"element":toType(value);if(!new RegExp(expectedTypes).test(valueType))throw new Error("".concat(componentName.toUpperCase(),": ")+'Option "'.concat(property,'" provided type "').concat(valueType,'" ')+'but expected type "'.concat(expectedTypes,'".'))}},findShadowRoot(element){if(!document.documentElement.attachShadow)return null;if("function"==typeof element.getRootNode){const root=element.getRootNode();return root instanceof ShadowRoot?root:null}return element instanceof ShadowRoot?element:element.parentNode?Util.findShadowRoot(element.parentNode):null},jQueryDetection(){if(void 0===_jquery.default)throw new TypeError("Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.");const version=_jquery.default.fn.jquery.split(" ")[0].split(".");if(version[0]<2&&version[1]<9||1===version[0]&&9===version[1]&&version[2]<1||version[0]>=4)throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}};Util.jQueryDetection(),_jquery.default.fn.emulateTransitionEnd=transitionEndEmulator,_jquery.default.event.special[Util.TRANSITION_END]={bindType:"transitionend",delegateType:"transitionend",handle(event){if((0,_jquery.default)(event.target).is(this))return event.handleObj.handler.apply(this,arguments)}};var _default=Util;return _exports.default=_default,_exports.default})); /** * Custom form error event handler to manipulate the bootstrap markup and show * nicely styled errors in an mform. * * @module theme_boost/form-display-errors * @copyright 2016 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("theme_boost/form-display-errors",["jquery","core_form/events"],(function($,FormEvent){return{enhance:function(elementid){var element=document.getElementById(elementid);if(element){element.addEventListener(FormEvent.eventTypes.formFieldValidationFailed,(e=>{const msg=e.detail.message;e.preventDefault();var parent=$(element).closest(".form-group"),feedback=parent.find(".form-control-feedback");const feedbackId=feedback.attr("id");let describedBy=$(element).attr("aria-describedby");void 0===describedBy&&(describedBy="");let describedByIds=[];describedBy.length&&(describedByIds=describedBy.split(" "));const feedbackIndex=describedByIds.indexOf(feedbackId);"TEXTAREA"==$(element).prop("tagName")&&parent.find("[contenteditable]").length>0&&(element=parent.find("[contenteditable]")),""!==msg?(parent.addClass("has-danger"),parent.data("client-validation-error",!0),$(element).addClass("is-invalid"),-1===feedbackIndex&&(describedByIds.push(feedbackId),$(element).attr("aria-describedby",describedByIds.join(" "))),$(element).attr("aria-invalid",!0),feedback.attr("tabindex",0),feedback.html(msg),feedback.is(":visible")||(feedback.show(),feedback.focus())):!0===parent.data("client-validation-error")&&(parent.removeClass("has-danger"),parent.data("client-validation-error",!1),$(element).removeClass("is-invalid"),feedbackIndex>-1&&describedByIds.splice(feedbackIndex,1),describedByIds.length?(describedBy=describedByIds.join(" "),$(element).attr("aria-describedby",describedBy)):$(element).removeAttr("aria-describedby"),$(element).attr("aria-invalid",!1),feedback.hide())}));var form=element.closest("form");form&&!("boostFormErrorsEnhanced"in form.dataset)&&(form.addEventListener("submit",(function(){var visibleError=$(".form-control-feedback:visible");visibleError.length&&visibleError[0].focus()})),form.dataset.boostFormErrorsEnhanced=1)}}}})); define("theme_boost/index",["exports","./bootstrap/alert","./bootstrap/button","./bootstrap/carousel","./bootstrap/collapse","./bootstrap/dropdown","./bootstrap/modal","./bootstrap/popover","./bootstrap/scrollspy","./bootstrap/tab","./bootstrap/toast","./bootstrap/tooltip","./bootstrap/util"],(function(_exports,_alert,_button,_carousel,_collapse,_dropdown,_modal,_popover,_scrollspy,_tab,_toast,_tooltip,_util){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Alert",{enumerable:!0,get:function(){return _alert.default}}),Object.defineProperty(_exports,"Button",{enumerable:!0,get:function(){return _button.default}}),Object.defineProperty(_exports,"Carousel",{enumerable:!0,get:function(){return _carousel.default}}),Object.defineProperty(_exports,"Collapse",{enumerable:!0,get:function(){return _collapse.default}}),Object.defineProperty(_exports,"Dropdown",{enumerable:!0,get:function(){return _dropdown.default}}),Object.defineProperty(_exports,"Modal",{enumerable:!0,get:function(){return _modal.default}}),Object.defineProperty(_exports,"Popover",{enumerable:!0,get:function(){return _popover.default}}),Object.defineProperty(_exports,"Scrollspy",{enumerable:!0,get:function(){return _scrollspy.default}}),Object.defineProperty(_exports,"Tab",{enumerable:!0,get:function(){return _tab.default}}),Object.defineProperty(_exports,"Toast",{enumerable:!0,get:function(){return _toast.default}}),Object.defineProperty(_exports,"Tooltip",{enumerable:!0,get:function(){return _tooltip.default}}),Object.defineProperty(_exports,"Util",{enumerable:!0,get:function(){return _util.default}}),_alert=_interopRequireDefault(_alert),_button=_interopRequireDefault(_button),_carousel=_interopRequireDefault(_carousel),_collapse=_interopRequireDefault(_collapse),_dropdown=_interopRequireDefault(_dropdown),_modal=_interopRequireDefault(_modal),_popover=_interopRequireDefault(_popover),_scrollspy=_interopRequireDefault(_scrollspy),_tab=_interopRequireDefault(_tab),_toast=_interopRequireDefault(_toast),_tooltip=_interopRequireDefault(_tooltip),_util=_interopRequireDefault(_util)})); define("theme_boost/loader",["exports","jquery","./aria","./index","core/pending","./bootstrap/tools/sanitizer","./pending"],(function(_exports,_jquery,Aria,_index,_pending,_sanitizer,_pending2){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Template renderer for Moodle. Load and render Moodle templates with Mustache. * * @module theme_boost/loader * @copyright 2015 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since 2.9 */Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Bootstrap",{enumerable:!0,get:function(){return _index.default}}),_jquery=_interopRequireDefault(_jquery),Aria=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Aria),_index=_interopRequireDefault(_index),_pending=_interopRequireDefault(_pending),_pending2=_interopRequireDefault(_pending2);const pendingPromise=new _pending.default("theme_boost/loader:init");(0,_pending2.default)(),Aria.init(),(()=>{(0,_jquery.default)('a[data-toggle="tab"]').on("shown.bs.tab",(function(e){var hash=(0,_jquery.default)(e.target).attr("href");history.replaceState?history.replaceState(null,null,hash):location.hash=hash}));const hash=window.location.hash;if(hash){const tab=document.querySelector('[role="tablist"] [href="'+hash+'"]');tab&&tab.click()}})(),(0,_jquery.default)("body").popover({container:"body",selector:'[data-toggle="popover"]',trigger:"focus",whitelist:Object.assign(_sanitizer.DefaultWhitelist,{table:[],thead:[],tbody:[],tr:[],th:[],td:[]})}),document.addEventListener("keydown",(e=>{"Escape"===e.key&&e.target.closest('[data-toggle="popover"]')&&(0,_jquery.default)(e.target).popover("hide")})),(0,_jquery.default)("body").tooltip({container:"body",selector:'[data-toggle="tooltip"]'}),_jquery.default.fn.dropdown.Constructor.Default.popperConfig={modifiers:{flip:{enabled:!1},storeTopPosition:{enabled:!0,fn:(data,options)=>(data.storedTop=data.offsets.popper.top,data),order:299},restoreTopPosition:{enabled:!0,fn:(data,options)=>(data.offsets.popper.top=data.storedTop,data),order:301}}},pendingPromise.resolve()})); define("theme_boost/pending",["exports","jquery"],(function(_exports,_jquery){var obj; /** * Add Pending JS checks to stock Bootstrap transitions. * * @module theme_boost/pending * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @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 moduleTransitions={alert:[{start:"close",end:"closed"}],carousel:[{start:"slide",end:"slid"}],collapse:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],dropdown:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],modal:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],popover:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],tab:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],toast:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}],tooltip:[{start:"hide",end:"hidden"},{start:"show",end:"shown"}]};return _exports.default=()=>{Object.entries(moduleTransitions).forEach((_ref=>{let[key,pairs]=_ref;pairs.forEach((pair=>{const eventStart="".concat(pair.start,".bs.").concat(key),eventEnd="".concat(pair.end,".bs.").concat(key);(0,_jquery.default)(document.body).on(eventStart,(e=>{M.util.js_pending(eventEnd),(0,_jquery.default)(e.target).one(eventEnd,(()=>{M.util.js_complete(eventEnd)}))}))}))}))},_exports.default})); define("theme_boost/popover",["exports","./bootstrap/popover"],(function(_exports,_popover){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Popover",{enumerable:!0,get:function(){return _popover.default}}),_popover=(obj=_popover)&&obj.__esModule?obj:{default:obj}})); define("theme_boost/toast",["exports","./bootstrap/toast"],(function(_exports,_toast){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Toast",{enumerable:!0,get:function(){return _toast.default}}),_toast=(obj=_toast)&&obj.__esModule?obj:{default:obj}})); define("theme_boost/aria",["exports","jquery","core/pending"],(function(_exports,_jquery,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Enhancements to Bootstrap components for accessibility. * * @module theme_boost/aria * @copyright 2018 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending);const dropdownFix=()=>{let focusEnd=!1;const setFocusEnd=function(){let end=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];focusEnd=end},shiftFocus=element=>{setTimeout((pendingPromise=>{element.focus(),pendingPromise.resolve()}),50,new _pending.default("core/aria:delayed-focus"))},handleMenuButton=e=>{const trigger=e.key;let fixFocus=!1;if(" "!==trigger&&"Enter"!==trigger||(fixFocus=!0,e.preventDefault(),e.target.click()),"ArrowUp"!==trigger&&"ArrowDown"!==trigger||(fixFocus=!0),!fixFocus)return;const menu=e.target.parentElement.querySelector('[role="menu"]');let menuItems=!1,foundMenuItem=!1;menu&&(menuItems=menu.querySelectorAll('[role="menuitem"]')),menuItems&&menuItems.length>0&&("ArrowUp"===trigger?setFocusEnd():setFocusEnd(!1),foundMenuItem=(()=>{const result=focusEnd;return focusEnd=!1,result})()?menuItems[menuItems.length-1]:menuItems[0]),foundMenuItem&&shiftFocus(foundMenuItem)};document.addEventListener("keypress",(e=>{if(e.target.matches('.dropdown [role="menu"] [role="menuitem"]')){const menu=e.target.closest('[role="menu"]');if(!menu)return;const menuItems=menu.querySelectorAll('[role="menuitem"]');if(!menuItems)return;const trigger=e.key.toLowerCase();for(let i=0;i<menuItems.length;i++){const item=menuItems[i];if(0==item.text.trim().toLowerCase().indexOf(trigger)){shiftFocus(item);break}}}})),document.addEventListener("keydown",(e=>{if(e.target.matches('[data-toggle="dropdown"]')&&handleMenuButton(e),e.target.matches('.dropdown [role="menu"] [role="menuitem"]')){const trigger=e.key;let next=!1;const menu=e.target.closest('[role="menu"]');if(!menu)return;const menuItems=menu.querySelectorAll('[role="menuitem"]');if(!menuItems)return;if("ArrowDown"==trigger){for(let i=0;i<menuItems.length-1;i++)if(menuItems[i]==e.target){next=menuItems[i+1];break}next||(next=menuItems[0])}else if("ArrowUp"==trigger){for(let i=1;i<menuItems.length;i++)if(menuItems[i]==e.target){next=menuItems[i-1];break}next||(next=menuItems[menuItems.length-1])}else"Home"==trigger?next=menuItems[0]:"End"==trigger&&(next=menuItems[menuItems.length-1]);next&&(e.preventDefault(),shiftFocus(next))}else;})),(0,_jquery.default)(".dropdown").on("hidden.bs.dropdown",(e=>{const trigger=e.target.querySelector('[data-toggle="dropdown"]'),focused=document.activeElement!=document.body?document.activeElement:null;trigger&&focused&&e.target.contains(focused)&&shiftFocus(trigger)}))},tabElementFix=()=>{document.addEventListener("keydown",(e=>{["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"].includes(e.key)&&e.target.matches('[role="tablist"] [role="tab"]')&&(e=>{const tabList=e.target.closest('[role="tablist"]'),vertical="vertical"==tabList.getAttribute("aria-orientation"),rtl=window.right_to_left(),arrowNext=vertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",arrowPrevious=vertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft",tabs=Array.prototype.filter.call(tabList.querySelectorAll('[role="tab"]'),(tab=>!!tab.offsetHeight));for(let i=0;i<tabs.length;i++)tabs[i].index=i;switch(e.key){case arrowNext:e.preventDefault(),void 0!==e.target.index&&tabs[e.target.index+1]?tabs[e.target.index+1].focus():tabs[0].focus();break;case arrowPrevious:e.preventDefault(),void 0!==e.target.index&&tabs[e.target.index-1]?tabs[e.target.index-1].focus():tabs[tabs.length-1].focus();break;case"Home":e.preventDefault(),tabs[0].focus();break;case"End":e.preventDefault(),tabs[tabs.length-1].focus()}})(e)})),document.addEventListener("click",(e=>{if(e.target.matches('[role="tablist"] [data-toggle="tab"], [role="tablist"] [data-toggle="pill"]')){const tabs=e.target.closest('[role="tablist"]').querySelectorAll('[data-toggle="tab"], [data-toggle="pill"]');e.preventDefault(),(0,_jquery.default)(e.target).tab("show"),tabs.forEach((tab=>{tab.tabIndex=-1})),e.target.tabIndex=0}}))};_exports.init=()=>{dropdownFix(),(()=>{(0,_jquery.default)(document).on("show.bs.dropdown",(e=>{if(e.relatedTarget.matches('[role="combobox"]')){const combobox=e.relatedTarget,listbox=combobox.parentElement.querySelector('[role="listbox"]'),selectedOption=listbox.querySelector('[role="option"][aria-selected="true"]');setTimeout((()=>{if(selectedOption)selectedOption.classList.add("active"),combobox.setAttribute("aria-activedescendant",selectedOption.id);else{const firstOption=listbox.querySelector('[role="option"]');firstOption.setAttribute("aria-selected","true"),firstOption.classList.add("active"),combobox.setAttribute("aria-activedescendant",firstOption.id)}}),0)}})),(0,_jquery.default)(document).on("hidden.bs.dropdown",(e=>{if(e.relatedTarget.matches('[role="combobox"]')){const combobox=e.relatedTarget,listbox=combobox.parentElement.querySelector('[role="listbox"]');combobox.removeAttribute("aria-activedescendant"),setTimeout((()=>{listbox.querySelectorAll('.active[role="option"]').forEach((option=>{option.classList.remove("active")}))}),0)}})),document.addEventListener("keydown",(e=>{if(e.target.matches('.select-menu [role="combobox"]')){const combobox=e.target,trigger=e.key;let next=null;const options=combobox.parentElement.querySelectorAll('[role="listbox"] [role="option"]'),activeOption=combobox.parentElement.querySelector('[role="listbox"] .active[role="option"]');if(options&&activeOption){if("ArrowDown"==trigger)for(let i=0;i<options.length-1;i++)if(options[i]==activeOption){next=options[i+1];break}if("ArrowUp"==trigger){for(let i=1;i<options.length;i++)if(options[i]==activeOption){next=options[i-1];break}}else if("Home"==trigger)next=options[0];else if("End"==trigger)next=options[options.length-1];else if(" "==trigger||"Enter"==trigger)selectOption(combobox,activeOption);else for(let i=0;i<options.length;i++){const option=options[i],optionText=option.textContent.trim().toLowerCase(),keyPressed=e.key.toLowerCase();if(0==optionText.indexOf(keyPressed)){next=option;break}}next&&(e.preventDefault(),activeOption.classList.remove("active"),next.classList.add("active"),combobox.setAttribute("aria-activedescendant",next.id))}}})),document.addEventListener("click",(e=>{if(e.target.matches('.select-menu [role="option"]')){const option=e.target,combobox=option.closest(".select-menu").querySelector('[role="combobox"]');combobox.focus(),selectOption(combobox,option)}})),document.addEventListener("change",(e=>{if(e.target.matches('.select-menu input[type="hidden"]')){const combobox=e.target.parentElement.querySelector('[role="combobox"]'),option=e.target.parentElement.querySelector('[role="option"][data-value="'.concat(e.target.value,'"]'));combobox&&option&&selectOption(combobox,option)}}));const selectOption=(combobox,option)=>{const oldSelectedOption=combobox.parentElement.querySelector('[role="listbox"] [role="option"][aria-selected="true"]'),inputElement=combobox.parentElement.querySelector('input[type="hidden"]');oldSelectedOption!=option&&(oldSelectedOption&&oldSelectedOption.removeAttribute("aria-selected"),option.setAttribute("aria-selected","true")),combobox.textContent=option.textContent,inputElement.value!=option.dataset.value&&(inputElement.value=option.dataset.value,inputElement.dispatchEvent(new Event("change",{bubbles:!0})))}})(),window.addEventListener("load",(()=>{const alerts=document.querySelectorAll('[data-aria-autofocus="true"][role="alert"]');Array.prototype.forEach.call(alerts,(autofocusElement=>{autofocusElement.innerHTML+=" ",autofocusElement.removeAttribute("data-aria-autofocus")}))})),tabElementFix(),document.addEventListener("keydown",(e=>{e.target.matches('[data-toggle="collapse"]')&&" "===e.key&&(e.preventDefault(),e.target.click())}))}})); /** * Contain the logic for a drawer. * * @module theme_boost/drawer * @copyright 2016 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("theme_boost/drawer",["jquery","core/custom_interaction_events","core/log","core/pubsub","core/aria"],(function($,CustomEvents,Log,PubSub,Aria){var SELECTORS_TOGGLE_REGION='[data-region="drawer-toggle"]',SELECTORS_TOGGLE_ACTION='[data-action="toggle-drawer"]',SELECTORS_BODY="body",SELECTORS_SECTION='.list-group-item[href*="#section-"]',SELECTORS_DRAWER="#nav-drawer",small=$(document).width()<768,Drawer=function(){$(SELECTORS_TOGGLE_REGION).length||Log.debug("Page is missing a drawer region"),$(SELECTORS_TOGGLE_ACTION).length||Log.debug("Page is missing a drawer toggle link"),$(SELECTORS_TOGGLE_REGION).each(function(index,ele){var trigger=$(ele).find(SELECTORS_TOGGLE_ACTION),drawerid=trigger.attr("aria-controls"),drawer=$(document.getElementById(drawerid)),hidden="false"==trigger.attr("aria-expanded"),side=trigger.attr("data-side"),body=$(SELECTORS_BODY),preference=trigger.attr("data-preference");small&&M.util.set_user_preference(preference,"false"),drawer.on("mousewheel DOMMouseScroll",this.preventPageScroll),hidden?trigger.attr("aria-expanded","false"):(body.addClass("drawer-open-"+side),trigger.attr("aria-expanded","true"))}.bind(this)),this.registerEventListeners(),small&&this.closeAll()};return Drawer.prototype.closeAll=function(){$(SELECTORS_TOGGLE_REGION).each((function(index,ele){var trigger=$(ele).find(SELECTORS_TOGGLE_ACTION),side=trigger.attr("data-side"),body=$(SELECTORS_BODY),drawerid=trigger.attr("aria-controls"),drawer=$(document.getElementById(drawerid)),preference=trigger.attr("data-preference");trigger.attr("aria-expanded","false"),body.removeClass("drawer-open-"+side),Aria.hide(drawer.get()),drawer.addClass("closed"),small||M.util.set_user_preference(preference,"false")}))},Drawer.prototype.toggleDrawer=function(e){var trigger=$(e.target).closest("[data-action=toggle-drawer]"),drawerid=trigger.attr("aria-controls"),drawer=$(document.getElementById(drawerid)),body=$(SELECTORS_BODY),side=trigger.attr("data-side"),preference=trigger.attr("data-preference");small&&M.util.set_user_preference(preference,"false"),body.addClass("drawer-ease");var open="true"==trigger.attr("aria-expanded");open?(body.removeClass("drawer-open-"+side),trigger.attr("aria-expanded","false"),drawer.addClass("closed").delay(500).queue((function(){$(this).hasClass("closed")&&Aria.hide(this),$(this).dequeue()})),small||M.util.set_user_preference(preference,"false")):(trigger.attr("aria-expanded","true"),Aria.unhide(drawer.get()),drawer.focus(),body.addClass("drawer-open-"+side),drawer.removeClass("closed"),small||M.util.set_user_preference(preference,"true")),PubSub.publish("nav-drawer-toggle-start",open)},Drawer.prototype.preventPageScroll=function(e){var delta=e.wheelDelta||e.originalEvent&&e.originalEvent.wheelDelta||-e.originalEvent.detail,bottomOverflow=this.scrollTop+$(this).outerHeight()-this.scrollHeight>=0,topOverflow=this.scrollTop<=0;(delta<0&&bottomOverflow||delta>0&&topOverflow)&&e.preventDefault()},Drawer.prototype.registerEventListeners=function(){$(SELECTORS_TOGGLE_ACTION).each(function(index,element){CustomEvents.define($(element),[CustomEvents.events.activate]),$(element).on(CustomEvents.events.activate,function(e,data){this.toggleDrawer(data.originalEvent),data.originalEvent.preventDefault()}.bind(this))}.bind(this)),$(SELECTORS_SECTION).click(function(){small&&this.closeAll()}.bind(this)),$(SELECTORS_DRAWER).on("webkitTransitionEnd msTransitionEnd transitionend",(function(e){var open=!!$(e.target).closest(SELECTORS_DRAWER).attr("aria-hidden");PubSub.publish("nav-drawer-toggle-end",open)}))},{init:function(){return new Drawer}}})); define("theme_boost/drawers",["exports","core/modal_backdrop","core/templates","core/aria","core/event_dispatcher","core/utils","core/pending","jquery"],(function(_exports,_modal_backdrop,_templates,Aria,_event_dispatcher,_utils,_pending,_jquery){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal_backdrop=_interopRequireDefault(_modal_backdrop),_templates=_interopRequireDefault(_templates),Aria=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Aria),_pending=_interopRequireDefault(_pending),_jquery=_interopRequireDefault(_jquery);let backdropPromise=null;const drawerMap=new Map,SELECTORS_BUTTONS='[data-toggler="drawers"]',SELECTORS_CLOSEBTN='[data-toggler="drawers"][data-action="closedrawer"]',SELECTORS_OPENBTN='[data-toggler="drawers"][data-action="opendrawer"]',SELECTORS_TOGGLEBTN='[data-toggler="drawers"][data-action="toggle"]',SELECTORS_DRAWERS='[data-region="fixed-drawer"]',SELECTORS_CONTAINER="#page.drawers",SELECTORS_DRAWERCONTENT=".drawercontent",CLASSES_SCROLLED="scrolled",CLASSES_SHOW="show",CLASSES_NOTINITIALISED="not-initialized",CLASSES_TOGGLERIGHT=".drawer-right-toggle",sizes_medium=991,sizes_large=1400,getCurrentWidth=()=>{const DomRect=document.body.getBoundingClientRect();return DomRect.x+DomRect.width},isSmall=()=>getCurrentWidth()<sizes_medium,getBackdrop=()=>(backdropPromise||(backdropPromise=_templates.default.render("core/modal_backdrop",{}).then((html=>new _modal_backdrop.default(html))).then((modalBackdrop=>(modalBackdrop.getAttachmentPoint().get(0).addEventListener("click",(e=>{e.preventDefault(),Drawers.closeAllDrawers()})),modalBackdrop))).catch()),backdropPromise),getDrawerOpenButton=drawerId=>{let openButton=document.querySelector("".concat(SELECTORS_OPENBTN,'[data-target="').concat(drawerId,'"]'));return openButton||(openButton=document.querySelector("".concat(SELECTORS_TOGGLEBTN,'[data-target="').concat(drawerId,'"]'))),openButton},disableDrawerTooltips=drawerNode=>{[drawerNode.querySelector(SELECTORS_CLOSEBTN),getDrawerOpenButton(drawerNode.id)].forEach((button=>{button&&disableButtonTooltip(button)}))},disableButtonTooltip=(button,enableOnBlur)=>{button.hasAttribute("data-original-title")?((0,_jquery.default)(button).tooltip("disable"),button.setAttribute("title",button.dataset.originalTitle)):(button.dataset.disabledToggle=button.dataset.toggle,button.removeAttribute("data-toggle")),enableOnBlur&&(button.dataset.restoreTooltipOnBlur=!0)},enableButtonTooltip=button=>{button.hasAttribute("data-original-title")?((0,_jquery.default)(button).tooltip("enable"),button.removeAttribute("title")):button.dataset.disabledToggle&&(button.dataset.toggle=button.dataset.disabledToggle,(0,_jquery.default)(button).tooltip()),delete button.dataset.restoreTooltipOnBlur};class Drawers{constructor(drawerNode){_defineProperty(this,"drawerNode",null),this.drawerNode=drawerNode,isSmall()&&this.closeDrawer({focusOnOpenButton:!1,updatePreferences:!1}),this.drawerNode.classList.contains(CLASSES_SHOW)?this.openDrawer({focusOnCloseButton:!1}):1==this.drawerNode.dataset.forceopen?isSmall()||this.openDrawer({focusOnCloseButton:!1}):Aria.hide(this.drawerNode),isSmall()&&disableDrawerTooltips(this.drawerNode),(drawerNode=>{const content=drawerNode.querySelector(SELECTORS_DRAWERCONTENT);content&&content.addEventListener("scroll",(()=>{drawerNode.classList.toggle(CLASSES_SCROLLED,0!=content.scrollTop)}))})(this.drawerNode),drawerMap.set(drawerNode,this),drawerNode.classList.remove(CLASSES_NOTINITIALISED)}get isOpen(){return this.drawerNode.classList.contains(CLASSES_SHOW)}get closeOnResize(){return!!parseInt(this.drawerNode.dataset.closeOnResize)}static getDrawerInstanceForNode(drawerNode){return drawerMap.has(drawerNode)||new Drawers(drawerNode),drawerMap.get(drawerNode)}dispatchEvent(eventname){let cancelable=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return(0,_event_dispatcher.dispatchEvent)(eventname,{drawerInstance:this},this.drawerNode,{cancelable:cancelable})}openDrawer(){var _this$drawerNode$quer;let{focusOnCloseButton:focusOnCloseButton=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const pendingPromise=new _pending.default("theme_boost/drawers:open");if(this.dispatchEvent(Drawers.eventTypes.drawerShow,!0).defaultPrevented)return;null===(_this$drawerNode$quer=this.drawerNode.querySelector(SELECTORS_CLOSEBTN))||void 0===_this$drawerNode$quer||_this$drawerNode$quer.classList.toggle("hidden",!0);let openButton=getDrawerOpenButton(this.drawerNode.id);var _jQuery;openButton&&openButton.hasAttribute("data-original-title")&&(null===(_jQuery=(0,_jquery.default)(openButton))||void 0===_jQuery||_jQuery.tooltip("hide"));Aria.unhide(this.drawerNode),this.drawerNode.classList.add(CLASSES_SHOW);const preference=this.drawerNode.dataset.preference;preference&&!isSmall()&&1!=this.drawerNode.dataset.forceopen&&M.util.set_user_preference(preference,!0);const state=this.drawerNode.dataset.state;if(state){document.getElementById("page").classList.add(state)}isSmall()&&getBackdrop().then((backdrop=>{backdrop.show();return document.getElementById("page").style.overflow="hidden",backdrop})).catch();const closeButton=this.drawerNode.querySelector(SELECTORS_CLOSEBTN);focusOnCloseButton&&closeButton&&disableButtonTooltip(closeButton,!0),setTimeout((()=>{closeButton.classList.toggle("hidden",!1),focusOnCloseButton&&closeButton.focus(),pendingPromise.resolve()}),300),this.dispatchEvent(Drawers.eventTypes.drawerShown)}closeDrawer(){let{focusOnOpenButton:focusOnOpenButton=!0,updatePreferences:updatePreferences=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const pendingPromise=new _pending.default("theme_boost/drawers:close");if(this.dispatchEvent(Drawers.eventTypes.drawerHide,!0).defaultPrevented)return;const closeButton=this.drawerNode.querySelector(SELECTORS_CLOSEBTN);var _jQuery2;(null==closeButton||closeButton.classList.toggle("hidden",!0),closeButton.hasAttribute("data-original-title"))&&(null===(_jQuery2=(0,_jquery.default)(closeButton))||void 0===_jQuery2||_jQuery2.tooltip("hide"));const preference=this.drawerNode.dataset.preference;preference&&updatePreferences&&!isSmall()&&M.util.set_user_preference(preference,!1);const state=this.drawerNode.dataset.state;if(state){document.getElementById("page").classList.remove(state)}Aria.hide(this.drawerNode),this.drawerNode.classList.remove(CLASSES_SHOW),getBackdrop().then((backdrop=>{if(backdrop.hide(),isSmall()){document.getElementById("page").style.overflow="auto"}return backdrop})).catch();let openButton=getDrawerOpenButton(this.drawerNode.id);openButton&&disableButtonTooltip(openButton,!0),setTimeout((()=>{openButton&&focusOnOpenButton&&openButton.focus(),pendingPromise.resolve()}),300),this.dispatchEvent(Drawers.eventTypes.drawerHidden)}toggleVisibility(){this.drawerNode.classList.contains(CLASSES_SHOW)?this.closeDrawer():this.openDrawer()}static closeAllDrawers(){drawerMap.forEach((drawerInstance=>{drawerInstance.closeDrawer()}))}static closeOtherDrawers(comparisonInstance){drawerMap.forEach((drawerInstance=>{drawerInstance!==comparisonInstance&&drawerInstance.closeDrawer()}))}}_exports.default=Drawers,_defineProperty(Drawers,"eventTypes",{drawerShow:"theme_boost/drawers:show",drawerShown:"theme_boost/drawers:shown",drawerHide:"theme_boost/drawers:hide",drawerHidden:"theme_boost/drawers:hidden"});const scrollbarVisible=htmlNode=>htmlNode.scrollHeight>htmlNode.clientHeight,setLastUsedToggle=toggleButton=>{toggleButton.dataset.target&&(document.querySelectorAll("".concat(SELECTORS_BUTTONS,'[data-target="').concat(toggleButton.dataset.target,'"]')).forEach((btn=>{btn.dataset.lastused=!1})),toggleButton.dataset.lastused=!0)};(()=>{const body=document.querySelector("body"),drawerLayout=document.querySelector(SELECTORS_CONTAINER);if(drawerLayout){const drawerRight=document.querySelector(SELECTORS_CONTAINER+" "+CLASSES_TOGGLERIGHT);!scrollbarVisible(drawerLayout)&&drawerRight&&(drawerRight.style.marginRight="0"),drawerLayout.addEventListener("scroll",(()=>{drawerLayout.scrollTop>=window.innerHeight?body.classList.add(CLASSES_SCROLLED):body.classList.remove(CLASSES_SCROLLED)}))}})(),(()=>{document.addEventListener("click",(e=>{const toggleButton=e.target.closest(SELECTORS_TOGGLEBTN);if(toggleButton&&toggleButton.dataset.target){e.preventDefault();const targetDrawer=document.getElementById(toggleButton.dataset.target),drawerInstance=Drawers.getDrawerInstanceForNode(targetDrawer);setLastUsedToggle(toggleButton),drawerInstance.toggleVisibility()}const openDrawerButton=e.target.closest(SELECTORS_OPENBTN);if(openDrawerButton&&openDrawerButton.dataset.target){e.preventDefault();const targetDrawer=document.getElementById(openDrawerButton.dataset.target),drawerInstance=Drawers.getDrawerInstanceForNode(targetDrawer);setLastUsedToggle(toggleButton),drawerInstance.openDrawer()}const closeDrawerButton=e.target.closest(SELECTORS_CLOSEBTN);if(closeDrawerButton&&closeDrawerButton.dataset.target){e.preventDefault();const targetDrawer=document.getElementById(closeDrawerButton.dataset.target);Drawers.getDrawerInstanceForNode(targetDrawer).closeDrawer(),(target=>{const lastUsedButton=document.querySelector("".concat(SELECTORS_BUTTONS,'[data-target="').concat(target,'"][data-lastused="true"'));lastUsedButton&&lastUsedButton.focus()})(closeDrawerButton.dataset.target)}})),document.addEventListener(Drawers.eventTypes.drawerShow,(e=>{getCurrentWidth()>=sizes_large||Drawers.closeOtherDrawers(e.detail.drawerInstance)}));const btnSelector="".concat(SELECTORS_TOGGLEBTN,", ").concat(SELECTORS_OPENBTN,", ").concat(SELECTORS_CLOSEBTN);document.addEventListener("focusout",(e=>{const button=e.target.closest(btnSelector);void 0!==(null==button?void 0:button.dataset.restoreTooltipOnBlur)&&enableButtonTooltip(button)}));window.addEventListener("resize",(0,_utils.debounce)((()=>{if(isSmall()){let anyOpen=!1;drawerMap.forEach((drawerInstance=>{disableDrawerTooltips(drawerInstance.drawerNode),drawerInstance.isOpen&&(drawerInstance.closeOnResize?drawerInstance.closeDrawer():anyOpen=!0)})),anyOpen&&getBackdrop().then((backdrop=>backdrop.show())).catch()}else drawerMap.forEach((drawerInstance=>{var drawerNode;[(drawerNode=drawerInstance.drawerNode).querySelector(SELECTORS_CLOSEBTN),getDrawerOpenButton(drawerNode.id)].forEach((button=>{button&&enableButtonTooltip(button)}))})),getBackdrop().then((backdrop=>backdrop.hide())).catch()}),400))})();return document.querySelectorAll(SELECTORS_DRAWERS).forEach((drawerNode=>Drawers.getDrawerInstanceForNode(drawerNode))),_exports.default})); define("theme_boost/footer-popover",["exports","jquery","./popover"],(function(_exports,_jquery,_popover){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Shows the footer content in a popover. * * @module theme_boost/footer-popover * @copyright 2021 Bas Brands * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),Object.defineProperty(_exports,"Popover",{enumerable:!0,get:function(){return _popover.default}}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_popover=_interopRequireDefault(_popover);const SELECTORS_FOOTERCONTAINER='[data-region="footer-container-popover"]',SELECTORS_FOOTERCONTENT='[data-region="footer-content-popover"]',SELECTORS_FOOTERBUTTON='[data-action="footer-popover"]';let footerIsShown=!1;_exports.init=()=>{const container=document.querySelector(SELECTORS_FOOTERCONTAINER),footerButton=document.querySelector(SELECTORS_FOOTERBUTTON);(0,_jquery.default)(footerButton).popover({content:getFooterContent,container:container,html:!0,placement:"top",customClass:"footer",trigger:"click"}),document.addEventListener("click",(e=>{footerIsShown&&!e.target.closest(SELECTORS_FOOTERCONTAINER)&&(0,_jquery.default)(footerButton).popover("hide")}),!0),document.addEventListener("keydown",(e=>{footerIsShown&&"Escape"===e.key&&((0,_jquery.default)(footerButton).popover("hide"),footerButton.focus())})),document.addEventListener("focus",(e=>{footerIsShown&&!e.target.closest(SELECTORS_FOOTERCONTAINER)&&(0,_jquery.default)(footerButton).popover("hide")}),!0),(0,_jquery.default)(footerButton).on("show.bs.popover",(()=>{footerIsShown=!0})),(0,_jquery.default)(footerButton).on("hide.bs.popover",(()=>{footerIsShown=!1}))};const getFooterContent=()=>document.querySelector(SELECTORS_FOOTERCONTENT).innerHTML})); define("theme_boost/sticky-footer",["exports","core/pending"],(function(_exports,_pending){var obj; /** * Sticky footer module. * * @module theme_boost/sticky-footer * @copyright 2022 Ferran Recio <ferran@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=_exports.enableStickyFooter=_exports.disableStickyFooter=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};const SELECTORS_STICKYFOOTER=".stickyfooter",SELECTORS_PAGE="#page",CLASSES_HASSTICKYFOOTER="hasstickyfooter";let initialized=!1,previousScrollPosition=0;const scrollSpy=()=>{if(document.body.clientWidth>=768)return;let scrollPosition=(()=>{const page=document.querySelector(SELECTORS_PAGE);return page?page.scrollTop:window.pageYOffset})();scrollPosition>previousScrollPosition?disableStickyFooter():enableStickyFooter(),previousScrollPosition=scrollPosition},enableStickyFooter=()=>{const pendingPromise=new _pending.default("theme_boost/sticky-footer:enabling"),footer=document.querySelector(SELECTORS_STICKYFOOTER),page=document.querySelector(SELECTORS_PAGE);footer&&page&&(document.body.classList.add(CLASSES_HASSTICKYFOOTER),page.classList.add(CLASSES_HASSTICKYFOOTER)),setTimeout((()=>pendingPromise.resolve()),1e3)};_exports.enableStickyFooter=enableStickyFooter;const disableStickyFooter=()=>{document.body.classList.remove(CLASSES_HASSTICKYFOOTER);const page=document.querySelector(SELECTORS_PAGE);null==page||page.classList.remove(CLASSES_HASSTICKYFOOTER)};_exports.disableStickyFooter=disableStickyFooter;_exports.init=()=>{var _document$querySelect;if(initialized||document.body.classList.contains("behat-site"))return;initialized=!0,enableStickyFooter();(null!==(_document$querySelect=document.querySelector(SELECTORS_PAGE))&&void 0!==_document$querySelect?_document$querySelect:document.body).addEventListener("scroll",scrollSpy)}})); /** * Theme LearnR - JS code back to top button * * @module theme_learnr/backtotopbutton * @copyright 2022 Alexander Bias, lern.link GmbH <alexander.bias@lernlink.de> * @copyright on behalf of Zurich University of Applied Sciences (ZHAW) * @copyright based on code from theme_boost_campus by Kathrin Osswald. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("theme_learnr/backtotopbutton",["jquery","core/str","core/notification"],(function($,str,Notification){let buttonShown=!1;function initBackToTop(){let stringsPromise=str.get_string("backtotop","theme_learnr");$.when(stringsPromise).then((function(string){return $("#page-footer").after('<button id="back-to-top" class="btn btn-icon bg-secondary icon-no-margin d-print-none"aria-label="'+string+'"><i aria-hidden="true" class="fa fa-chevron-up fa-fw "></i></button>'),$("#page").on("scroll",(function(){$("#page").scrollTop()>220?!1===buttonShown&&$("#back-to-top").fadeIn(300,(function(){buttonShown=!0})):!0===buttonShown&&$("#back-to-top").fadeOut(100,(function(){buttonShown=!1}))})),$("#back-to-top").on("click",(function(event){event.preventDefault(),$("#page").animate({scrollTop:0},500),$("#back-to-top").blur()})),!0})).fail(Notification.exception)}return{init:function(){initBackToTop()}}})); define("theme_learnr/scrollspy",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=()=>{var callback;callback=(()=>{if(document.querySelector("form.editmode-switch-form").addEventListener("click",(()=>{window.sessionStorage.setItem("edittoggled",!0);let viewporttop=document.getElementById("page").scrollTop,closest=null,closestoffset=null;document.querySelectorAll(".section.main").forEach((node=>{let thisoffset=node.offsetTop;closest&&closest.offsetTop&&(closestoffset=closest.offsetTop),(null===closest||Math.abs(thisoffset-viewporttop)<Math.abs(closestoffset-viewporttop))&&(closest=node)})),window.sessionStorage.setItem("closestid",closest.id),window.sessionStorage.setItem("closestdelta",viewporttop-closest.offsetTop)})),window.sessionStorage.getItem("edittoggled")){let closestid=window.sessionStorage.getItem("closestid"),closestdelta=window.sessionStorage.getItem("closestdelta");if(closestid&&closestdelta){let y=document.getElementById(closestid).offsetTop+parseInt(closestdelta);document.getElementById("page").scrollTo(0,y)}window.sessionStorage.removeItem("edittoggled"),window.sessionStorage.removeItem("closestid"),window.sessionStorage.removeItem("closestdelta")}})(),"complete"===document.readyState||"interactive"===document.readyState?setTimeout(callback,1):document.addEventListener("DOMContentLoaded",callback)}})); /** * Theme LearnR - JS code off-canvas * * @module theme_learnr/offcanvas * @copyright 2022 bdecent gmbh <https://bdecent.de> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("theme_learnr/offcanvas",["jquery","theme_boost/drawers","core/modal"],(function($,Drawers,Modal){let modalBackdrop=null;const getDrawerBackdrop=function(){return modalBackdrop||(modalBackdrop=Modal.prototype.getBackdrop().then((backdrop=>(backdrop.getAttachmentPoint().get(0).addEventListener("click",(e=>{e.preventDefault(),Drawers.getDrawerInstanceForNode(document.getElementById("theme_learnr-drawers-offcanvas")).closeDrawer(!1),backdrop.hide()})),backdrop))).catch()),modalBackdrop};return{init:function(){document.addEventListener(Drawers.eventTypes.drawerShown,(function(e){return"theme_learnr-drawers-offcanvas"!=e.target.id?null:(getDrawerBackdrop().then((backdrop=>(backdrop.show(),backdrop))).catch(),!0)})),document.addEventListener(Drawers.eventTypes.drawerHide,(function(e){return"theme_learnr-drawers-offcanvas"!=e.target.id?null:(getDrawerBackdrop().then((backdrop=>(backdrop.hide(),backdrop))).catch(),!0)}))}}})); /** * Theme LearnR - JS code infobanner * * @module theme_learnr/infobanner * @copyright 2022 Alexander Bias, lern.link GmbH <alexander.bias@lernlink.de> * @copyright on behalf of Zurich University of Applied Sciences (ZHAW) * @copyright based on code from theme_boost_campus by Kathrin Osswald. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("theme_learnr/infobanner",["jquery"],(function($){return{init:function(){$(".themeboostunioninfobanner .close").on("click",(function(){var infobannerno=$(this).attr("data-infobanner-no");M.util.set_user_preference("theme_learnr_infobanner"+infobannerno+"_dismissed",!0)}))}}})); /** * JS handling group/grouping toggler for filerenaming * * @module local_assignsubmission_download/filerenaming_grouptoggle * @author Philipp Hager * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("local_assignsubmission_download/filerenaming_grouptoggle",["jquery","core/log"],(function($,log){var instance=new function(){};return instance.initializer=function(){log.info("Initialise filerenaming group taggling ...","local_assignsubmission_download");var coursegroups=$("#id_coursegroup").first();coursegroups&&coursegroups.change(instance,(function(){var success=$(".alert-success");success&&success.remove(),$("#id_coursegrouping").first().prop("value","0")}));var coursegroupings=$("#id_coursegrouping").first();coursegroupings&&coursegroupings.change(instance,(function(){var success=$(".alert-success");success&&success.remove(),$("#id_coursegroup").first().prop("value","0")}))},instance})); /** * JS handling group/grouping toggler for filerenaming * * @module local_assignsubmission_download/filerenaming_groupingtoggle * @author Philipp Hager * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("local_assignsubmission_download/filerenaming_groupingtoggle",["jquery","core/log"],(function($,log){var instance=new function(){};return instance.initializer=function(groupings){log.info("Initialise filerenaming grouping taggling ...","local_assignsubmission_download");var coursegroups=$("#id_coursegroup").first(),coursegroupings=$("#id_coursegrouping").first();coursegroupings&&coursegroupings.change(instance,(function(){var success=$(".alert-success");success&&success.remove();var curgrouping=$(this).children("option:selected").val();coursegroups&&($("#id_coursegroup").empty(),$.each(groupings,(function(groupingid,groupingitem){groupingid==curgrouping&&$.each(groupingitem,(function(i,item){"groups"==i&&$.each(item,(function(unused,ginfo){$("#id_coursegroup").append($("<option>",{value:ginfo.gid,text:ginfo.name}))}))}))})))}))},instance})); /** * JS handling insertion of tags for filerenaming * * @module local_assignsubmission_download/filerenaming_tagsupport * @author Philipp Hager * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("local_assignsubmission_download/filerenaming_tagsupport",["jquery","core/log"],(function($,log){var Tagsupport=function(){};Tagsupport.prototype.add_tag=function(e){e.stopPropagation(),e.preventDefault(),log.info("Add tag...","local_assignsubmission_download");var tag,targetfield=$("input[name=filerenamingpattern]");tag=$(e.target).data("nametag");var content=targetfield.val(),caretPos=targetfield[0].selectionStart;targetfield.val(content.substring(0,caretPos)+tag+content.substring(caretPos)),targetfield.focus();var postpos=caretPos+tag.length;targetfield[0].selectionStart=postpos,targetfield[0].selectionEnd=postpos};var instance=new Tagsupport;return instance.initializer=function(){log.info("Initialise filerenaming tag handling js...","local_assignsubmission_download"),$("[data-nametag]").unbind("click"),$("[data-nametag]").on("click",null,this,this.add_tag),$("[data-nametag]").css("cursor","pointer")},instance})); /** * JS handling of the printpreview form * * @module local_assignsubmission_download/printpreviewer * @author Andreas Krieger * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define("local_assignsubmission_download/printpreviewer",["jquery","core/log"],(function($,log){var Printpreviewer=function(){};Printpreviewer.prototype.change_in_perpage=function(e){e.preventDefault(),e.stopPropagation(),0==$(window.combo[1]).val()?($(window.combo[0]).prop("checked",!0),$(window.combo[1]).prop("disabled",!0)):(window.stdperpage=$(window.combo[1]).val(),$(window.combo[0]).prop("checked",!1),$(window.combo[1]).prop("disabled",!1))},Printpreviewer.prototype.change_in_optimum=function(e){e.preventDefault(),e.stopPropagation(),$(window.combo[0]).prop("checked")?(window.stdperpage=$(window.combo[1]).val(),$(window.combo[1]).val(0),$(window.combo[1]).prop("disabled",!0)):($(window.combo[1]).val(window.stdperpage),$(window.combo[1]).prop("disabled",!1))};var instance=new Printpreviewer;return instance.initializer=function(){if(window.washere)return!0;window.washere=1,log.info("Initialise printpreview handling js...","local_assignsubmission_download");var filterelement=$("#id_filter"),groupelement=$("#id_group"),exportformat=$("#id_exportformat"),selectall=$("#selectall"),select=$("td.cell input[type=checkbox]"),toggleprintsettings=function(exportformat){0==exportformat?($("#id_grpperpage_perpage").prop("disabled",!1),$("#id_grpperpage_optimum").prop("disabled",!1),$("#id_textsize").prop("disabled",!1),$("#id_pageorientation").prop("disabled",!1),$("#id_printheader").prop("disabled",!1)):($("#id_grpperpage_perpage").prop("disabled",!0),$("#id_grpperpage_optimum").prop("disabled",!0),$("#id_textsize").prop("disabled",!0),$("#id_pageorientation").prop("disabled",!0),$("#id_printheader").prop("disabled",!0))};return filterelement&&filterelement.on("change",(function(){$("form.mform").submit()})),groupelement&&groupelement.on("change",(function(){$("form.mform").submit()})),exportformat&&exportformat.on("change",(function(){toggleprintsettings(exportformat.val())})),selectall.prop("checked","checked"),select.prop("checked","checked"),window.combo=new Array,window.combo[0]="input[id=id_grpperpage_optimum]",window.combo[1]="input[id=id_grpperpage_perpage]",window.stdperpage=$(window.combo[1]).val(),$(window.combo[0]).checked?$(window.combo[1]).prop("disabled",!0):$(window.combo[1]).prop("disabled",!1),$(window.combo[1]).change(this.change_in_perpage),$(window.combo[0]).change(this.change_in_optimum),toggleprintsettings(exportformat.val()),!0},instance})); define("paygw_paypal/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * PayPal repository module to encapsulate all of the AJAX requests that can be sent for PayPal. * * @module paygw_paypal/repository * @copyright 2020 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.markTransactionComplete=_exports.getConfigForJs=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.getConfigForJs=(component,paymentArea,itemId)=>{const request={methodname:"paygw_paypal_get_config_for_js",args:{component:component,paymentarea:paymentArea,itemid:itemId}};return _ajax.default.call([request])[0]};_exports.markTransactionComplete=(component,paymentArea,itemId,orderId)=>{const request={methodname:"paygw_paypal_create_transaction_complete",args:{component:component,paymentarea:paymentArea,itemid:itemId,orderid:orderId}};return _ajax.default.call([request])[0]}})); define("paygw_paypal/gateways_modal",["exports","./repository","core/templates","core/truncate","core/modal_factory","core/modal_events","core/str"],(function(_exports,Repository,_templates,_truncate,_modal_factory,_modal_events,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.process=void 0,Repository=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * This module is responsible for PayPal content in the gateways modal. * * @module paygw_paypal/gateway_modal * @copyright 2020 Shamim Rezaie <shamim@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(Repository),_templates=_interopRequireDefault(_templates),_truncate=_interopRequireDefault(_truncate),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events);const showModalWithPlaceholder=async()=>{const modal=await _modal_factory.default.create({body:await _templates.default.render("paygw_paypal/paypal_button_placeholder",{})});return modal.show(),modal};_exports.process=(component,paymentArea,itemId,description)=>Promise.all([showModalWithPlaceholder(),Repository.getConfigForJs(component,paymentArea,itemId)]).then((_ref=>{let[modal,paypalConfig]=_ref;return modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy()})),Promise.all([modal,paypalConfig,switchSdk(paypalConfig.clientid,paypalConfig.currency)])})).then((_ref2=>{let[modal,paypalConfig]=_ref2;return modal.setBody(""),new Promise((resolve=>{window.paypal.Buttons({createOrder:function(data,actions){return actions.order.create({purchase_units:[{amount:{currency_code:paypalConfig.currency_code,value:paypalConfig.cost},description:_truncate.default.truncate(description,{length:127,stripTags:!0})}],application_context:{shipping_preference:"NO_SHIPPING",brand_name:_truncate.default.truncate(paypalConfig.brandname,{length:127,stripTags:!0})}})},onApprove:function(data){modal.getRoot().on(_modal_events.default.outsideClick,(e=>{e.preventDefault()})),modal.setBody((0,_str.get_string)("authorising","paygw_paypal")),Repository.markTransactionComplete(component,paymentArea,itemId,data.orderID).then((res=>(modal.hide(),res))).then(resolve)}}).render(modal.getBody()[0])}))})).then((res=>res.success?Promise.resolve(res.message):Promise.reject(res.message)));const switchSdk=(clientId,currency)=>{const sdkUrl="https://www.paypal.com/sdk/js?client-id=".concat(clientId,"¤cy=").concat(currency);if(switchSdk.currentlyloaded===sdkUrl)return Promise.resolve();if(switchSdk.currentlyloaded){const suspectedScript=document.querySelector('script[src="'.concat(switchSdk.currentlyloaded,'"]'));suspectedScript&&suspectedScript.parentNode.removeChild(suspectedScript)}const script=document.createElement("script");return new Promise((resolve=>{script.readyState?script.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,resolve())}:script.onload=function(){resolve()},script.setAttribute("src",sdkUrl),document.head.appendChild(script),switchSdk.currentlyloaded=sdkUrl}))};switchSdk.currentlyloaded=""})); define("forumreport_summary/filters",["exports","jquery","core/popper","core/custom_interaction_events","forumreport_summary/selectors","core/ajax","core/key_codes","core_form/changechecker"],(function(_exports,_jquery,_popper,_custom_interaction_events,_selectors,_ajax,_key_codes,FormChangeChecker){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Module responsible for handling forum summary report filters. * * @module forumreport_summary/filters * @copyright 2019 Michael Hawkins <michaelh@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_popper=_interopRequireDefault(_popper),_custom_interaction_events=_interopRequireDefault(_custom_interaction_events),_selectors=_interopRequireDefault(_selectors),_ajax=_interopRequireDefault(_ajax),_key_codes=_interopRequireDefault(_key_codes),FormChangeChecker=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(FormChangeChecker);_exports.init=root=>{let jqRoot=(0,_jquery.default)(root);(0,_jquery.default)(document).ready((function(){(0,_jquery.default)(".loading-icon").hide(),(0,_jquery.default)("#summaryreport").removeClass("hidden")}));const generateWithFilters=(event,getparams)=>{let newLink,currentLink=document.forms.filtersform.action;if(event){event.preventDefault();let currentSplit=currentLink.split("?"),currentstring=currentSplit[1],newparamsarray=getparams.split("&"),paramsstring="",paramkeys=[],paramvalues=[];currentstring.split("&").forEach((function(param){let splitparam=param.split("=");paramkeys.push(splitparam[0]),paramvalues.push(splitparam[1])})),newparamsarray.forEach((function(paramstring){let newparam=paramstring.split("="),existingkey=paramkeys.indexOf(newparam[0]);existingkey>-1?paramvalues[existingkey]=newparam[1]:(paramkeys.push(newparam[0]),paramvalues.push(newparam[1]))})),paramkeys.forEach((function(name,key){paramsstring+="&".concat(name,"=").concat(paramvalues[key])})),newLink=currentSplit[0]+"?"+paramsstring.substr(1)}else newLink=currentLink;document.forms.filtersform.action=newLink,document.forms.filtersform.submit()};(0,_jquery.default)(".resettable").on("click","a",(function(event){generateWithFilters(event,event.target.search.substr(1))})),(0,_jquery.default)("thead").on("click","a",(function(event){generateWithFilters(event,event.target.search.substr(1))})),(0,_jquery.default)(".pagination").on("click","a",(function(event){generateWithFilters(event,event.target.search.substr(1))})),document.forms.selectperpage&&(document.forms.selectperpage.onsubmit=event=>{let getparam="perpage="+document.forms.selectperpage.elements.perpage.value;generateWithFilters(event,getparam)});const downloadForm=document.getElementById("summaryreport").querySelector("form.dataformatselector");downloadForm&&(downloadForm.onsubmit=event=>{const downloadType=downloadForm.querySelector("#downloadtype_download").value,getParams="download=".concat(downloadType),prevAction=document.forms.filtersform.action;generateWithFilters(event,getParams),document.forms.filtersform.action=prevAction});const submitWithFilter=containerelement=>{FormChangeChecker.unWatchForm(document.forms.filtersform),(0,_jquery.default)(containerelement).addClass("hidden"),generateWithFilters(!1)},updateCalendarPosition=referenceid=>{let referenceElement=document.querySelector(referenceid),popperContent=document.querySelector(_selectors.default.filters.date.calendar);popperContent.style.removeProperty("z-index"),new _popper.default(referenceElement,popperContent,{placement:"bottom"})},closeOpenFilters=(openFilterButton,openFilter)=>{openFilter.classList.add("hidden"),openFilter.setAttribute("data-openfilter","false"),openFilterButton.classList.add("btn-primary"),openFilterButton.classList.remove("btn-outline-primary"),openFilterButton.setAttribute("aria-expanded",!1)};jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.group.selectall,(function(){root.querySelectorAll(_selectors.default.filters.group.checkbox+":not(:checked)").forEach((function(checkbox){checkbox.checked=!0}))})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.group.clear,(function(){root.querySelectorAll(_selectors.default.filters.group.checkbox+":checked").forEach((function(checkbox){checkbox.checked=!1}))})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.group.trigger,(function(){let referenceElement=root.querySelector(_selectors.default.filters.group.trigger),popperContent=root.querySelector(_selectors.default.filters.group.popover);new _popper.default(referenceElement,popperContent,{placement:"bottom"}),popperContent.classList.remove("hidden"),popperContent.setAttribute("data-openfilter","true"),referenceElement.classList.add("btn-outline-primary"),referenceElement.classList.remove("btn-primary"),referenceElement.setAttribute("aria-expanded",!0);const closeListener=e=>{e.target.id===referenceElement.id||popperContent===e.target.closest('[data-openfilter="true"]')||void 0!==e.keyCode&&e.keyCode!==_key_codes.default.enter&&e.keyCode!==_key_codes.default.space||(closeOpenFilters(referenceElement,popperContent),document.removeEventListener("click",closeListener),document.removeEventListener("keyup",closeListener),document.removeEventListener("keyup",escCloseListener))};document.addEventListener("click",closeListener),document.addEventListener("keyup",closeListener);const escCloseListener=e=>{e.keyCode===_key_codes.default.escape&&(closeOpenFilters(referenceElement,popperContent),document.removeEventListener("keyup",escCloseListener),document.removeEventListener("click",closeListener))};document.addEventListener("keyup",escCloseListener)})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.group.save,(function(){root.querySelectorAll(_selectors.default.filters.group.checkbox).forEach((function(popcheckbox){let filtersform=document.forms.filtersform,saveid=popcheckbox.getAttribute("data-saveid");filtersform.querySelector("#".concat(saveid)).checked=popcheckbox.checked})),submitWithFilter("#filter-groups-popover")})),document.querySelectorAll(_selectors.default.filters.exportlink.link).forEach((function(exportbutton){exportbutton.addEventListener("click",(function(event){document.forms.exportlinkform.action=event.target.dataset.url,document.forms.exportlinkform.submit()}))})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.date.trigger,(function(){let referenceElement=root.querySelector(_selectors.default.filters.date.trigger),popperContent=root.querySelector(_selectors.default.filters.date.popover);new _popper.default(referenceElement,popperContent,{placement:"bottom"}),popperContent.classList.remove("hidden"),popperContent.setAttribute("data-openfilter","true"),popperContent.querySelector('[name="filterdatefrompopover[enabled]"]').focus(),referenceElement.classList.add("btn-outline-primary"),referenceElement.classList.remove("btn-primary"),referenceElement.setAttribute("aria-expanded",!0);const closeListener=e=>{e.target.id===referenceElement.id||popperContent===e.target.closest('[data-openfilter="true"]')||void 0!==e.keyCode&&e.keyCode!==_key_codes.default.enter&&e.keyCode!==_key_codes.default.space||(closeOpenFilters(referenceElement,popperContent),document.removeEventListener("click",closeListener),document.removeEventListener("keyup",closeListener),document.removeEventListener("keyup",escCloseListener))};document.addEventListener("click",closeListener),document.addEventListener("keyup",closeListener);const escCloseListener=e=>{e.keyCode===_key_codes.default.escape&&(closeOpenFilters(referenceElement,popperContent),document.removeEventListener("keyup",escCloseListener),document.removeEventListener("click",closeListener))};document.addEventListener("keyup",escCloseListener)})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.date.save,(function(){let filtersForm=document.forms.filtersform;const datesPopover=root.querySelector(_selectors.default.filters.date.popover),fromEnabled=datesPopover.querySelector('[name="filterdatefrompopover[enabled]"]').checked?1:0,toEnabled=datesPopover.querySelector('[name="filterdatetopopover[enabled]"]').checked?1:0;if(fromEnabled||toEnabled){let args={data:[]};fromEnabled&&args.data.push({key:"from",year:datesPopover.querySelector('[name="filterdatefrompopover[year]"]').value,month:datesPopover.querySelector('[name="filterdatefrompopover[month]"]').value,day:datesPopover.querySelector('[name="filterdatefrompopover[day]"]').value,hour:0,minute:0}),toEnabled&&args.data.push({key:"to",year:datesPopover.querySelector('[name="filterdatetopopover[year]"]').value,month:datesPopover.querySelector('[name="filterdatetopopover[month]"]').value,day:datesPopover.querySelector('[name="filterdatetopopover[day]"]').value,hour:23,minute:59});const request={methodname:"core_calendar_get_timestamps",args:args};_ajax.default.call([request])[0].done((function(result){let fromTimestamp=0,toTimestamp=0;if(result.timestamps.forEach((function(data){"from"===data.key?fromTimestamp=data.timestamp:"to"===data.key&&(toTimestamp=data.timestamp)})),toTimestamp>0&&fromTimestamp>toTimestamp){const warningdiv=document.getElementById("dates-filter-warning");warningdiv.classList.remove("hidden"),warningdiv.classList.add("d-block")}else filtersForm.elements["datefrom[timestamp]"].value=fromTimestamp,filtersForm.elements["datefrom[enabled]"].value=fromEnabled,filtersForm.elements["dateto[timestamp]"].value=toTimestamp,filtersForm.elements["dateto[enabled]"].value=toEnabled,submitWithFilter("#filter-dates-popover")}))}else filtersForm.elements["datefrom[timestamp]"].value=0,filtersForm.elements["datefrom[enabled]"].value=fromEnabled,filtersForm.elements["dateto[timestamp]"].value=0,filtersForm.elements["dateto[enabled]"].value=toEnabled,submitWithFilter("#filter-dates-popover")})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.date.calendariconfrom,(function(){updateCalendarPosition(_selectors.default.filters.date.calendariconfrom)})),jqRoot.on(_custom_interaction_events.default.events.activate,_selectors.default.filters.date.calendariconto,(function(){updateCalendarPosition(_selectors.default.filters.date.calendariconto)}))}})); define("forumreport_summary/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={filters:{group:{checkbox:'[data-region="filter-groups"] input[type="checkbox"]',clear:'[data-region="filter-groups"] .filter-clear',popover:"#filter-groups-popover",save:'[data-region="filter-groups"] .filter-save',selectall:'[data-region="filter-groups"] .select-all',trigger:"#filter-groups-button"},date:{calendar:"#dateselector-calendar-panel",calendariconfrom:"#id_filterdatefrompopover_calendar",calendariconto:"#id_filterdatetopopover_calendar",popover:"#filter-dates-popover",save:'[data-region="filter-dates"] .filter-save',trigger:"#filter-dates-button"},exportlink:{link:"#summaryreport #forumreport_summary_table button.export-link"}}},_exports.default})); define("quizaccess_seb/managetemplates",["jquery","core/ajax","core/str","core/notification"],(function($,ajax,str,notification){var manager={removeTemplate:function(e){e.preventDefault();var targetUrl=$(e.currentTarget).attr("href");str.get_strings([{key:"confirmtemplateremovaltitle",component:"quizaccess_seb"},{key:"confirmtemplateremovalquestion",component:"quizaccess_seb"},{key:"yes",component:"moodle"},{key:"no",component:"moodle"}]).then((function(s){notification.confirm(s[0],s[1],s[2],s[3],(function(){window.location=targetUrl}))})).catch()},setup:function(){$("body").delegate('[data-action="delete"]',"click",manager.removeTemplate)}};return{setup:manager.setup}})); define("quizaccess_seb/validate_quiz_access",["exports","core/ajax","core/config","core/notification","quizaccess_seb/view"],(function(_exports,_ajax,_config,_notification,View){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Validate Safe Exam Browser access keys. * * @module quizaccess_seb/validate_quiz_access * @author Andrew Madden <andrewmadden@catalyst-au.net> * @copyright 2021 Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_config=_interopRequireDefault(_config),_notification=_interopRequireDefault(_notification),View=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(View),window.SafeExamBrowser=window.SafeExamBrowser||null;const safeExamBrowserKeysUpdated=function(cmid){let autoreconfigure=arguments.length>1&&void 0!==arguments[1]&&arguments[1];isQuizAccessValid(cmid).then((response=>(setTimeout(View.clearLoadingAlert,1e3),response.configkey&&response.browserexamkey?View.allowAccess():(!0===autoreconfigure&&!1===response.configkey&&reconfigureSafeExamBrowser(cmid),setTimeout(View.showValidationFailedModal,1e3)),response))).catch((err=>{_notification.default.exception(err)}))},isQuizAccessValid=cmid=>{const request={methodname:"quizaccess_seb_validate_quiz_keys",args:{cmid:cmid,url:window.location.href,configkey:window.SafeExamBrowser.security.configKey,browserexamkey:window.SafeExamBrowser.security.browserExamKey}};return _ajax.default.call([request])[0]},isKeyEmpty=key=>":"===key,reconfigureSafeExamBrowser=cmid=>{const redirecturl=_config.default.wwwroot.replace(/^http/i,"seb")+"/mod/quiz/accessrule/seb/config.php?cmid="+cmid;document.location.replace(redirecturl)};_exports.init=async function(cmid){let autoreconfigure=arguments.length>1&&void 0!==arguments[1]&&arguments[1];null!==window.SafeExamBrowser&&(await View.addLoadingAlert(),isKeyEmpty(window.SafeExamBrowser.security.configKey)&&isKeyEmpty(window.SafeExamBrowser.security.browserExamKey)?window.SafeExamBrowser.security.updateKeys(safeExamBrowserKeysUpdated):safeExamBrowserKeysUpdated(cmid,autoreconfigure))}})); define("quizaccess_seb/view",["exports","core/notification","core/templates","core/str","core/modal_factory"],(function(_exports,_notification,Templates,Str,ModalFactory){var obj; /** * Manage the quiz views. * * @module quizaccess_seb/view * @author Andrew Madden <andrewmadden@catalyst-au.net> * @copyright 2021 Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.showValidationFailedModal=_exports.clearLoadingAlert=_exports.allowAccess=_exports.addLoadingAlert=void 0,_notification=(obj=_notification)&&obj.__esModule?obj:{default:obj},Templates=_interopRequireWildcard(Templates),Str=_interopRequireWildcard(Str),ModalFactory=_interopRequireWildcard(ModalFactory);const SELECTOR_MAIN="#region-main",SELECTOR_LOADING=".seb-loading",TEMPLATE_LOADING="quizaccess_seb/loading";_exports.allowAccess=()=>{window.location.reload()};_exports.addLoadingAlert=()=>Templates.render(TEMPLATE_LOADING,{}).then(((html,js)=>{const alertRegion=window.document.querySelector(SELECTOR_MAIN);return Templates.prependNodeContents(alertRegion,html,js)})).catch(_notification.default.exception);_exports.clearLoadingAlert=()=>{const alert=window.document.querySelector(SELECTOR_LOADING);alert&&Templates.replaceNode(alert,"","")};_exports.showValidationFailedModal=()=>{ModalFactory.create({type:ModalFactory.types.ALERT,title:Str.get_string("sebkeysvalidationfailed","quizaccess_seb"),body:Str.get_string("invalidkeys","quizaccess_seb"),large:!1}).then((modal=>{modal.show()})).fail(_notification.default.exception)}})); define("tiny_accessibilitychecker/colorbase",["exports"],(function(_exports){function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj} /* * @package tiny_accessibilitychecker * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default=class{constructor(){_defineProperty(this,"REGEX_HEX",/^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})(\ufffe)?/),_defineProperty(this,"REGEX_HEX3",/^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})(\ufffe)?/),_defineProperty(this,"REGEX_RGB",/rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/),_defineProperty(this,"TYPES",{HEX:"hex",RGB:"rgb",RGBA:"rgba"}),_defineProperty(this,"KEYWORDS",{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"}),_defineProperty(this,"STR_HEX","#{*}{*}{*}"),_defineProperty(this,"STR_RGB","rgb({*}, {*}, {*})"),_defineProperty(this,"STR_RGBA","rgba({*}, {*}, {*}, {*})"),_defineProperty(this,"toHex",(str=>{var clr=this._convertTo(str,"hex"),isTransparent="transparent"===clr.toLowerCase();return"#"===clr.charAt(0)||isTransparent||(clr="#"+clr),isTransparent?clr.toLowerCase():clr.toUpperCase()})),_defineProperty(this,"toRGB",(str=>this._convertTo(str,"rgb").toLowerCase())),_defineProperty(this,"toRGBA",(str=>this._convertTo(str,"rgba").toLowerCase())),_defineProperty(this,"toArray",(str=>{var regex,arr,length,type=this.findType(str).toUpperCase();return"HEX"===type&&str.length<5&&(type="HEX3"),"A"===type.charAt(type.length-1)&&(type=type.slice(0,-1)),(regex=this._getRightValue("REGEX_"+type))&&(length=(arr=regex.exec(str)||[]).length)&&(arr.shift(),length--,"HEX3"===type&&(arr[0]+=arr[0],arr[1]+=arr[1],arr[2]+=arr[2]),arr[length-1]||(arr[length-1]=1)),arr})),_defineProperty(this,"fromArray",((arr,template)=>{if(arr=arr.concat(),void 0===template)return arr.join(", ");for(template=this._getRightValue("STR_"+template.toUpperCase()),3===arr.length&&4===template.match(/\{\*\}/g).length&&arr.push(1);template.indexOf("{*}")>=0&&arr.length>0;)template=template.replace("{*}",arr.shift());return template})),_defineProperty(this,"findType",(str=>{if(this.KEYWORDS[str])return"keyword";var key,index=str.indexOf("(");return index>0&&(key=str.substr(0,index)),key&&this.TYPES[key.toUpperCase()]?this.TYPES[key.toUpperCase()]:"hex"})),_defineProperty(this,"_getAlpha",(clr=>{var alpha,arr=this.toArray(clr);return arr.length>3&&(alpha=arr.pop()),+alpha||1})),_defineProperty(this,"_keywordToHex",(clr=>{var keyword=this.KEYWORDS[clr];return keyword||keyword})),_defineProperty(this,"_convertTo",((clr,to)=>{if("transparent"===clr)return clr;var needsAlpha,alpha,method,ucTo,from=this.findType(clr),originalTo=to;return"keyword"===from&&(clr=this._keywordToHex(clr),from="hex"),"hex"===from&&clr.length<5&&("#"===clr.charAt(0)&&(clr=clr.substr(1)),clr="#"+clr.charAt(0)+clr.charAt(0)+clr.charAt(1)+clr.charAt(1)+clr.charAt(2)+clr.charAt(2)),from===to||("a"===from.charAt(from.length-1)&&(from=from.slice(0,-1)),(needsAlpha="a"===to.charAt(to.length-1))&&(to=to.slice(0,-1),alpha=this._getAlpha(clr)),ucTo=to.charAt(0).toUpperCase()+to.substr(1).toLowerCase(),(method=window["_"+from+"To"+ucTo])||"rgb"!==from&&"rgb"!==to&&(clr=window["_"+from+"ToRgb"](clr),from="rgb",method=window["_"+from+"To"+ucTo]),method&&(clr=method(clr,needsAlpha)),needsAlpha&&(Array.isArray(clr)||(clr=this.toArray(clr)),clr.push(alpha),clr=this.fromArray(clr,originalTo.toUpperCase()))),clr})),_defineProperty(this,"_hexToRgb",((str,array)=>{var r,g,b;return"#"===str.charAt(0)&&(str=str.substr(1)),r=(str=parseInt(str,16))>>16,g=str>>8&255,b=255&str,array?[r,g,b]:"rgb("+r+", "+g+", "+b+")"})),_defineProperty(this,"_rgbToHex",(str=>{var rgb=this.toArray(str),hex=rgb[2]|rgb[1]<<8|rgb[0]<<16;for(hex=(+hex).toString(16);hex.length<6;)hex="0"+hex;return"#"+hex})),_defineProperty(this,"_getRightValue",(string=>{let regex=null;return"REGEX_RGB"===string?regex=this.REGEX_RGB:"REGEX_HEX"===string?regex=this.REGEX_HEX:"REGEX_HEX3"===string?regex=this.REGEX_HEX3:"STR_HEX"===string?regex=this.STR_HEX:"STR_RGB"===string?regex=this.STR_RGB:"STR_RGBA"===string&&(regex=this.STR_RGBA),regex}))}},_exports.default})); define("tiny_accessibilitychecker/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_accessibilitychecker/plugin",component:"tiny_accessibilitychecker",accessbilityButtonName:"tiny_accessibilitychecker",icon:"accessibility-check"},_exports.default})); define("tiny_accessibilitychecker/configuration",["exports","./common","editor_tiny/utils"],(function(_exports,_common,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0;_exports.configure=instanceConfig=>({menu:(0,_utils.addMenubarItem)(instanceConfig.menu,"tools",_common.accessbilityButtonName)})})); define("tiny_accessibilitychecker/plugin",["exports","editor_tiny/loader","editor_tiny/utils","./common","./commands","./configuration"],(function(_exports,_loader,_utils,_common,Commands,Configuration){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny Media Manager plugin for Moodle. * * @module tiny_accessibilitychecker/plugin * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,Commands=_interopRequireWildcard(Commands),Configuration=_interopRequireWildcard(Configuration);var _default=new Promise((async resolve=>{const[tinyMCE,setupCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),Commands.getSetup(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(setupCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_accessibilitychecker/checker",["exports","core/templates","core/str","./common","core/modal_factory","core/modal_events","./colorbase","editor_tiny/options"],(function(_exports,_templates,_str,_common,Modal,ModalEvents,_colorbase,_options){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /* * @package tiny_accessibilitychecker * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=_interopRequireDefault(_templates),Modal=_interopRequireWildcard(Modal),ModalEvents=_interopRequireWildcard(ModalEvents),_colorbase=_interopRequireDefault(_colorbase);return _exports.default=class{constructor(editor){this.editor=editor,this.colorBase=new _colorbase.default,this.modal=null,this.placeholderSelectors=null;const placeholders=(0,_options.getPlaceholderSelectors)(this.editor);placeholders.length&&(this.placeholderSelectors=placeholders.join(", "))}destroy(){delete this.editor,delete this.colorBase,this.modal.destroy(),delete this.modal}async displayDialogue(){this.modal=await Modal.create({type:Modal.types.DEFAULT,large:!0,title:(0,_str.get_string)("pluginname",_common.component),body:this.getDialogueContent()}),this.modal.getRoot().on(ModalEvents.hidden,(()=>this.destroy())),this.modal.getRoot()[0].addEventListener("click",(event=>{const faultLink=event.target.closest('[data-action="highlightfault"]');if(!faultLink)return;event.preventDefault();const nodeName=faultLink.dataset.nodeName;let selectedNode=null;if(nodeName)if(nodeName.includes(",")||"body"===nodeName)selectedNode=this.editor.dom.select("body")[0];else{var _faultLink$dataset$no;const nodeIndex=null!==(_faultLink$dataset$no=faultLink.dataset.nodeIndex)&&void 0!==_faultLink$dataset$no?_faultLink$dataset$no:0;selectedNode=this.editor.dom.select(nodeName)[nodeIndex]}selectedNode&&"BODY"!==selectedNode.nodeName.toUpperCase()&&this.selectAndScroll(selectedNode),this.modal.hide()})),this.modal.show()}async getAllWarningStrings(){const keys=["emptytext","entiredocument","imagesmissingalt","needsmorecontrast","needsmoreheadings","tablesmissingcaption","tablesmissingheaders","tableswithmergedcells"],stringValues=await(0,_str.get_strings)(keys.map((key=>({key:key,component:_common.component}))));return new Map(keys.map(((key,index)=>[key,stringValues[index]])))}async getDialogueContent(){const langStrings=await this.getAllWarningStrings(),warnings=this.getWarnings().map((warning=>(warning.description&&("langstring"===warning.description.type?warning.description=langStrings.get(warning.description.value):warning.description=warning.description.value),warning.nodeData=warning.nodeData.map((problemNode=>(problemNode.text&&("langstring"===problemNode.text.type?problemNode.text=langStrings.get(problemNode.text.value):problemNode.text=problemNode.text.value),problemNode))),warning)));return _templates.default.render("tiny_accessibilitychecker/warning_content",{warnings:warnings})}selectAndScroll(node){this.editor.selection.select(node).scrollIntoView({behavior:"smooth",block:"nearest"})}getWarnings(){const warnings=[];return warnings.push(this.createWarnings("imagesmissingalt",this.checkImage(),!0)),warnings.push(this.createWarnings("needsmorecontrast",this.checkOtherElements(),!1)),this.editor.getContent({format:"text"}).length>1e3&&this.editor.dom.select("h3,h4,h5").length<1&&warnings.push(this.createWarnings("needsmoreheadings",[this.editor],!1)),warnings.push(this.createWarnings("tablesmissingcaption",this.checkTableCaption(),!1)),warnings.push(this.createWarnings("tableswithmergedcells",this.checkTableMergedCells(),!1)),warnings.push(this.createWarnings("tablesmissingheaders",this.checkTableHeaders(),!1)),warnings.filter((warning=>warning.nodeData.length>0))}createWarnings(description,nodes,isImageType){const getTextValue=node=>{if(node===this.editor)return{type:"langstring",value:"entiredocument"};const emptyStringValue={type:"langstring",value:"emptytext"};if("innerText"in node){const value=node.innerText.trim();return value.length?{type:"raw",value:value}:emptyStringValue}if("textContent"in node){const value=node.textContent.trim();return value.length?{type:"raw",value:value}:emptyStringValue}return{type:"raw",value:node.nodeName}},getEventualNode=node=>{if(node!==this.editor)return node;const childNodes=node.dom.select("body")[0].childNodes;return childNodes.length?document.body:childNodes},warning={description:{type:"langstring",value:description},nodeData:[]};return warning.nodeData=[...nodes].filter((node=>node!==this.editor&&this.placeholderSelectors?!1===node.matches(this.placeholderSelectors):node)).map((node=>{const describedNode=getEventualNode(node),nodeIndex=this.editor.dom.select(describedNode.nodeName).indexOf(describedNode),warning={src:null,text:null,nodeName:describedNode.nodeName,nodeIndex:nodeIndex};return isImageType?warning.src=node.getAttribute("src"):warning.text=getTextValue(node),warning})),warning}checkImage(){const problemNodes=[];return this.editor.dom.select("img").forEach((img=>{img.getAttribute("alt")||"presentation"===img.getAttribute("role")||problemNodes.push(img)})),problemNodes}checkTableCaption(){const problemNodes=[];return this.editor.dom.select("table").forEach((table=>{const caption=table.querySelector("caption");null!=caption&&caption.textContent.trim()||problemNodes.push(table)})),problemNodes}checkOtherElements(){const problemNodes=[];return this.editor.dom.select("body *").filter((node=>node.hasChildNodes()&&null!==node.childNodes[0].nodeValue)).forEach((node=>{const foreground=this.colorBase.fromArray(this.getComputedBackgroundColor(node,window.getComputedStyle(node,null).getPropertyValue("color")),this.colorBase.TYPES.RGBA),background=this.colorBase.fromArray(this.getComputedBackgroundColor(node),this.colorBase.TYPES.RGBA),lum1=this.getLuminanceFromCssColor(foreground),lum2=this.getLuminanceFromCssColor(background),ratio=((lum1,lum2)=>lum1>lum2?(lum1+.05)/(lum2+.05):(lum2+.05)/(lum1+.05))(lum1,lum2);ratio<=4.5&&(window.console.log("\n Contrast ratio is too low: ".concat(ratio,"\n Colour 1: ").concat(foreground,"\n Colour 2: ").concat(background,"\n Luminance 1: ").concat(lum1,"\n Luminance 2: ").concat(lum2,"\n ")),problemNodes.find((existingProblemNode=>existingProblemNode.contains(node)))||problemNodes.push(node))})),problemNodes}checkTableMergedCells(){const problemNodes=[];return this.editor.dom.select("table").forEach((table=>{table.querySelectorAll("[colspan], [rowspan]").length&&problemNodes.push(table)})),problemNodes}checkTableHeaders(){const problemNodes=[];return this.editor.dom.select("table").forEach((table=>{if(table.querySelector("tr").querySelector("td")){[...table.querySelectorAll("tr")].some((row=>{const header=row.querySelector("th");return!header||!header.textContent.trim()}))&&problemNodes.push(table)}else[...table.querySelectorAll("tr th")].some((header=>!header.textContent.trim()))&&problemNodes.push(table)})),problemNodes}getLuminanceFromCssColor(colortext){"transparent"===colortext&&(colortext="#ffffff");const color=this.colorBase.toArray(this.colorBase.toRGB(colortext)),part1=a=>((a=parseInt(a,10)/255)<=.03928?a/=12.92:a=Math.pow((a+.055)/1.055,2.4),a);return.2126*part1(color[0])+.7152*part1(color[1])+.0722*part1(color[2])}getComputedBackgroundColor(node,color){if(!node.parentNode)return this.colorBase.toArray("rgba(255, 255, 255, 1)");"rgba(0, 0, 0, 0)"!==(color=color||window.getComputedStyle(node,null).getPropertyValue("background-color")).toLowerCase()&&"transparent"!==color.toLowerCase()||(color="rgba(1, 1, 1, 0)");const colorParts=this.colorBase.toArray(color),alpha=colorParts[3];if(1===alpha)return colorParts;const parentColor=this.getComputedBackgroundColor(node.parentNode);return[(1-alpha)*parentColor[0]+alpha*colorParts[0],(1-alpha)*parentColor[1]+alpha*colorParts[1],(1-alpha)*parentColor[2]+alpha*colorParts[2],1]}},_exports.default})); define("tiny_accessibilitychecker/commands",["exports","core/str","./common","./checker"],(function(_exports,_str,_common,_checker){var obj; /** * Tiny Media Manager commands. * * @module tiny_accessibilitychecker/commands * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0,_checker=(obj=_checker)&&obj.__esModule?obj:{default:obj};_exports.getSetup=async()=>{const[buttonTooltip]=await Promise.all([(0,_str.get_string)("pluginname",_common.component)]);return editor=>{editor.ui.registry.addButton(_common.accessbilityButtonName,{icon:_common.icon,tooltip:buttonTooltip,onAction:()=>{new _checker.default(editor).displayDialogue()}}),editor.ui.registry.addMenuItem(_common.accessbilityButtonName,{icon:_common.icon,text:buttonTooltip,onAction:()=>{new _checker.default(editor).displayDialogue()}})}}})); define("tiny_autosave/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={component:"tiny_autosave",pluginName:"tiny_autosave/plugin",getLogSource:editor=>"tiny_autosave/".concat(editor.id)},_exports.default})); define("tiny_autosave/plugin",["exports","editor_tiny/loader","editor_tiny/utils","./common","./options","./autosaver"],(function(_exports,_loader,_utils,_common,Options,Autosaver){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny Autosave plugin for Moodle. * * @module tiny_autosave/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,Options=_interopRequireWildcard(Options),Autosaver=_interopRequireWildcard(Autosaver);var _default=new Promise((async resolve=>{const[tinyMCE,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add(_common.pluginName,(editor=>(Options.register(editor),Autosaver.register(editor),pluginMetadata))),resolve(_common.pluginName)}));return _exports.default=_default,_exports.default})); define("tiny_autosave/repository",["exports","core/ajax","core/config","./options","core/pending","editor_tiny/utils"],(function(_exports,_ajax,config,Options,_pending,_utils){var obj;function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Repository helper for the Moodle Tiny Autosave plugin. * * @module tiny_autosave/repository * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.updateAutosaveSession=_exports.resumeAutosaveSession=_exports.removeAutosaveSession=void 0,config=_interopRequireWildcard(config),Options=_interopRequireWildcard(Options),_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};const fetchOne=(methodname,args)=>(0,_ajax.call)([{methodname:methodname,args:args}])[0];_exports.resumeAutosaveSession=editor=>{if(!(0,_utils.ensureEditorIsValid)(editor))return Promise.reject("Invalid editor");const pendingPromise=new _pending.default("tiny_autosave/repository:resumeAutosaveSession");return fetchOne("tiny_autosave_resume_session",{contextid:Options.getContextId(editor),pagehash:Options.getPageHash(editor),pageinstance:Options.getPageInstance(editor),elementid:editor.targetElm.id,draftid:Options.getDraftItemId(editor)}).then((result=>(pendingPromise.resolve(),result)))};_exports.updateAutosaveSession=editor=>{if(!(0,_utils.ensureEditorIsValid)(editor))return Promise.reject("Invalid editor");if(Options.hasAutosaveHasReset(editor))return Promise.reject("Skipping store of autosave content - content has been reset");const pendingPromise=new _pending.default("tiny_autosave/repository:updateAutosaveSession");return fetchOne("tiny_autosave_update_session",{contextid:Options.getContextId(editor),pagehash:Options.getPageHash(editor),pageinstance:Options.getPageInstance(editor),elementid:editor.targetElm.id,drafttext:editor.getContent()}).then((result=>(pendingPromise.resolve(),result)))};_exports.removeAutosaveSession=editor=>{if(!(0,_utils.ensureEditorIsValid)(editor))throw new Error("Invalid editor");Options.setAutosaveHasReset(editor);const requestUrl=new URL("".concat(config.wwwroot,"/lib/ajax/service.php"));requestUrl.searchParams.set("sesskey",config.sesskey);const args={contextid:Options.getContextId(editor),pagehash:Options.getPageHash(editor),pageinstance:Options.getPageInstance(editor),elementid:editor.targetElm.id};navigator.sendBeacon(requestUrl,JSON.stringify([{index:0,methodname:"tiny_autosave_reset_session",args:args}]))}})); define("tiny_autosave/autosaver",["exports","./options","./storage","core/log","./common"],(function(_exports,Options,Storage,_log,_common){var obj;function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Storage helper for the Moodle Tiny Autosave plugin. * * @module tiny_autosave/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=void 0,Options=_interopRequireWildcard(Options),Storage=_interopRequireWildcard(Storage),_log=(obj=_log)&&obj.__esModule?obj:{default:obj};_exports.register=editor=>{const undoHandler=()=>{editor.undoManager.hasUndo()?Storage.saveDraft(editor):_log.default.debug("Ignoring undo event as there is no undo history",(0,_common.getLogSource)(editor))},visibilityChangedHandler=()=>{"hidden"===document.visibilityState&&Options.isInitialised(editor)&&Storage.saveDraft(editor)};document.addEventListener("visibilitychange",visibilityChangedHandler),editor.on("submit",(()=>{document.removeEventListener("visibilitychange",visibilityChangedHandler),Storage.removeAutosaveSession(editor)})),editor.on("init",(()=>{editor.on("AddUndo",undoHandler),editor.dom.isEmpty(editor.getBody())?(_log.default.info("Attempting to restore draft",(0,_common.getLogSource)(editor)),Storage.restoreDraft(editor)):(_log.default.warn("Skipping draft restoration. The editor is not empty.",(0,_common.getLogSource)(editor)),Options.markInitialised(editor))}))}})); define("tiny_autosave/options",["exports","./common","editor_tiny/options","editor_tiny/utils"],(function(_exports,_common,_options,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getBackoffTime=void 0,Object.defineProperty(_exports,"getContextId",{enumerable:!0,get:function(){return _options.getContextId}}),Object.defineProperty(_exports,"getDraftItemId",{enumerable:!0,get:function(){return _options.getDraftItemId}}),_exports.setAutosaveHasReset=_exports.register=_exports.markInitialised=_exports.isInitialised=_exports.hasAutosaveHasReset=_exports.getPageInstance=_exports.getPageHash=void 0; /** * Options helper for the Moodle Tiny Autosave plugin. * * @module tiny_autosave/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const initialisedOptionName=(0,_options.getPluginOptionName)(_common.pluginName,"initialised"),pageHashName=(0,_options.getPluginOptionName)(_common.pluginName,"pagehash"),pageInstanceName=(0,_options.getPluginOptionName)(_common.pluginName,"pageinstance"),backoffTime=(0,_options.getPluginOptionName)(_common.pluginName,"backoffTime"),autosaveHasReset=(0,_options.getPluginOptionName)(_common.pluginName,"autosaveHasReset");_exports.register=editor=>{const registerOption=editor.options.register;registerOption(initialisedOptionName,{processor:"boolean",default:!1}),registerOption(pageHashName,{processor:"string",default:""}),registerOption(pageInstanceName,{processor:"string",default:""}),registerOption(pageInstanceName,{processor:"string",default:""}),registerOption(backoffTime,{processor:"number",default:500}),registerOption(autosaveHasReset,{processor:"boolean",default:!1})};_exports.isInitialised=editor=>!!(0,_utils.ensureEditorIsValid)(editor)&&editor.options.get(initialisedOptionName);_exports.markInitialised=editor=>editor.options.set(initialisedOptionName,!0);_exports.getPageHash=editor=>editor.options.get(pageHashName);_exports.getPageInstance=editor=>editor.options.get(pageInstanceName);_exports.getBackoffTime=editor=>editor.options.get(backoffTime);_exports.setAutosaveHasReset=editor=>editor.options.set(autosaveHasReset,!0);_exports.hasAutosaveHasReset=editor=>editor.options.get(autosaveHasReset)})); define("tiny_autosave/storage",["exports","./repository","core/pending","./options","core/log","./common"],(function(_exports,Repository,_pending,_options,_log,_common){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.saveDraft=_exports.restoreDraft=_exports.removeAutosaveSession=void 0,Repository=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Storage helper for the Moodle Tiny Autosave plugin. * * @module tiny_autosave/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(Repository),_pending=_interopRequireDefault(_pending),_log=_interopRequireDefault(_log);const saveDebounceMap=new Map;_exports.restoreDraft=async editor=>{const pendingPromise=new _pending.default("tiny_autosave/restoreDraft");try{const session=await Repository.resumeAutosaveSession(editor);session&&session.drafttext&&editor.undoManager.ignore((()=>{editor.setContent(session.drafttext),editor.save()}))}catch(error){_log.default.warn("Failed to restore draft: ".concat(error),(0,_common.getLogSource)(editor))}(0,_options.markInitialised)(editor),pendingPromise.resolve()};_exports.saveDraft=editor=>{const timerId=saveDebounceMap.get(editor);timerId&&clearTimeout(timerId),saveDebounceMap.set(editor,setTimeout((()=>{_log.default.debug("Saving draft",(0,_common.getLogSource)(editor)),Repository.updateAutosaveSession(editor).catch((error=>window.console.warn(error)))}),(0,_options.getBackoffTime)(editor)))};_exports.removeAutosaveSession=editor=>{_log.default.debug("Removing Autosave session",(0,_common.getLogSource)(editor)),Repository.removeAutosaveSession(editor)}})); define("tiny_equation/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_equation/plugin",component:"tiny_equation",buttonName:"tiny_equation",icon:"tiny_equation"},_exports.default})); define("tiny_equation/configuration",["exports","tiny_equation/common","editor_tiny/utils"],(function(_exports,_common,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0;_exports.configure=instanceConfig=>{return{menu:(0,_utils.addMenubarItem)(instanceConfig.menu,"insert",_common.component),toolbar:(toolbar=instanceConfig.toolbar,(0,_utils.addToolbarSection)(toolbar,"advanced","lists",!0),(0,_utils.addToolbarButton)(toolbar,"advanced",_common.component))};var toolbar}})); define("tiny_equation/equation",["exports","tiny_equation/selectors"],(function(_exports,_selectors){var obj; /** * Equation helper for Tiny Equation plugin. * * @module tiny_equation/equation * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setEquation=_exports.getSourceEquation=_exports.getSelectedEquation=_exports.getCurrentEquationData=void 0,_selectors=(obj=_selectors)&&obj.__esModule?obj:{default:obj};let sourceEquation=null;const getSourceEquation=()=>sourceEquation;_exports.getSourceEquation=getSourceEquation;const getSelectedEquation=editor=>{const currentSelection=editor.selection.getSel();if(!currentSelection)return!1;const textSelection=editor.selection.getNode().textContent,currentCaretPos=currentSelection.focusOffset;let returnValue=!1;return _selectors.default.equationPatterns.forEach((pattern=>{const regexPattern=new RegExp(pattern.source,"g");[...textSelection.matchAll(regexPattern)].forEach((matches=>{const match=matches[0];let startIndex=0;const startOuter=textSelection.indexOf(match,startIndex),endOuter=startOuter+match.length,innerMatch=match.match(pattern);if(innerMatch&&innerMatch.length){const startInner=textSelection.indexOf(innerMatch[1],startOuter),endInner=startInner+innerMatch[1].length;if(currentCaretPos>=startOuter&¤tCaretPos<=endOuter)return returnValue=innerMatch[1],void(sourceEquation={startInnerPosition:startInner,endInnerPosition:endInner,innerMatch:innerMatch})}startIndex=endOuter}))})),!1!==returnValue?returnValue=returnValue.trim():sourceEquation=null,returnValue};_exports.getSelectedEquation=getSelectedEquation;_exports.getCurrentEquationData=editor=>{let properties={};const equation=getSelectedEquation(editor);return equation&&(properties.equation=equation),properties};_exports.setEquation=(currentForm,editor)=>{const input=currentForm.querySelector(_selectors.default.elements.equationTextArea),sourceEquation=getSourceEquation();let value=input.value;if(""!==value)if(sourceEquation){const selectedNode=editor.selection.getNode(),text=selectedNode.textContent;value=" "+value+" ",selectedNode.textContent=text.slice(0,sourceEquation.startInnerPosition)+value+text.slice(sourceEquation.endInnerPosition)}else value=_selectors.default.delimiters.start+" "+value+" "+_selectors.default.delimiters.end,editor.insertContent(value)}})); define("tiny_equation/options",["exports","editor_tiny/options","tiny_equation/common"],(function(_exports,_options,_common){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=_exports.isTexFilterActive=_exports.getTexDocsUrl=_exports.getLibraries=_exports.getContextId=void 0; /** * Options helper for Tiny Equation plugin. * * @module tiny_equation/options * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const librariesName=(0,_options.getPluginOptionName)(_common.pluginName,"libraries"),texFilterName=(0,_options.getPluginOptionName)(_common.pluginName,"texfilter"),contextIdName=(0,_options.getPluginOptionName)(_common.pluginName,"contextid"),texDocsUrlName=(0,_options.getPluginOptionName)(_common.pluginName,"texdocsurl");_exports.register=editor=>{const registerOption=editor.options.register;registerOption(librariesName,{processor:"array",default:[]}),registerOption(texFilterName,{processor:"boolean",default:!1}),registerOption(contextIdName,{processor:"number",default:0}),registerOption(texDocsUrlName,{processor:"string",default:""})};_exports.getLibraries=editor=>editor.options.get(librariesName);_exports.isTexFilterActive=editor=>editor.options.get(texFilterName);_exports.getContextId=editor=>editor.options.get(contextIdName);_exports.getTexDocsUrl=editor=>editor.options.get(texDocsUrlName)})); define("tiny_equation/plugin",["exports","editor_tiny/loader","editor_tiny/utils","tiny_equation/common","tiny_equation/commands","tiny_equation/configuration","tiny_equation/options"],(function(_exports,_loader,_utils,_common,Commands,Configuration,Options){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny Equation plugin for Moodle. * * @module tiny_equation/plugin * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,Commands=_interopRequireWildcard(Commands),Configuration=_interopRequireWildcard(Configuration),Options=_interopRequireWildcard(Options);var _default=new Promise((async resolve=>{const[tinyMCE,setupCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),Commands.getSetup(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(Options.register(editor),setupCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_equation/repository",["exports","core/ajax"],(function(_exports,_ajax){var obj; /** * A javascript module to handle TinyMCE Equation ajax actions. * * @module tiny_equation/repository * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.filterEquation=void 0,_ajax=(obj=_ajax)&&obj.__esModule?obj:{default:obj};_exports.filterEquation=(contextId,content)=>{const request={methodname:"tiny_equation_filter",args:{contextid:contextId,content:content}};return _ajax.default.call([request])[0]}})); define("tiny_equation/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={equationPatterns:[/\$\$([\S\s]+?)\$\$/,/\\\(([\S\s]+?)\\\)/,/\\\[([\S\s]+?)\\\]/,/\[tex\]([\S\s]+?)\[\/tex\]/],delimiters:{start:"\\(",end:"\\)"},cursorLatex:"\\Downarrow ",actions:{submit:'[data-action="save"]'},elements:{form:"form",library:".tiny_equation_library",libraryItem:".tiny_equation_library button",equationTextArea:".tiny_equation_equation",preview:".tiny_equation_preview"}},_exports.default})); define("tiny_equation/ui",["exports","tiny_equation/modal","core/modal_factory","core/modal_events","tiny_equation/options","core/event","tiny_equation/repository","core/notification","core/utils","tiny_equation/selectors","tiny_equation/equation"],(function(_exports,_modal,_modal_factory,_modal_events,_options,_event,TinyEquationRepository,_notification,_utils,_selectors,_equation){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Tiny Equation UI. * * @module tiny_equation/ui * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */let currentForm;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.handleAction=void 0,_modal=_interopRequireDefault(_modal),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),TinyEquationRepository=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(TinyEquationRepository),_selectors=_interopRequireDefault(_selectors);let lastCursorPos=0;_exports.handleAction=editor=>{displayDialogue(editor)};const displayDialogue=async editor=>{let data={};const currentEquationData=(0,_equation.getCurrentEquationData)(editor);currentEquationData&&Object.assign(data,currentEquationData);const modalPromises=await _modal_factory.default.create({type:_modal.default.TYPE,templateContext:getTemplateContext(editor,data),large:!0});modalPromises.show();const $root=await modalPromises.getRoot(),root=$root[0];currentForm=root.querySelector(_selectors.default.elements.form),$root.on(_modal_events.default.hidden,(()=>{modalPromises.destroy()})),$root.on(_modal_events.default.shown,(()=>{const library=root.querySelector(_selectors.default.elements.library);TinyEquationRepository.filterEquation(1,library.innerHTML).then((async data=>(library.innerHTML=data.content,updatePreview(),notifyFilter(library),data))).catch(_notification.exception)})),root.addEventListener("click",(e=>{const libraryItem=e.target.closest(_selectors.default.elements.libraryItem),submitAction=e.target.closest(_selectors.default.actions.submit),textArea=e.target.closest(".tiny_equation_equation");libraryItem&&(e.preventDefault(),selectLibraryItem(libraryItem)),submitAction&&(e.preventDefault(),(0,_equation.setEquation)(currentForm,editor),modalPromises.destroy()),textArea&&(0,_utils.debounce)(updatePreview(),500)})),root.addEventListener("keyup",(e=>{e.target.closest(_selectors.default.elements.equationTextArea)&&(0,_utils.debounce)(updatePreview(),500)})),root.addEventListener("keydown",(e=>{e.target.closest(_selectors.default.elements.libraryItem)&&(37!=e.keyCode&&39!=e.keyCode||groupNavigation(e))}))},getTemplateContext=(editor,data)=>{const libraries=(0,_options.getLibraries)(editor),texDocsUrl=(0,_options.getTexDocsUrl)(editor);return Object.assign({},{elementid:editor.id,libraries:libraries,texdocsurl:texDocsUrl,delimiters:_selectors.default.delimiters},data)},selectLibraryItem=libraryItem=>{const tex=libraryItem.getAttribute("data-tex"),input=currentForm.querySelector(_selectors.default.elements.equationTextArea);let oldValue,newValue,focusPoint=0;oldValue=input.value,newValue=oldValue.substring(0,lastCursorPos)," "!==newValue.charAt(newValue.length-1)&&(newValue+=" "),newValue+=tex,focusPoint=newValue.length," "!==oldValue.charAt(lastCursorPos)&&(newValue+=" "),newValue+=oldValue.substring(lastCursorPos,oldValue.length),input.value=newValue,input.focus(),input.selectionStart=input.selectionEnd=focusPoint,updatePreview()},updatePreview=()=>{const textarea=currentForm.querySelector(_selectors.default.elements.equationTextArea),preview=currentForm.querySelector(_selectors.default.elements.preview),cursorLatex=_selectors.default.cursorLatex,isChar=/[a-zA-Z{]/;let currentPos=textarea.selectionStart,equation=textarea.value;for(currentPos||(currentPos=0),(0,_equation.getSourceEquation)()&&(currentPos=equation.length);"\\"===equation.charAt(currentPos)&¤tPos>=0;)currentPos-=1;if(0!==currentPos&&"{"!=equation.charAt(currentPos-1))for(;isChar.test(equation.charAt(currentPos))&¤tPos<equation.length&&isChar.test(equation.charAt(currentPos-1));)currentPos+=1;lastCursorPos=currentPos,equation=""+equation.substring(0,currentPos)+cursorLatex+equation.substring(currentPos),equation=_selectors.default.delimiters.start+" "+equation+" "+_selectors.default.delimiters.end,TinyEquationRepository.filterEquation(1,equation).then((data=>(preview.innerHTML=data.content,notifyFilter(preview),data))).catch(_notification.exception)},notifyFilter=element=>{(0,_event.notifyFilterContentUpdated)(element)},groupNavigation=e=>{e.preventDefault();const current=e.target.closest(_selectors.default.elements.libraryItem),parent=current.parentNode,buttons=Array.prototype.slice.call(parent.querySelectorAll(_selectors.default.elements.libraryItem)),direction=37!==e.keyCode?1:-1;let nextButton,index=buttons.indexOf(current);index<0&&(index=0),index+=direction,index<0?index=buttons.length-1:index>=buttons.length&&(index=0),nextButton=buttons[index],nextButton.focus()}})); define("tiny_equation/commands",["exports","editor_tiny/utils","core/str","tiny_equation/common","tiny_equation/ui","tiny_equation/equation","tiny_equation/options"],(function(_exports,_utils,_str,_common,_ui,_equation,_options){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0;_exports.getSetup=async()=>{const[buttonText,buttonImage]=await Promise.all([(0,_str.get_string)("buttontitle",_common.component),(0,_utils.getButtonImage)("icon",_common.component)]);return editor=>{(0,_options.isTexFilterActive)(editor)&&(editor.ui.registry.addIcon(_common.icon,buttonImage.html),editor.ui.registry.addToggleButton(_common.buttonName,{icon:_common.icon,tooltip:buttonText,onAction:()=>{(0,_ui.handleAction)(editor)},onSetup:api=>{editor.on("NodeChange",(()=>{const result=(0,_equation.getSelectedEquation)(editor);api.setActive(result)}))}}),editor.ui.registry.addMenuItem(_common.buttonName,{icon:_common.icon,text:buttonText,onAction:()=>(0,_ui.handleAction)(editor)}))}}})); define("tiny_equation/modal",["exports","core/modal","core/modal_registry"],(function(_exports,_modal,_modal_registry){var _class;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);const EquationModal=(_defineProperty(_class=class extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}},"TYPE","tiny_equation/modal"),_defineProperty(_class,"TEMPLATE","tiny_equation/modal"),_class);_modal_registry.default.register(EquationModal.TYPE,EquationModal,EquationModal.TEMPLATE);var _default=EquationModal;return _exports.default=_default,_exports.default})); define("tiny_h5p/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_h5p/plugin",component:"tiny_h5p",buttonName:"tiny_h5p",icon:"tiny_h5p"},_exports.default})); define("tiny_h5p/configuration",["exports","./common","editor_tiny/utils"],(function(_exports,_common,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0;_exports.configure=instanceConfig=>({toolbar:(0,_utils.addToolbarButton)(instanceConfig.toolbar,"content",_common.component),menu:(0,_utils.addMenubarItem)(instanceConfig.menu,"insert",_common.component)})})); define("tiny_h5p/filtercontent",["exports","editor_tiny/options"],(function(_exports,_options){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setup=void 0;_exports.setup=async editor=>{const classSelector=".".concat("h5p-placeholder");(0,_options.registerPlaceholderSelectors)(editor,[classSelector]),editor.on("PreInit",(()=>{editor.formatter.register("h5p",{inline:"div",classes:"h5p-placeholder"})})),editor.on("SetContent",(()=>{editor.getBody().querySelectorAll("".concat(classSelector,":not([contenteditable])")).forEach((node=>{node.contentEditable=!1}))}))}})); define("tiny_h5p/options",["exports","editor_tiny/options","./common"],(function(_exports,_options,_common){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=_exports.hasAnyH5PPermission=_exports.getPermissions=void 0; /** * Options helper for Tiny H5P plugin. * * @module tiny_h5p/options * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const permissionsName=(0,_options.getPluginOptionName)(_common.pluginName,"permissions");_exports.register=editor=>{(0,editor.options.register)(permissionsName,{processor:"object",default:{upload:!1,embed:!1}})};const getPermissions=editor=>editor.options.get(permissionsName);_exports.getPermissions=getPermissions;_exports.hasAnyH5PPermission=editor=>{const permissions=getPermissions(editor);return permissions.upload||permissions.embed}})); define("tiny_h5p/plugin",["exports","editor_tiny/loader","editor_tiny/utils","./common","./filtercontent","./commands","./configuration","./options"],(function(_exports,_loader,_utils,_common,FilterContent,Commands,Configuration,Options){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny H5P plugin for Moodle. * * @module tiny_h5p/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,FilterContent=_interopRequireWildcard(FilterContent),Commands=_interopRequireWildcard(Commands),Configuration=_interopRequireWildcard(Configuration),Options=_interopRequireWildcard(Options);var _default=new Promise((async resolve=>{const[tinyMCE,setupCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),Commands.getSetup(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(Options.register(editor),FilterContent.setup(editor),setupCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_h5p/commands",["exports","editor_tiny/utils","./ui","core/str","./common","./options"],(function(_exports,_utils,_ui,_str,_common,_options){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0;_exports.getSetup=async()=>{const[buttonText,buttonImage]=await Promise.all([(0,_str.get_string)("buttontitle",_common.component),(0,_utils.getButtonImage)("icon",_common.component)]);return editor=>{(0,_options.hasAnyH5PPermission)(editor)&&(editor.ui.registry.addIcon(_common.icon,buttonImage.html),editor.ui.registry.addToggleButton(_common.buttonName,{icon:_common.icon,tooltip:buttonText,onAction:()=>(0,_ui.handleAction)(editor),onSetup:api=>{api.setActive(editor.formatter.match("h5p"));const changed=editor.formatter.formatChanged("h5p",(state=>api.setActive(state)));return()=>changed.unbind()}}),editor.ui.registry.addMenuItem(_common.buttonName,{icon:_common.icon,text:buttonText,onAction:()=>(0,_ui.handleAction)(editor)}))}}})); define("tiny_h5p/modal",["exports","core/modal","core/modal_registry"],(function(_exports,_modal,_modal_registry){var _class;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);const H5PModal=(_defineProperty(_class=class extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}},"TYPE","tiny_h5p/modal"),_defineProperty(_class,"TEMPLATE","tiny_h5p/modal"),_class);_modal_registry.default.register(H5PModal.TYPE,H5PModal,H5PModal.TEMPLATE);var _default=H5PModal;return _exports.default=_default,_exports.default})); define("tiny_h5p/ui",["exports","editor_tiny/utils","./common","./options","core/config","core/normalise","core/templates","tiny_h5p/modal","core/modal_events","core/modal_factory","core/pending"],(function(_exports,_utils,_common,_options,_config,_normalise,_templates,_modal,_modal_events,_modal_factory,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Tiny H5P Content configuration. * * @module tiny_h5p/commands * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.handleAction=void 0,_config=_interopRequireDefault(_config),_modal=_interopRequireDefault(_modal),_modal_events=_interopRequireDefault(_modal_events),_modal_factory=_interopRequireDefault(_modal_factory),_pending=_interopRequireDefault(_pending);let openingSelection=null;_exports.handleAction=editor=>{openingSelection=editor.selection.getBookmark(),displayDialogue(editor)};const getTemplateContext=(editor,data)=>{var _permissions$upload,_permissions$embed,_data$url;const permissions=(0,_options.getPermissions)(editor),canUpload=null!==(_permissions$upload=permissions.upload)&&void 0!==_permissions$upload&&_permissions$upload,canEmbed=null!==(_permissions$embed=permissions.embed)&&void 0!==_permissions$embed&&_permissions$embed,canUploadAndEmbed=canUpload&&canEmbed;return Object.assign({},{elementid:editor.id,canUpload:canUpload,canEmbed:canEmbed,canUploadAndEmbed:canUploadAndEmbed,showOptions:!1,fileURL:null!==(_data$url=null==data?void 0:data.url)&&void 0!==_data$url?_data$url:""},data)},isValidUrl=url=>!!new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*").test(url),handleDialogueSubmission=async(editor,modal,data)=>{const pendingPromise=new _pending.default("tiny_h5p:handleDialogueSubmission"),form=(0,_normalise.getList)(modal.getRoot())[0].querySelector("form");if(!form)return modal.destroy(),displayDialogue(editor,Object.assign({},data)),void pendingPromise.resolve();const submittedUrl=form.querySelector('input[name="url"]').value,url=((form,submittedUrl,permissions)=>{if(!submittedUrl||!submittedUrl.startsWith(_config.default.wwwroot)&&!isValidUrl(submittedUrl))return null;const url=new URL(submittedUrl);return null!=permissions&&permissions.upload&&form.querySelector('[name="download"]').checked&&url.searchParams.append("export",1),null!=permissions&&permissions.embed&&form.querySelector('[name="embed"]').checked&&url.searchParams.append("embed",1),form.querySelector('[name="copyright"]').checked&&url.searchParams.append("copyright",1),url})(form,submittedUrl,(0,_options.getPermissions)(editor));if(!url)return modal.destroy(),displayDialogue(editor,Object.assign({},data,{url:submittedUrl,invalidUrl:!0})),void pendingPromise.resolve();const content=await(0,_templates.renderForPromise)("".concat(_common.component,"/content"),{url:url.toString()});editor.selection.moveToBookmark(openingSelection),editor.execCommand("mceInsertContent",!1,content.html),editor.selection.moveToBookmark(openingSelection),pendingPromise.resolve()},getCurrentH5PData=currentH5P=>{const data={};let url;try{url=new URL(currentH5P.textContent)}catch(error){return data}return url.searchParams.has("export")&&(data.download=!0,data.showOptions=!0,url.searchParams.delete("export")),url.searchParams.has("embed")&&(data.embed=!0,data.showOptions=!0,url.searchParams.delete("embed")),url.searchParams.has("copyright")&&(data.copyright=!0,data.showOptions=!0,url.searchParams.delete("copyright")),data.url=url.toString(),data},displayDialogue=async function(editor){let data=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const selection=editor.selection.getNode(),currentH5P=selection.closest(".h5p-placeholder");currentH5P&&Object.assign(data,getCurrentH5PData(currentH5P));const modal=await _modal_factory.default.create({type:_modal.default.TYPE,templateContext:getTemplateContext(editor,data),large:!0});modal.show();const $root=modal.getRoot(),root=$root[0];$root.on(_modal_events.default.save,((event,modal)=>{handleDialogueSubmission(editor,modal,data)})),root.addEventListener("click",(e=>{e.target.closest('[data-target="filepicker"]')&&(0,_utils.displayFilepicker)(editor,"h5p").then((params=>{if(""!==params.url){root.querySelector('form input[name="url"]').value=params.url}return params})).catch()}))}})); define("tiny_link/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_link/plugin",component:"tiny_link",linkButtonName:"link",linkButtonShortName:"tiny_link_link",unlinkButtonName:"unlink",unlinkButtonShortName:"tiny_link_unlink"},_exports.default})); define("tiny_link/configuration",["exports","tiny_link/common","editor_tiny/utils"],(function(_exports,_common,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0;_exports.configure=instanceConfig=>{return{menu:(menu=instanceConfig.menu,menu.insert.items.match(/\blink\b/)?menu.insert.items=menu.insert.items.replace(/\blink\b/,_common.linkButtonShortName):menu.insert.items="".concat(_common.linkButtonShortName," ").concat(menu.insert.items),menu),toolbar:(0,_utils.addToolbarButtons)(instanceConfig.toolbar,"content",[_common.linkButtonShortName,_common.unlinkButtonShortName])};var menu}})); define("tiny_link/link",["exports","core/templates","core/pending","tiny_link/selectors"],(function(_exports,_templates,_pending,_selectors){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Link helper for Tiny Link plugin. * * @module tiny_link/link * @copyright 2023 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.unSetLink=_exports.toggleActiveState=_exports.setLink=_exports.getCurrentLinkData=void 0,_templates=_interopRequireDefault(_templates),_pending=_interopRequireDefault(_pending),_selectors=_interopRequireDefault(_selectors);_exports.setLink=(currentForm,editor)=>{let value=currentForm.querySelector(_selectors.default.elements.urlEntry).value;if(""!==value){const pendingPromise=new _pending.default("tiny_link/setLink");value=value.trim();new RegExp(/^[a-zA-Z]*\.*\/|^#|^[a-zA-Z]*:/).test(value)||(value="http://"+value),setLinkOnSelection(currentForm,editor,value).then(pendingPromise.resolve)}};_exports.unSetLink=editor=>{if(editor.hasPlugin("rtc",!0))editor.execCommand("unlink");else{const dom=editor.dom,selection=editor.selection,bookmark=selection.getBookmark(),rng=selection.getRng().cloneRange(),startAnchorElm=dom.getParent(rng.startContainer,"a[href]",editor.getBody()),endAnchorElm=dom.getParent(rng.endContainer,"a[href]",editor.getBody());startAnchorElm&&rng.setStartBefore(startAnchorElm),endAnchorElm&&rng.setEndAfter(endAnchorElm),selection.setRng(rng),editor.execCommand("unlink"),selection.moveToBookmark(bookmark)}};const setLinkOnSelection=async(currentForm,editor,url)=>{const urlText=currentForm.querySelector(_selectors.default.elements.urlText),target=currentForm.querySelector(_selectors.default.elements.openInNewWindow);let textToDisplay=urlText.value.replace(/(<([^>]+)>)/gi,"").trim();""===textToDisplay&&(textToDisplay=url);const context={url:url,newwindow:target.checked};urlText.getAttribute("data-link-on-element")?(context.title=textToDisplay,context.name=editor.selection.getNode().outerHTML):context.name=textToDisplay;const{html:html}=await _templates.default.renderForPromise("tiny_link/embed_link",context),currentLink=getSelectedLink(editor);currentLink?currentLink.outerHTML=html:editor.insertContent(html)};_exports.getCurrentLinkData=editor=>{let properties={};const link=getSelectedLink(editor);if(link){const url=link.getAttribute("href"),target=link.getAttribute("target"),textToDisplay=link.innerText,title=link.getAttribute("title");""!==url&&(properties.url=url),"_blank"===target&&(properties.newwindow=!0),title&&""!==title?properties.urltext=title.trim():""!==textToDisplay&&(properties.urltext=textToDisplay.trim())}else{const selectedNode=editor.selection.getNode();if(selectedNode){const textToDisplay=getTextSelection(editor);""!==textToDisplay?(properties.urltext=textToDisplay.trim(),properties.hasTextToDisplay=!0,properties.hasPlainTextSelected=!0):selectedNode.getAttribute("data-mce-selected")&&(properties.setLinkOnElement=!0)}}return properties};const getSelectedLink=editor=>getAnchorElement(editor),getAnchorElement=(editor,selectedElm)=>(selectedElm=selectedElm||editor.selection.getNode(),editor.dom.getParent(selectedElm,"a[href]")),getTextSelection=editor=>{let selText="";const sel=editor.selection.getSel(),rangeCount=sel.rangeCount;if(rangeCount){let rangeTexts=[];for(let i=0;i<rangeCount;++i)rangeTexts.push(""+sel.getRangeAt(i));selText=rangeTexts.join("")}return selText};_exports.toggleActiveState=editor=>api=>{const updateState=()=>api.setActive(!editor.mode.isReadOnly()&&((editor,selectedElm)=>null!==getAnchorElement(editor,selectedElm))(editor,editor.selection.getNode()));return updateState(),((editor,toggler)=>(editor.on("NodeChange",toggler),()=>editor.off("NodeChange",toggler)))(editor,updateState)}})); define("tiny_link/options",["exports","editor_tiny/options","tiny_link/common"],(function(_exports,_options,_common){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=_exports.getPermissions=void 0; /** * Options helper for Tiny Link plugin. * * @module tiny_link/options * @copyright 2023 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const dataName=(0,_options.getPluginOptionName)(_common.pluginName,"data"),permissionsName=(0,_options.getPluginOptionName)(_common.pluginName,"permissions");_exports.register=editor=>{const registerOption=editor.options.register;registerOption(permissionsName,{processor:"object",default:{filepicker:!1}}),registerOption(dataName,{processor:"object"})};_exports.getPermissions=editor=>editor.options.get(permissionsName)})); define("tiny_link/plugin",["exports","editor_tiny/loader","editor_tiny/utils","tiny_link/common","tiny_link/commands","tiny_link/configuration","tiny_link/options"],(function(_exports,_loader,_utils,_common,Commands,Configuration,Options){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny Link plugin for Moodle. * * @module tiny_link/plugin * @copyright 2023 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,Commands=_interopRequireWildcard(Commands),Configuration=_interopRequireWildcard(Configuration),Options=_interopRequireWildcard(Options);var _default=new Promise((async resolve=>{const[tinyMCE,setupCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),Commands.getSetup(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(Options.register(editor),setupCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_link/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={actions:{submit:'[data-action="save"]',linkBrowser:".openlinkbrowser"},elements:{urlEntry:".tiny_link_urlentry",urlText:".tiny_link_urltext",openInNewWindow:".tiny_link_newwindow"}},_exports.default})); define("tiny_link/ui",["exports","core/modal_factory","core/modal_events","editor_tiny/utils","tiny_link/modal","tiny_link/options","tiny_link/link","tiny_link/selectors"],(function(_exports,_modal_factory,_modal_events,_utils,_modal,_options,_link,_selectors){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Tiny Link UI. * * @module tiny_link/ui * @copyright 2023 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.handleAction=void 0,_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_modal=_interopRequireDefault(_modal),_selectors=_interopRequireDefault(_selectors);_exports.handleAction=function(editor){let unlink=arguments.length>1&&void 0!==arguments[1]&&arguments[1];unlink?(0,_link.unSetLink)(editor):displayDialogue(editor)};const displayDialogue=async editor=>{const modalPromises=await _modal_factory.default.create({type:_modal.default.TYPE,templateContext:getTemplateContext(editor),large:!1});modalPromises.show();const $root=await modalPromises.getRoot(),root=$root[0],currentForm=root.querySelector("form");$root.on(_modal_events.default.hidden,(()=>{modalPromises.destroy()})),root.addEventListener("click",(e=>{const submitAction=e.target.closest(_selectors.default.actions.submit),linkBrowserAction=e.target.closest(_selectors.default.actions.linkBrowser);submitAction&&(e.preventDefault(),(0,_link.setLink)(currentForm,editor),modalPromises.destroy()),linkBrowserAction&&(e.preventDefault(),(0,_utils.displayFilepicker)(editor,"link").then((params=>(filePickerCallback(params,currentForm,editor),modalPromises.destroy()))).catch())}));const linkTitle=root.querySelector(_selectors.default.elements.urlText),linkUrl=root.querySelector(_selectors.default.elements.urlEntry);linkTitle.addEventListener("change",(()=>{linkTitle.value.length>0?linkTitle.dataset.useLinkAsText="false":(linkTitle.dataset.useLinkAsText="true",linkTitle.value=linkUrl.value)})),linkUrl.addEventListener("keyup",(()=>{updateTextToDisplay(currentForm)}))},getTemplateContext=editor=>{const data=(0,_link.getCurrentLinkData)(editor);return Object.assign({},{elementid:editor.id,showfilepicker:(0,_options.getPermissions)(editor).filepicker,isupdating:Object.keys(data).length>0},data)},filePickerCallback=(params,currentForm,editor)=>{if(params.url){currentForm.querySelector(_selectors.default.elements.urlEntry).value=params.url,(0,_link.setLink)(currentForm,editor)}},updateTextToDisplay=currentForm=>{const urlEntry=currentForm.querySelector(_selectors.default.elements.urlEntry),urlText=currentForm.querySelector(_selectors.default.elements.urlText);"true"===urlText.dataset.useLinkAsText&&(urlText.value=urlEntry.value)}})); define("tiny_link/commands",["exports","core/str","tiny_link/common","tiny_link/ui","tiny_link/link"],(function(_exports,_str,_common,_ui,_link){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0;_exports.getSetup=async()=>{const[linkButtonText,unlinkButtonText]=await Promise.all([(0,_str.get_string)("link",_common.component),(0,_str.get_string)("unlink",_common.component)]);return editor=>{editor.ui.registry.addToggleButton(_common.linkButtonShortName,{icon:"link",tooltip:linkButtonText,onAction:()=>{(0,_ui.handleAction)(editor)},onSetup:(0,_link.toggleActiveState)(editor)}),editor.ui.registry.addMenuItem(_common.linkButtonShortName,{icon:"link",shortcut:"Meta+K",text:linkButtonText,onAction:()=>{(0,_ui.handleAction)(editor)}}),editor.ui.registry.addToggleButton(_common.unlinkButtonShortName,{icon:"unlink",tooltip:unlinkButtonText,onAction:()=>{(0,_ui.handleAction)(editor,!0)},onSetup:(0,_link.toggleActiveState)(editor)}),editor.shortcuts.add("Meta+K","Shortcut for create link",(()=>{(0,_ui.handleAction)(editor)}))}}})); define("tiny_link/modal",["exports","core/modal","core/modal_registry"],(function(_exports,_modal,_modal_registry){var _class;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);const LinkModal=(_defineProperty(_class=class extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}},"TYPE","tiny_link/modal"),_defineProperty(_class,"TEMPLATE","tiny_link/modal"),_class);_modal_registry.default.register(LinkModal.TYPE,LinkModal,LinkModal.TEMPLATE);var _default=LinkModal;return _exports.default=_default,_exports.default})); define("tiny_media/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_media/plugin",component:"tiny_media",imageButtonName:"tiny_media_image",videoButtonName:"tiny_media_video",mediaManagerButtonName:"tiny_mediamanager"},_exports.default})); define("tiny_media/configuration",["exports","./common","editor_tiny/uploader","editor_tiny/utils"],(function(_exports,_common,_uploader,_utils){var obj; /** * Tiny Media configuration. * * @module tiny_media/configuration * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0,_uploader=(obj=_uploader)&&obj.__esModule?obj:{default:obj};_exports.configure=instanceConfig=>{return{contextmenu:(0,_utils.addContextmenuItem)(instanceConfig.contextmenu,_common.imageButtonName,_common.videoButtonName),menu:(menu=instanceConfig.menu,menu.insert.items.match(/\bmedia\b/)?menu.insert.items=menu.insert.items.replace(/\bmedia\b/,_common.videoButtonName):menu.insert.items="".concat(_common.videoButtonName," ").concat(menu.insert.items),menu.insert.items.match(/\bimage\b/)?menu.insert.items=menu.insert.items.replace(/\bimage\b/,_common.imageButtonName):menu.insert.items="".concat(_common.imageButtonName," ").concat(menu.insert.items),menu.tools.items+=" ".concat(_common.mediaManagerButtonName),menu),toolbar:(toolbar=instanceConfig.toolbar,toolbar.map((section=>("content"===section.name&§ion.items.unshift(_common.imageButtonName,_common.videoButtonName),section)))),images_upload_handler:(blobInfo,progress)=>(0,_uploader.default)(window.tinymce.activeEditor,"image",blobInfo.blob(),blobInfo.filename(),progress),images_reuse_filename:!0};var toolbar,menu}})); define("tiny_media/options",["exports","editor_tiny/options","./common"],(function(_exports,_options,_common){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=_exports.getPermissions=_exports.getImagePermissions=_exports.getEmbedPermissions=_exports.getData=void 0; /** * Options helper for Tiny Media plugin. * * @module tiny_media/options * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const dataName=(0,_options.getPluginOptionName)(_common.pluginName,"data"),permissionsName=(0,_options.getPluginOptionName)(_common.pluginName,"permissions");_exports.register=editor=>{const registerOption=editor.options.register;registerOption(permissionsName,{processor:"object",default:{image:{filepicker:!1}}}),registerOption(dataName,{processor:"object"})};const getPermissions=editor=>editor.options.get(permissionsName);_exports.getPermissions=getPermissions;_exports.getImagePermissions=editor=>getPermissions(editor).image;_exports.getEmbedPermissions=editor=>getPermissions(editor).embed;_exports.getData=editor=>editor.options.get(dataName)})); define("tiny_media/plugin",["exports","editor_tiny/loader","editor_tiny/utils","./common","./commands","./configuration","./options"],(function(_exports,_loader,_utils,_common,Commands,Configuration,Options){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj} /** * Tiny Media plugin for Moodle. * * @module tiny_media/plugin * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,Commands=_interopRequireWildcard(Commands),Configuration=_interopRequireWildcard(Configuration),Options=_interopRequireWildcard(Options);var _default=new Promise((async resolve=>{const[tinyMCE,setupCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),Commands.getSetup(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(Options.register(editor),setupCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_media/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={IMAGE:{actions:{submit:".tiny_image_urlentrysubmit",imageBrowser:".openimagebrowser"},elements:{form:"form.tiny_image_form",alignment:".tiny_image_alignment",alignSettings:".tiny_image_button",alt:".tiny_image_altentry",altWarning:".tiny_image_altwarning",height:".tiny_image_heightentry",width:".tiny_image_widthentry",url:".tiny_image_urlentry",urlWarning:".tiny_image_urlwarning",size:".tiny_image_size",presentation:".tiny_image_presentation",constrain:".tiny_image_constrain",customStyle:".tiny_image_customstyle",preview:".tiny_image_preview",previewBox:".tiny_image_preview_box"},styles:{responsive:"img-fluid"},alignments:[{name:"verticalAlign",value:"align-top",margin:"0 0.5em",legacyValues:["atto_image_button_text-top"]},{name:"verticalAlign",value:"align-middle",margin:"0 0.5em",legacyValues:["atto_image_button_middle"]},{name:"verticalAlign",value:"align-bottom",margin:"0 0.5em",isDefault:!0,legacyValues:["atto_image_button_text-bottom"]}]},EMBED:{actions:{submit:".tiny_media_submit",mediaBrowser:".openmediabrowser"},elements:{form:"form.tiny_media_form",source:".tiny_media_source",track:".tiny_media_track",mediaSource:".tiny_media_media_source",linkSource:".tiny_media_link_source",linkSize:".tiny_media_link_size",posterSource:".tiny_media_poster_source",posterSize:".tiny_media_poster_size",displayOptions:".tiny_media_display_options",name:".tiny_media_name_entry",title:".tiny_media_title_entry",url:".tiny_media_url_entry",width:".tiny_media_width_entry",height:".tiny_media_height_entry",trackSource:".tiny_media_track_source",trackKind:".tiny_media_track_kind_entry",trackLabel:".tiny_media_track_label_entry",trackLang:".tiny_media_track_lang_entry",trackDefault:".tiny_media_track_default",mediaControl:".tiny_media_controls",mediaAutoplay:".tiny_media_autoplay",mediaMute:".tiny_media_mute",mediaLoop:".tiny_media_loop",advancedSettings:".tiny_media_advancedsettings",linkTab:'li[data-medium-type="link"]',videoTab:'li[data-medium-type="video"]',audioTab:'li[data-medium-type="audio"]',linkPane:'.tab-pane[data-medium-type="link"]',videoPane:'.tab-pane[data-medium-type="video"]',audioPane:'.tab-pane[data-medium-type="audio"]',trackSubtitlesTab:'li[data-track-kind="subtitles"]',trackCaptionsTab:'li[data-track-kind="captions"]',trackDescriptionsTab:'li[data-track-kind="descriptions"]',trackChaptersTab:'li[data-track-kind="chapters"]',trackMetadataTab:'li[data-track-kind="metadata"]',trackSubtitlesPane:'.tab-pane[data-track-kind="subtitles"]',trackCaptionsPane:'.tab-pane[data-track-kind="captions"]',trackDescriptionsPane:'.tab-pane[data-track-kind="descriptions"]',trackChaptersPane:'.tab-pane[data-track-kind="chapters"]',trackMetadataPane:'.tab-pane[data-track-kind="metadata"]'},mediaTypes:{link:"LINK",video:"VIDEO",audio:"AUDIO"},trackKinds:{subtitles:"SUBTITLES",captions:"CAPTIONS",descriptions:"DESCRIPTIONS",chapters:"CHAPTERS",metadata:"METADATA"}}},_exports.default})); define("tiny_media/usedfiles",["exports","core/templates","core/config"],(function(_exports,Templates,_config){var obj;function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,Templates=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj} /** * Tiny Media Manager usedfiles. * * @module tiny_media/usedfiles * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */(Templates),_config=(obj=_config)&&obj.__esModule?obj:{default:obj};class UsedFileManager{constructor(files,userContext,itemId,elementId){this.files=files,this.userContext=userContext,this.itemId=itemId,this.elementId=elementId}getElementId(){return this.elementId}getUsedFiles(){const editor=window.parent.tinymce.EditorManager.get(this.getElementId());if(!editor)return window.console.error("Editor not found for ".concat(this.getElementId())),[];const content=editor.getContent(),baseUrl="".concat(_config.default.wwwroot,"/draftfile.php/").concat(this.userContext,"/user/draft/").concat(this.itemId,"/"),pattern=new RegExp("[\"']"+baseUrl.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")+"(?<filename>.+?)[\\?\"']","gm");return[...content.matchAll(pattern)].map((match=>decodeURIComponent(match.groups.filename)))}findUnusedFiles(usedFiles){return Object.entries(this.files).filter((_ref=>{let[filename]=_ref;return!usedFiles.includes(filename)})).map((_ref2=>{let[filename]=_ref2;return filename}))}findMissingFiles(usedFiles){return usedFiles.filter((filename=>!this.files.hasOwnProperty(filename)))}updateFiles(){const form=document.querySelector("form"),usedFiles=this.getUsedFiles(),unusedFiles=this.findUnusedFiles(usedFiles),missingFiles=this.findMissingFiles(usedFiles);return form.querySelectorAll('input[type=checkbox][name^="deletefile"]').forEach((checkbox=>{unusedFiles.includes(checkbox.dataset.filename)||checkbox.closest(".fitem").remove()})),form.classList.toggle("has-missing-files",!!missingFiles.length),form.classList.toggle("has-unused-files",!!unusedFiles.length),Templates.renderForPromise("tiny_media/missingfiles",{missingFiles:missingFiles}).then((_ref3=>{let{html:html,js:js}=_ref3;Templates.replaceNodeContents(form.querySelector(".missing-files"),html,js)}))}}_exports.init=(files,usercontext,itemid,elementid)=>{const manager=new UsedFileManager(files,usercontext,itemid,elementid);return manager.updateFiles(),manager}})); define("tiny_media/commands",["exports","core/str","./common","./image","./embed","./manager","editor_tiny/utils"],(function(_exports,_str,_common,_image,_embed,_manager,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0; /** * Tiny Media commands. * * @module tiny_media/commands * @copyright 2022 Huong Nguyen <huongnv13@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const isImage=node=>"img"===node.nodeName.toLowerCase(),isVideo=node=>"video"===node.nodeName.toLowerCase()||"audio"===node.nodeName.toLowerCase();_exports.getSetup=async()=>{const[imageButtonText,mediaButtonText,mediaManagerButtonText]=await(0,_str.get_strings)(["imagebuttontitle","mediabuttontitle","mediamanagerbuttontitle"].map((key=>({key:key,component:_common.component})))),[mediaManagerButtonImage]=await Promise.all([(0,_utils.getButtonImage)("filemanager",_common.component)]);return editor=>{((editor,imageButtonText)=>{const handleImageAction=()=>{new _image.MediaImage(editor).displayDialogue()};editor.ui.registry.addToggleButton(_common.imageButtonName,{icon:"image",tooltip:imageButtonText,onAction:handleImageAction,onSetup:api=>editor.selection.selectorChangedWithUnbind("img:not([data-mce-object]):not([data-mce-placeholder]),figure.image",api.setActive).unbind}),editor.ui.registry.addMenuItem(_common.imageButtonName,{icon:"image",text:imageButtonText,onAction:handleImageAction}),editor.ui.registry.addContextToolbar(_common.imageButtonName,{predicate:isImage,items:_common.imageButtonName,position:"node",scope:"node"}),editor.ui.registry.addContextMenu(_common.imageButtonName,{update:isImage})})(editor,imageButtonText),((editor,videoButtonText)=>{const handleEmbedAction=()=>{new _embed.MediaEmbed(editor).displayDialogue()};editor.ui.registry.addToggleButton(_common.videoButtonName,{icon:"embed",tooltip:videoButtonText,onAction:handleEmbedAction,onSetup:api=>editor.selection.selectorChangedWithUnbind("video:not([data-mce-object]):not([data-mce-placeholder]),audio:not([data-mce-object]):not([data-mce-placeholder])",api.setActive).unbind}),editor.ui.registry.addMenuItem(_common.videoButtonName,{icon:"embed",text:videoButtonText,onAction:handleEmbedAction}),editor.ui.registry.addContextMenu(_common.videoButtonName,{update:isVideo}),editor.ui.registry.addContextToolbar(_common.videoButtonName,{predicate:isVideo,items:_common.videoButtonName,position:"node",scope:"node"})})(editor,mediaButtonText),((editor,mediaManagerButtonText,mediaManagerButtonImage)=>{const handleMediaManager=()=>{new _manager.MediaManager(editor).displayDialogue()};editor.ui.registry.addIcon("filemanager",mediaManagerButtonImage.html),editor.ui.registry.addButton(_common.mediaManagerButtonName,{icon:"filemanager",tooltip:mediaManagerButtonText,onAction:()=>{handleMediaManager()}}),editor.ui.registry.addMenuItem(_common.mediaManagerButtonName,{icon:"filemanager",text:mediaManagerButtonText,onAction:()=>{handleMediaManager()}})})(editor,mediaManagerButtonText,mediaManagerButtonImage)}}})); define("tiny_media/embed",["exports","core/templates","core/str","core/modal_factory","core/modal_events","editor_tiny/utils","editor_tiny/options","./common","./embedmodal","./selectors","./options"],(function(_exports,_templates,_str,ModalFactory,ModalEvents,_utils,_options,_common,_embedmodal,_selectors,_options2){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.MediaEmbed=void 0,_templates=_interopRequireDefault(_templates),ModalFactory=_interopRequireWildcard(ModalFactory),ModalEvents=_interopRequireWildcard(ModalEvents),_embedmodal=_interopRequireDefault(_embedmodal),_selectors=_interopRequireDefault(_selectors);_exports.MediaEmbed=class{constructor(editor){_defineProperty(this,"editor",null),_defineProperty(this,"canShowFilePicker",!1),_defineProperty(this,"helpStrings",null),_defineProperty(this,"isUpdating",!1);const permissions=(0,_options2.getEmbedPermissions)(editor);this.canShowFilePicker=permissions.filepicker,this.editor=editor}async getHelpStrings(){if(!this.helpStrings){const[addSource,tracks,subtitles,captions,descriptions,chapters,metadata]=await(0,_str.get_strings)(["addsource_help","tracks_help","subtitles_help","captions_help","descriptions_help","chapters_help","metadata_help"].map((key=>({key:key,component:_common.component}))));this.helpStrings={addSource:addSource,tracks:tracks,subtitles:subtitles,captions:captions,descriptions:descriptions,chapters:chapters,metadata:metadata}}return this.helpStrings}async getTemplateContext(data){const languages=this.prepareMoodleLang(),helpIcons=Array.from(Object.entries(await this.getHelpStrings())).forEach((_ref=>{let[key,text]=_ref;data["".concat(key.toLowerCase(),"helpicon")]={text:text}}));return Object.assign({},{elementid:this.editor.getElement().id,showfilepicker:this.canShowFilePicker,langsinstalled:languages.installed,langsavailable:languages.available,link:!0,video:!1,audio:!1,isupdating:this.isUpdating},data,helpIcons)}async displayDialogue(){const data=Object.assign({},this.getCurrentEmbedData());this.isUpdating=0!==Object.keys(data).length;const modal=await ModalFactory.create({type:_embedmodal.default.TYPE,title:(0,_str.get_string)("createmedia","tiny_media"),templateContext:await this.getTemplateContext(data),removeOnClose:!0,large:!0});this.currentModal=modal,await this.registerEventListeners(modal),modal.show()}getCurrentEmbedData(){const properties=this.getMediumProperties();if(!properties)return{};const processedProperties={};return processedProperties[properties.type.toLowerCase()]=properties,processedProperties.link=!1,processedProperties}getSelectedMedia(){const mediaElm=this.editor.selection.getNode();return mediaElm?"video"===mediaElm.nodeName.toLowerCase()||"audio"===mediaElm.nodeName.toLowerCase()?mediaElm:mediaElm.querySelector("video")?mediaElm.querySelector("video"):mediaElm.querySelector("audio")?mediaElm.querySelector("audio"):null:null}getMediumProperties(){const boolAttr=(elem,attr)=>elem.hasAttribute(attr)&&(elem.getAttribute(attr)||""===elem.getAttribute(attr)),tracks={subtitles:[],captions:[],descriptions:[],chapters:[],metadata:[]},sources=[],medium=this.getSelectedMedia();return medium?(medium.querySelectorAll("track").forEach((track=>{tracks[track.getAttribute("kind")].push({src:track.getAttribute("src"),srclang:track.getAttribute("srclang"),label:track.getAttribute("label"),defaultTrack:boolAttr(track,"default")})})),medium.querySelectorAll("source").forEach((source=>{sources.push(source.src)})),{type:"video"===medium.nodeName.toLowerCase()?_selectors.default.EMBED.mediaTypes.video:_selectors.default.EMBED.mediaTypes.audio,sources:sources,poster:medium.getAttribute("poster"),title:medium.getAttribute("title"),width:medium.getAttribute("width"),height:medium.getAttribute("height"),autoplay:boolAttr(medium,"autoplay"),loop:boolAttr(medium,"loop"),muted:boolAttr(medium,"muted"),controls:boolAttr(medium,"controls"),tracks:tracks}):null}prepareMoodleLang(){const moodleLangs=(0,_options.getMoodleLang)(this.editor),currentLanguage=(0,_options.getCurrentLanguage)(this.editor);return{installed:Object.entries(moodleLangs.installed).map((_ref2=>{let[lang,code]=_ref2;return{lang:lang,code:code,default:lang===currentLanguage}})),available:Object.entries(moodleLangs.available).map((_ref3=>{let[lang,code]=_ref3;return{lang:lang,code:code,default:lang===currentLanguage}}))}}getMoodleLangObj(subtitleLang){const{available:available}=(0,_options.getMoodleLang)(this.editor);return available[subtitleLang]?{lang:subtitleLang,code:available[subtitleLang]}:null}filePickerCallback(params,element,fpType){if(""!==params.url){const tabPane=element.closest(".tab-pane");if(element.closest(_selectors.default.EMBED.elements.source).querySelector(_selectors.default.EMBED.elements.url).value=params.url,tabPane.id===this.editor.getElement().id+"_"+_selectors.default.EMBED.mediaTypes.link.toLowerCase()&&(tabPane.querySelector(_selectors.default.EMBED.elements.name).value=params.file),"subtitle"===fpType){const subtitleLang=params.file.split(".vtt")[0].split("-").slice(-1)[0],langObj=this.getMoodleLangObj(subtitleLang);if(langObj){const track=element.closest(_selectors.default.EMBED.elements.track);track.querySelector(_selectors.default.EMBED.elements.trackLabel).value=langObj.lang.trim(),track.querySelector(_selectors.default.EMBED.elements.trackLang).value=langObj.code}}}}addMediaSourceComponent(element,callback){const sourceElement=element.closest(_selectors.default.EMBED.elements.source+_selectors.default.EMBED.elements.mediaSource),clone=sourceElement.cloneNode(!0);sourceElement.querySelector(".removecomponent-wrapper").classList.remove("hidden"),sourceElement.querySelector(".addcomponent-wrapper").classList.add("hidden"),sourceElement.parentNode.insertBefore(clone,sourceElement.nextSibling),callback&&callback(clone)}removeMediaSourceComponent(element){element.closest(_selectors.default.EMBED.elements.source+_selectors.default.EMBED.elements.mediaSource).remove()}addTrackComponent(element,callback){const trackElement=element.closest(_selectors.default.EMBED.elements.track),clone=trackElement.cloneNode(!0);trackElement.querySelector(".removecomponent-wrapper").classList.remove("hidden"),trackElement.querySelector(".addcomponent-wrapper").classList.add("hidden"),trackElement.parentNode.insertBefore(clone,trackElement.nextSibling),callback&&callback(clone)}removeTrackComponent(element){element.closest(_selectors.default.EMBED.elements.track).remove()}getMediumTypeFromTabPane(tabPane){return tabPane.getAttribute("data-medium-type")}getTrackTypeFromTabPane(tabPane){return tabPane.getAttribute("data-track-kind")}getMediaHTML(form){const mediumType=this.getMediumTypeFromTabPane(form.querySelector(".root.tab-content > .tab-pane.active")),tabContent=form.querySelector(_selectors.default.EMBED.elements[mediumType.toLowerCase()+"Pane"]);return this["getMediaHTML"+mediumType[0].toUpperCase()+mediumType.substr(1)](tabContent)}getMediaHTMLLink(tab){const context={url:tab.querySelector(_selectors.default.EMBED.elements.url).value,name:tab.querySelector(_selectors.default.EMBED.elements.name).value||!1};return context.url?_templates.default.renderForPromise("tiny_media/embed_media_link",context):""}getMediaHTMLVideo(tab){const context=this.getContextForMediaHTML(tab);return context.width=tab.querySelector(_selectors.default.EMBED.elements.width).value||!1,context.height=tab.querySelector(_selectors.default.EMBED.elements.height).value||!1,context.poster=tab.querySelector("".concat(_selectors.default.EMBED.elements.posterSource," ").concat(_selectors.default.EMBED.elements.url)).value||!1,context.sources.length?_templates.default.renderForPromise("tiny_media/embed_media_video",context):""}getMediaHTMLAudio(tab){const context=this.getContextForMediaHTML(tab);return context.sources.length?_templates.default.renderForPromise("tiny_media/embed_media_audio",context):""}getContextForMediaHTML(tab){const tracks=Array.from(tab.querySelectorAll(_selectors.default.EMBED.elements.track)).map((track=>({track:track.querySelector(_selectors.default.EMBED.elements.trackSource+" "+_selectors.default.EMBED.elements.url).value,kind:this.getTrackTypeFromTabPane(track.closest(".tab-pane")),label:track.querySelector(_selectors.default.EMBED.elements.trackLabel).value||track.querySelector(_selectors.default.EMBED.elements.trackLang).value,srclang:track.querySelector(_selectors.default.EMBED.elements.trackLang).value,defaultTrack:track.querySelector(_selectors.default.EMBED.elements.trackDefault).checked?"true":null}))).filter((track=>!!track.track));return{sources:Array.from(tab.querySelectorAll(_selectors.default.EMBED.elements.mediaSource+" "+_selectors.default.EMBED.elements.url)).filter((source=>!!source.value)).map((source=>source.value)),description:tab.querySelector(_selectors.default.EMBED.elements.mediaSource+" "+_selectors.default.EMBED.elements.url).value||!1,tracks:tracks,showControls:tab.querySelector(_selectors.default.EMBED.elements.mediaControl).checked,autoplay:tab.querySelector(_selectors.default.EMBED.elements.mediaAutoplay).checked,muted:tab.querySelector(_selectors.default.EMBED.elements.mediaMute).checked,loop:tab.querySelector(_selectors.default.EMBED.elements.mediaLoop).checked,title:tab.querySelector(_selectors.default.EMBED.elements.title).value||!1}}getFilepickerTypeFromElement(element){return element.closest(_selectors.default.EMBED.elements.posterSource)?"image":element.closest(_selectors.default.EMBED.elements.trackSource)?"subtitle":"media"}async clickHandler(e){const element=e.target;if(element.closest(_selectors.default.EMBED.actions.mediaBrowser)){e.preventDefault();const fpType=this.getFilepickerTypeFromElement(element),params=await(0,_utils.displayFilepicker)(this.editor,fpType);this.filePickerCallback(params,element,fpType)}element.closest(_selectors.default.EMBED.elements.mediaSource+" .addcomponent")&&(e.preventDefault(),this.addMediaSourceComponent(element));element.closest(_selectors.default.EMBED.elements.mediaSource+" .removecomponent")&&(e.preventDefault(),this.removeMediaSourceComponent(element));element.closest(_selectors.default.EMBED.elements.track+" .addcomponent")&&(e.preventDefault(),this.addTrackComponent(element));element.closest(_selectors.default.EMBED.elements.track+" .removecomponent")&&(e.preventDefault(),this.removeTrackComponent(element));const trackDefaultAction=element.closest(_selectors.default.EMBED.elements.trackDefault);if(trackDefaultAction&&trackDefaultAction.checked){const getKind=el=>this.getTrackTypeFromTabPane(el.parentElement.closest(".tab-pane"));element.parentElement.closest(".root.tab-content").querySelectorAll(_selectors.default.EMBED.elements.trackDefault).forEach((select=>{select!==element&&getKind(element)===getKind(select)&&(select.checked=!1)}))}}async handleDialogueSubmission(event,modal){const{html:html}=await this.getMediaHTML(modal.getRoot()[0]);if(html)if(this.isUpdating){this.getSelectedMedia().outerHTML=html,this.isUpdating=!1}else this.editor.insertContent(html)}async registerEventListeners(modal){await modal.getBody();const $root=modal.getRoot(),root=$root[0];this.canShowFilePicker&&root.addEventListener("click",this.clickHandler.bind(this)),$root.on(ModalEvents.save,this.handleDialogueSubmission.bind(this)),$root.on(ModalEvents.hidden,(()=>{this.currentModal.destroy()})),$root.on(ModalEvents.shown,(()=>{root.querySelectorAll(_selectors.default.EMBED.elements.trackLang).forEach((dropdown=>{const defaultVal=dropdown.getAttribute("data-value");defaultVal&&(dropdown.value=defaultVal)}))}))}}})); define("tiny_media/embedmodal",["exports","core/modal","core/modal_registry","./common"],(function(_exports,_modal,_modal_registry,_common){var _class;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);const EmbedModal=(_defineProperty(_class=class extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}},"TYPE","".concat(_common.component,"/modal")),_defineProperty(_class,"TEMPLATE","".concat(_common.component,"/embed_media_modal")),_class);_modal_registry.default.register(EmbedModal.TYPE,EmbedModal,EmbedModal.TEMPLATE);var _default=EmbedModal;return _exports.default=_default,_exports.default})); define("tiny_media/image",["exports","core/templates","core/str","core/modal_factory","core/pending","editor_tiny/utils","./selectors","./imagemodal","./options","./common"],(function(_exports,_templates,_str,ModalFactory,_pending,_utils,_selectors,_imagemodal,_options,_common){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.MediaImage=void 0,_templates=_interopRequireDefault(_templates),ModalFactory=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(ModalFactory),_pending=_interopRequireDefault(_pending),_selectors=_interopRequireDefault(_selectors),_imagemodal=_interopRequireDefault(_imagemodal);_exports.MediaImage=class{constructor(editor){_defineProperty(this,"DEFAULTS",{WIDTH:160,HEIGHT:160}),_defineProperty(this,"form",null),_defineProperty(this,"rawImageDimensions",null),_defineProperty(this,"canShowFilePicker",!1),_defineProperty(this,"editor",null),_defineProperty(this,"currentModal",null),_defineProperty(this,"selectedImage",null),_defineProperty(this,"imageAlignment",null);const permissions=(0,_options.getImagePermissions)(editor);this.canShowFilePicker=permissions.filepicker,this.editor=editor}async displayDialogue(){this.rawImageDimensions=null;const currentImageData=await this.getCurrentImageData(),modal=await ModalFactory.create({type:_imagemodal.default.TYPE,title:(0,_str.get_string)("imageproperties","tiny_media"),templateContext:await this.getTemplateContext(currentImageData),removeOnClose:!0,large:!0});this.currentModal=modal,currentImageData&¤tImageData.src&&this.loadPreviewImage(currentImageData.src),await this.registerEventListeners(modal),modal.show()}async getAlignmentTitles(){if(!this.alignmentTitles){const[top,middle,bottom]=await(0,_str.get_strings)(["alignment_top","alignment_middle","alignment_bottom"].map((key=>({key:key,component:_common.component}))));this.alignmentTitles={top:top,middle:middle,bottom:bottom}}return this.alignmentTitles}async getImageAlignment(){let selected=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const titles=await this.getAlignmentTitles(),alignments=[{text:titles.top,value:"align-top"},{text:titles.middle,value:"align-middle"},{text:titles.bottom,value:"align-bottom"}];return selected&&alignments.forEach(((alignment,index,array)=>{alignment.value===selected&&(array[index].selected=!0)})),alignments}async getTemplateContext(data){return{elementid:this.editor.id,showfilepicker:this.canShowFilePicker,alignoptions:await this.getImageAlignment(),...data}}async getCurrentImageData(){const selectedImageProperties=this.getSelectedImageProperties();if(!selectedImageProperties)return{};const properties={...selectedImageProperties};return properties.align&&(properties.alignoptions=await this.getImageAlignment(properties.align)),properties.src&&(properties.haspreview=!0),properties.alt||(properties.presentation=!0),properties}filePickerCallback(params,self){if(params.url){self.form.querySelector(_selectors.default.IMAGE.elements.url).value=params.url,self.form.querySelector(_selectors.default.IMAGE.elements.width).value="",self.form.querySelector(_selectors.default.IMAGE.elements.height).value="",self.loadPreviewImage(params.url)}}storeImageDimensions(image){this.rawImageDimensions={width:image.width||this.DEFAULTS.WIDTH,height:image.height||this.DEFAULTS.HEIGHT};const currentWidth=(element=>(""===element.value&&(element.value=this.rawImageDimensions.width),element.value))(this.form.querySelector(_selectors.default.IMAGE.elements.width)),currentHeight=(element=>(""===element.value&&(element.value=this.rawImageDimensions.height),element.value))(this.form.querySelector(_selectors.default.IMAGE.elements.height)),preview=this.form.querySelector(_selectors.default.IMAGE.elements.preview);preview.setAttribute("src",image.src),preview.style.display="inline";const constrain=this.form.querySelector(_selectors.default.IMAGE.elements.constrain);if(this.isPercentageValue(currentWidth)&&this.isPercentageValue(currentHeight))constrain.checked=currentWidth===currentHeight;else if(0===image.width||0===image.height)constrain.disabled="disabled";else{const widthRatio=Math.round(1e3*parseInt(currentWidth,10)/image.width),heightRatio=Math.round(1e3*parseInt(currentHeight,10)/image.height);constrain.checked=widthRatio===heightRatio}}loadPreviewImage(url){const image=new Image;image.addEventListener("error",(()=>{this.form.querySelector(_selectors.default.IMAGE.elements.preview).style.display="none"})),image.addEventListener("load",(()=>{this.storeImageDimensions(image),this.autoAdjustSize()})),image.src=url}urlChanged(){const input=this.form.querySelector(_selectors.default.IMAGE.elements.url);input.value&&this.loadPreviewImage(input.value)}hasErrorUrlField(){const urlError=""===this.form.querySelector(_selectors.default.IMAGE.elements.url).value;return this.toggleVisibility(_selectors.default.IMAGE.elements.urlWarning,urlError),this.toggleAriaInvalid([_selectors.default.IMAGE.elements.url],urlError),urlError}hasErrorAltField(){const alt=this.form.querySelector(_selectors.default.IMAGE.elements.alt).value,presentation=this.form.querySelector(_selectors.default.IMAGE.elements.presentation).checked,imageAltError=""===alt&&!presentation;return this.toggleVisibility(_selectors.default.IMAGE.elements.altWarning,imageAltError),this.toggleAriaInvalid([_selectors.default.IMAGE.elements.alt,_selectors.default.IMAGE.elements.presentation],imageAltError),imageAltError}toggleVisibility(selector,predicate){this.form.querySelectorAll(selector).forEach((element=>{element.style.display=predicate?"block":"none"}))}toggleAriaInvalid(selectors,predicate){selectors.forEach((selector=>{this.form.querySelectorAll(selector).forEach((element=>element.setAttribute("aria-invalid",predicate)))}))}getAlignmentClass(alignment){return alignment}updateWarning(){const urlError=this.hasErrorUrlField(),imageAltError=this.hasErrorAltField();return urlError||imageAltError}getImageContext(){if(this.updateWarning())return null;const classList=[];this.form.querySelector(_selectors.default.IMAGE.elements.constrain).value&&classList.push(_selectors.default.IMAGE.styles.responsive);const alignment=this.getAlignmentClass(this.form.querySelector(_selectors.default.IMAGE.elements.alignment).value);return classList.push(alignment),{url:this.form.querySelector(_selectors.default.IMAGE.elements.url).value,alt:this.form.querySelector(_selectors.default.IMAGE.elements.alt).value,width:this.form.querySelector(_selectors.default.IMAGE.elements.width).value,height:this.form.querySelector(_selectors.default.IMAGE.elements.height).value,presentation:this.form.querySelector(_selectors.default.IMAGE.elements.presentation).checked,customStyle:this.form.querySelector(_selectors.default.IMAGE.elements.customStyle).value,classlist:classList.join(" ")}}setImage(){const pendingPromise=new _pending.default("tiny_media:setImage");if(""===this.form.querySelector(_selectors.default.IMAGE.elements.url).value)return;if(this.updateWarning())return void pendingPromise.resolve();const width=this.form.querySelector(_selectors.default.IMAGE.elements.width).value;if(!this.isPercentageValue(width)&&isNaN(parseInt(width,10)))return this.form.querySelector(_selectors.default.IMAGE.elements.width).focus(),void pendingPromise.resolve();const height=this.form.querySelector(_selectors.default.IMAGE.elements.height).value;if(!this.isPercentageValue(height)&&isNaN(parseInt(height,10)))return this.form.querySelector(_selectors.default.IMAGE.elements.height).focus(),void pendingPromise.resolve();_templates.default.render("tiny_media/image",this.getImageContext()).then((html=>(this.editor.insertContent(html),this.currentModal.destroy(),pendingPromise.resolve(),html))).catch()}handleKeyupCharacterCount(){const alt=this.form.querySelector(_selectors.default.IMAGE.elements.alt).value;this.form.querySelector("#currentcount").innerHTML=alt.length}autoAdjustSize(){let forceHeight=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.rawImageDimensions)return;const widthField=this.form.querySelector(_selectors.default.IMAGE.elements.width),heightField=this.form.querySelector(_selectors.default.IMAGE.elements.height),normalizeFieldData=fieldData=>(fieldData.isPercentageValue=!!this.isPercentageValue(fieldData.field.value),fieldData.isPercentageValue?(fieldData.percentValue=parseInt(fieldData.field.value,10),fieldData.pixelSize=this.rawImageDimensions[fieldData.type]/100*fieldData.percentValue):(fieldData.pixelSize=parseInt(fieldData.field.value,10),fieldData.percentValue=fieldData.pixelSize/this.rawImageDimensions[fieldData.type]*100),fieldData),imagePreview=this.form.querySelector(_selectors.default.IMAGE.elements.preview);imagePreview.style.width="",imagePreview.style.height="";const constrainField=this.form.querySelector(_selectors.default.IMAGE.elements.constrain),keyField=(()=>{const currentValue=forceHeight?{field:heightField,type:"height"}:{field:widthField,type:"width"};return""===currentValue.field.value&&(currentValue.field.value=this.rawImageDimensions[currentValue.type]),normalizeFieldData(currentValue)})(),relativeField=normalizeFieldData(forceHeight?{field:widthField,type:"width"}:{field:heightField,type:"height"});constrainField.checked&&(keyField.isPercentageValue?(relativeField.field.value=keyField.field.value,relativeField.percentValue=keyField.percentValue):(relativeField.pixelSize=Math.round(keyField.pixelSize/this.rawImageDimensions[keyField.type]*this.rawImageDimensions[relativeField.type]),relativeField.field.value=relativeField.pixelSize)),function(image,keyField,relativeField){let forceHeight=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const getStyleValue=field=>field.isPercentageValue?"".concat(field.percentValue,"%"):"".concat(field.pixelSize,"px");forceHeight?"width"===keyField.type?image.style.width=getStyleValue(keyField):image.style.width=getStyleValue(relativeField):(image.style[keyField.type]=getStyleValue(keyField),image.style[relativeField.type]=getStyleValue(relativeField))}(imagePreview,keyField,relativeField,!!constrainField.checked)}getSelectedImageProperties(){const image=this.getSelectedImage();if(!image)return this.selectedImage=null,null;const properties={src:null,alt:null,width:null,height:null,align:"",presentation:!1};this.removeLegacyAlignment(image),this.selectedImage=image,properties.customStyle=image.style.cssText;const width=(image=>this.isPercentageValue(String(image.width))?image.width:parseInt(image.width,10))(image);0!==width&&(properties.width=width);const height=(image=>this.isPercentageValue(String(image.height))?image.height:parseInt(image.height,10))(image);0!==height&&(properties.height=height);const alignment=this.getAlignmentProperties(image,properties);return alignment&&(properties.align=alignment.value),properties.src=image.getAttribute("src"),properties.alt=image.getAttribute("alt")||"",properties.presentation="presentation"===image.getAttribute("role"),properties}removeLegacyAlignment(imageNode){return imageNode.style.margin?(_selectors.default.IMAGE.alignments.some((alignment=>{if(imageNode.style[alignment.name]!==alignment.value)return!1;const normalisedNode=document.createElement("div");return normalisedNode.style.margin=alignment.margin,imageNode.style.margin===normalisedNode.style.margin&&(imageNode.classList.add(this.getAlignmentClass(alignment.value)),imageNode.style[alignment.name]=null,imageNode.style.margin=null,!0)})),imageNode):imageNode}getAlignmentProperties(image){const currentAlignment=_selectors.default.IMAGE.alignments.find((alignment=>!!image.classList.contains(this.getAlignmentClass(alignment.value))||!!alignment.legacyValues&&alignment.legacyValues.some((legacyValue=>image.classList.contains(legacyValue)))));return currentAlignment||_selectors.default.IMAGE.alignments.find((alignment=>alignment.isDefault))}getSelectedImage(){const imgElm=this.editor.selection.getNode(),figureElm=this.editor.dom.getParent(imgElm,"figure.image");return figureElm?this.editor.dom.select("img",figureElm)[0]:imgElm&&("IMG"!==imgElm.nodeName.toUpperCase()||this.isPlaceholderImage(imgElm))?null:imgElm}isPlaceholderImage(imgElm){return"IMG"===imgElm.nodeName.toUpperCase()&&(imgElm.hasAttribute("data-mce-object")||imgElm.hasAttribute("data-mce-placeholder"))}isPercentageValue(value){return value.match(/\d+%/)}async registerEventListeners(modal){await modal.getBody();const root=modal.getRoot()[0];this.form=root.querySelector(_selectors.default.IMAGE.elements.form),root.addEventListener("click",(e=>{const submitAction=e.target.closest(_selectors.default.IMAGE.actions.submit),imageBrowserAction=e.target.closest(_selectors.default.IMAGE.actions.imageBrowser);submitAction&&(e.preventDefault(),this.setImage()),imageBrowserAction&&this.canShowFilePicker&&(e.preventDefault(),(0,_utils.displayFilepicker)(this.editor,"image").then((params=>{this.filePickerCallback(params,this)})).catch())})),root.addEventListener("change",(e=>{e.target.closest(_selectors.default.IMAGE.elements.url)&&this.hasErrorUrlField();e.target.closest(_selectors.default.IMAGE.elements.presentation)&&this.hasErrorAltField();e.target.closest(_selectors.default.IMAGE.elements.constrain)&&this.autoAdjustSize(!0)})),root.addEventListener("blur",(e=>{if(e.target.nodeType===Node.ELEMENT_NODE){e.target.closest(_selectors.default.IMAGE.elements.url)&&this.urlChanged();e.target.closest(_selectors.default.IMAGE.elements.alt)&&this.hasErrorAltField();e.target.closest(_selectors.default.IMAGE.elements.width)&&this.autoAdjustSize();e.target.closest(_selectors.default.IMAGE.elements.height)&&this.autoAdjustSize(!0)}}),!0),root.addEventListener("keyup",(e=>{e.target.closest(_selectors.default.IMAGE.elements.alt)&&this.handleKeyupCharacterCount()}))}}})); define("tiny_media/imagemodal",["exports","core/modal","core/modal_registry","./common"],(function(_exports,_modal,_modal_registry,_common){var _class;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);const ImageModal=(_defineProperty(_class=class extends _modal.default{registerEventListeners(){super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}},"TYPE","".concat(_common.component,"/imagemodal")),_defineProperty(_class,"TEMPLATE","".concat(_common.component,"/insert_image_modal")),_class);_modal_registry.default.register(ImageModal.TYPE,ImageModal,ImageModal.TEMPLATE);var _default=ImageModal;return _exports.default=_default,_exports.default})); define("tiny_media/manager",["exports","core/templates","core/str","core/modal_factory","core/modal_events","./options","core/config"],(function(_exports,_templates,_str,Modal,ModalEvents,_options,_config){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.MediaManager=void 0,_templates=_interopRequireDefault(_templates),Modal=_interopRequireWildcard(Modal),ModalEvents=_interopRequireWildcard(ModalEvents),_config=_interopRequireDefault(_config);_exports.MediaManager=class{constructor(editor){_defineProperty(this,"editor",null),_defineProperty(this,"area",null),_defineProperty(this,"displayDialogue",(()=>{Modal.create({type:Modal.types.DEFAULT,large:!0,title:(0,_str.get_string)("mediamanagerproperties","tiny_media"),body:_templates.default.render("tiny_media/mm_iframe",{src:this.getIframeURL()})}).then((modal=>(modal.getRoot().on(ModalEvents.bodyRendered,(()=>{this.selectFirstElement()})),modal.getRoot().on(ModalEvents.hidden,(()=>{modal.destroy()})),modal.show(),document.querySelector(".modal-lg").style.cssText="max-width: 850px",modal))).catch()})),_defineProperty(this,"selectFirstElement",(()=>{const iframe=document.getElementById("mm-iframe");iframe.addEventListener("load",(function(){let intervalId=setInterval((function(){const iDocument=iframe.contentWindow.document;if(iDocument.querySelector(".filemanager")){const firstFocusableElement=iDocument.querySelector(".fp-navbar a:not([disabled])");firstFocusableElement&&firstFocusableElement.focus(),clearInterval(intervalId)}}),200)}))})),_defineProperty(this,"getIframeURL",(()=>{const url=new URL("".concat(_config.default.wwwroot,"/lib/editor/tiny/plugins/media/manage.php"));url.searchParams.append("elementid",this.editor.getElement().id);for(const key in this.area)url.searchParams.append(key,this.area[key]);return url.toString()})),this.editor=editor;const data=(0,_options.getData)(editor);this.area=data.params.area,this.area.itemid=data.fpoptions.image.itemid}}})); define("tiny_recordrtc/common",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={pluginName:"tiny_recordrtc/plugin",component:"tiny_recordrtc",audioButtonName:"tiny_recordrtc_audio",videoButtonName:"tiny_recordrtc_video"},_exports.default})); define("tiny_recordrtc/configuration",["exports","./common","editor_tiny/utils"],(function(_exports,_common,_utils){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.configure=void 0; /** * Tiny Record RTC configuration. * * @module tiny_recordrtc/configuration * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const configureMenu=menu=>{const items=menu.insert.items.split(" ");return items.some(((item,index)=>!!item.match(/(media|video)\b/)&&(items.splice(index+1,0,_common.audioButtonName,_common.videoButtonName),!0)))?menu.insert.items=items.join(" "):(0,_utils.addMenubarItem)(menu,"insert","".concat(_common.audioButtonName," ").concat(_common.videoButtonName)),menu};_exports.configure=instanceConfig=>{return{toolbar:(toolbar=instanceConfig.toolbar,toolbar.map((section=>("content"===section.name&&(section.items.some(((item,index)=>!!item.match(/(media|video)\b/)&&(section.items.splice(index+1,0,_common.audioButtonName,_common.videoButtonName),!0)))||section.items.unshift(_common.audioButtonName,_common.videoButtonName)),section)))),menu:configureMenu(instanceConfig.menu)};var toolbar}})); define("tiny_recordrtc/modal",["exports","core/modal"],(function(_exports,_modal){var obj; /** * Abstract Recording Modal for TinyMCE's RecordRTC plugin. * * @module tiny_recordrtc/modal * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk> * @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(){this.setRemoveOnClose(!0),super.registerEventListeners(),this.registerCloseOnSave(),this.registerCloseOnCancel()}}return _exports.default=_default,_exports.default})); define("tiny_recordrtc/options",["exports","./common","editor_tiny/options"],(function(_exports,_common,_options){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.register=_exports.isVideoAllowed=_exports.isAudioAllowed=_exports.getData=void 0; /** * Options helper for Tiny Record RTC plugin. * * @module tiny_recordrtc/options * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ const dataName=(0,_options.getPluginOptionName)(_common.pluginName,"data"),videoAllowedName=(0,_options.getPluginOptionName)(_common.pluginName,"videoAllowed"),audioAllowedName=(0,_options.getPluginOptionName)(_common.pluginName,"audioAllowed");_exports.register=editor=>{const registerOption=editor.options.register;registerOption(dataName,{processor:"object"}),registerOption(videoAllowedName,{processor:"boolean",default:!1}),registerOption(audioAllowedName,{processor:"boolean",default:!1})};_exports.getData=editor=>editor.options.get(dataName);_exports.isAudioAllowed=editor=>editor.options.get(audioAllowedName);_exports.isVideoAllowed=editor=>editor.options.get(videoAllowedName)})); define("tiny_recordrtc/plugin",["exports","editor_tiny/loader","editor_tiny/utils","./commands_audio","./commands_video","./configuration","./options","./common"],(function(_exports,_loader,_utils,_commands_audio,_commands_video,Configuration,Options,_common){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /** * Tiny Record RTC plugin for Moodle. * * @module tiny_recordrtc/plugin * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_commands_audio=_interopRequireDefault(_commands_audio),_commands_video=_interopRequireDefault(_commands_video),Configuration=_interopRequireWildcard(Configuration),Options=_interopRequireWildcard(Options);var _default=new Promise((async resolve=>{const[tinyMCE,setupAudioCommands,setupVideoCommands,pluginMetadata]=await Promise.all([(0,_loader.getTinyMCE)(),(0,_commands_audio.default)(),(0,_commands_video.default)(),(0,_utils.getPluginMetadata)(_common.component,_common.pluginName)]);tinyMCE.PluginManager.add("".concat(_common.component,"/plugin"),(editor=>(Options.register(editor),setupVideoCommands(editor),setupAudioCommands(editor),pluginMetadata))),resolve(["".concat(_common.component,"/plugin"),Configuration])}));return _exports.default=_default,_exports.default})); define("tiny_recordrtc/audio_recorder",["exports","./base_recorder","./modal","core/modal_registry","tiny_recordrtc/common"],(function(_exports,_base_recorder,_modal,_modal_registry,_common){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_base_recorder=_interopRequireDefault(_base_recorder),_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);class Audio extends _base_recorder.default{configurePlayer(){return this.modalRoot.querySelector("audio")}getSupportedTypes(){return["audio/ogg;codecs=opus","audio/mp4;codecs=opus","audio/mp4;codecs=wav","audio/mp4;codecs=mp3"]}getRecordingOptions(){return{audioBitsPerSecond:parseInt(this.config.audiobitrate)}}getMediaConstraints(){return{audio:!0}}getRecordingType(){return"audio"}getTimeLimit(){return this.config.audiotimelimit}getEmbedTemplateName(){return"tiny_recordrtc/embed_audio"}getFileName(prefix){return"".concat(prefix,"-audio.").concat(this.getFileExtension())}getFileExtension(){return window.MediaRecorder.isTypeSupported("audio/ogg")?"ogg":window.MediaRecorder.isTypeSupported("audio/mp4")?"mp4":(window.console.warn("Unknown file type for MediaRecorder API"),"")}static getModalClass(){var _class;const modalType="".concat(_common.component,"/audio_recorder"),registration=_modal_registry.default.get(modalType);if(registration)return registration.module;const AudioModal=(_defineProperty(_class=class extends _modal.default{},"TYPE",modalType),_defineProperty(_class,"TEMPLATE","".concat(_common.component,"/audio_recorder")),_class);return _modal_registry.default.register(AudioModal.TYPE,AudioModal,AudioModal.TEMPLATE),AudioModal}}return _exports.default=Audio,_exports.default})); define("tiny_recordrtc/base_recorder",["exports","core/str","./common","core/pending","./options","editor_tiny/uploader","core/toast","core/modal_events","core/modal_factory","core/templates","core/notification","core/prefetch"],(function(_exports,_str,_common,_pending,_options,_uploader,_toast,ModalEvents,ModalFactory,Templates,_notification,_prefetch){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_pending=_interopRequireDefault(_pending),_uploader=_interopRequireDefault(_uploader),ModalEvents=_interopRequireWildcard(ModalEvents),ModalFactory=_interopRequireWildcard(ModalFactory),Templates=_interopRequireWildcard(Templates);var _systemImportTransformerGlobalIdentifier="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}return _exports.default=class{constructor(editor,modal){var obj,key,value;value=!1,(key="stopRequested")in(obj=this)?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,this.ready=!1,this.checkAndWarnAboutBrowserCompatibility()&&(this.editor=editor,this.config=(0,_options.getData)(editor).params,this.modal=modal,this.modalRoot=modal.getRoot()[0],this.startStopButton=this.modalRoot.querySelector('button[data-action="startstop"]'),this.uploadButton=this.modalRoot.querySelector('button[data-action="upload"]'),this.setRecordButtonState(!1),this.player=this.configurePlayer(),this.registerEventListeners(),this.ready=!0,this.captureUserMedia(),this.prefetchContent())}isReady(){return this.ready}configurePlayer(){throw new Error("configurePlayer() must be implemented in ".concat(this.constructor.name))}getSupportedTypes(){throw new Error("getSupportedTypes() must be implemented in ".concat(this.constructor.name))}getRecordingOptions(){throw new Error("getRecordingOptions() must be implemented in ".concat(this.constructor.name))}getFileName(prefix){throw new Error("getFileName() must be implemented in ".concat(this.constructor.name))}getMediaConstraints(){throw new Error("getMediaConstraints() must be implemented in ".concat(this.constructor.name))}playOnCapture(){return!1}getTimeLimit(){throw new Error("getTimeLimit() must be implemented in ".concat(this.constructor.name))}getEmbedTemplateName(){throw new Error("getEmbedTemplateName() must be implemented in ".concat(this.constructor.name))}static getModalClass(){throw new Error("getModalClass() must be implemented in ".concat(this.constructor.name))}getParsedRecordingOptions(){const compatTypes=this.getSupportedTypes().reduce(((result,type)=>(result.push(type),result.push(type.replace("=",":")),result)),[]).filter((type=>window.MediaRecorder.isTypeSupported(type))),options=this.getRecordingOptions();return 0!==compatTypes.length&&(options.mimeType=compatTypes[0]),window.console.info("Selected codec ".concat(options.mimeType," from ").concat(compatTypes.length," options."),compatTypes),options}async captureUserMedia(){try{const stream=await navigator.mediaDevices.getUserMedia(this.getMediaConstraints());this.handleCaptureSuccess(stream)}catch(error){this.handleCaptureFailure(error)}}prefetchContent(){(0,_prefetch.prefetchStrings)(_common.component,["uploading","recordagain_title","recordagain_desc","discard_title","discard_desc","confirm_yes","recordinguploaded","maxfilesizehit","maxfilesizehit_title","uploadfailed"]),(0,_prefetch.prefetchTemplates)([this.getEmbedTemplateName(),"tiny_recordrtc/timeremaining"])}async displayAlert(title,content){const pendingPromise=new _pending.default("core/confirm:alert"),ModalFactory=await("function"==typeof _systemImportTransformerGlobalIdentifier.define&&_systemImportTransformerGlobalIdentifier.define.amd?new Promise((function(resolve,reject){_systemImportTransformerGlobalIdentifier.require(["core/modal_factory"],resolve,reject)})):"undefined"!=typeof module&&module.exports&&"undefined"!=typeof require||"undefined"!=typeof module&&module.component&&_systemImportTransformerGlobalIdentifier.require&&"component"===_systemImportTransformerGlobalIdentifier.require.loader?Promise.resolve(require("core/modal_factory")):Promise.resolve(_systemImportTransformerGlobalIdentifier["core/modal_factory"])),modal=await ModalFactory.create({type:ModalFactory.types.ALERT,title:title,body:content,removeOnClose:!0});return modal.show(),pendingPromise.resolve(),modal}handleCaptureSuccess(stream){this.player.srcObject=stream,this.playOnCapture()&&(this.player.muted=!0,this.player.play()),this.stream=stream,this.setupPlayerSource(),this.setRecordButtonState(!0)}setupPlayerSource(){this.player.srcObject||(this.player.srcObject=this.stream,this.player.muted=!0,this.player.play())}setRecordButtonState(enabled){this.startStopButton.disabled=!enabled}setRecordButtonVisibility(visible){this.getButtonContainer("start-stop").classList.toggle("hide",!visible)}setUploadButtonState(enabled){this.uploadButton.disabled=!enabled}setUploadButtonVisibility(visible){this.getButtonContainer("upload").classList.toggle("hide",!visible)}handleCaptureFailure(error){var subject="gum".concat(error.name.replace("Error","").toLowerCase());this.displayAlert((0,_str.get_string)("".concat(subject,"_title"),_common.component),(0,_str.get_string)(subject,_common.component))}close(){this.modal.hide()}registerEventListeners(){this.modalRoot.addEventListener("click",this.handleModalClick.bind(this)),this.modal.getRoot().on(ModalEvents.outsideClick,this.outsideClickHandler.bind(this)),this.modal.getRoot().on(ModalEvents.hidden,(()=>{this.cleanupStream(),this.requestRecordingStop()}))}async outsideClickHandler(event){if(this.isRecording())event.preventDefault();else if(this.hasData()){event.preventDefault();try{await(0,_notification.saveCancelPromise)(await(0,_str.get_string)("discard_title",_common.component),await(0,_str.get_string)("discard_desc",_common.component),await(0,_str.get_string)("confirm_yes",_common.component)),this.modal.hide()}catch(error){}}}handleModalClick(event){const button=event.target.closest("button");if(button&&button.dataset.action){const action=button.dataset.action;"startstop"===action&&this.handleRecordingStartStopRequested(),"upload"===action&&this.uploadRecording()}}handleRecordingStartStopRequested(){var _this$mediaRecorder;"recording"===(null===(_this$mediaRecorder=this.mediaRecorder)||void 0===_this$mediaRecorder?void 0:_this$mediaRecorder.state)?this.requestRecordingStop():this.startRecording()}async onMediaStopped(){var _this$getButtonContai;this.blob=new Blob(this.data.chunks,{type:this.mediaRecorder.mimeType}),this.player.srcObject=null,this.player.src=URL.createObjectURL(this.blob),this.setRecordButtonTextFromString("recordagain"),this.player.muted=!1,this.player.controls=!0,null===(_this$getButtonContai=this.getButtonContainer("player"))||void 0===_this$getButtonContai||_this$getButtonContai.classList.toggle("hide",!1),this.setUploadButtonVisibility(!0),this.setUploadButtonState(!0)}async uploadRecording(){if(0===this.data.chunks.length)return void this.displayAlert("norecordingfound");const fileName=this.getFileName((1e3*Math.random()).toString().replace(".",""));try{this.setRecordButtonVisibility(!1),this.setUploadButtonState(!1);const fileURL=await(0,_uploader.default)(this.editor,"media",this.blob,fileName,(progress=>{this.setUploadButtonTextProgress(progress)}));this.insertMedia(fileURL),this.close(),(0,_toast.add)(await(0,_str.get_string)("recordinguploaded",_common.component))}catch(error){this.setUploadButtonState(!0),(0,_toast.add)(await(0,_str.get_string)("uploadfailed",_common.component,{error:error}),{type:"error"})}}getButtonContainer(purpose){return this.modalRoot.querySelector('[data-purpose="'.concat(purpose,'-container"]'))}static isBrowserCompatible(){return this.checkSecure()&&this.hasUserMedia()}static async display(editor){const ModalClass=this.getModalClass(),modal=await ModalFactory.create({type:ModalClass.TYPE,templateContext:{},large:!0});return new this(editor,modal).isReady()&&modal.show(),modal}checkAndWarnAboutBrowserCompatibility(){return this.constructor.checkSecure()?!!this.constructor.hasUserMedia||((0,_str.get_strings)(["nowebrtc_title","nowebrtc"].map((key=>({key:key,component:_common.component})))).then((_ref2=>{let[title,message]=_ref2;return(0,_toast.add)(message,{title:title,type:"error"})})).catch(),!1):((0,_str.get_strings)(["insecurealert_title","insecurealert"].map((key=>({key:key,component:_common.component})))).then((_ref=>{let[title,message]=_ref;return(0,_toast.add)(message,{title:title,type:"error"})})).catch(),!1)}static hasUserMedia(){return navigator.mediaDevices&&window.MediaRecorder}static checkSecure(){return window.isSecureContext}async setStopRecordingButton(){const{html:html,js:js}=await Templates.renderForPromise("tiny_recordrtc/timeremaining",this.getTimeRemaining());Templates.replaceNodeContents(this.startStopButton,html,js),this.buttonTimer=setInterval(this.updateRecordButtonTime.bind(this),500)}updateRecordButtonTime(){const{remaining:remaining,minutes:minutes,seconds:seconds}=this.getTimeRemaining();remaining<0?this.requestRecordingStop():(this.startStopButton.querySelector('[data-type="minutes"]').textContent=minutes,this.startStopButton.querySelector('[data-type="seconds"]').textContent=seconds)}async setRecordButtonTextFromString(string){this.startStopButton.textContent=await(0,_str.get_string)(string,_common.component)}async setUploadButtonTextProgress(progress){this.uploadButton.textContent=await(0,_str.get_string)("uploading",_common.component,{progress:Math.round(100*progress)/100})}async resetUploadButtonText(){this.uploadButton.textContent=await(0,_str.get_string)("upload",_common.component)}clearButtonTimer(){this.buttonTimer&&clearInterval(this.buttonTimer),this.buttonTimer=null}getTimeRemaining(){const now=(new Date).getTime(),remaining=Math.floor(this.getTimeLimit()-(now-this.startTime)/1e3),formatter=new Intl.NumberFormat(navigator.language,{minimumIntegerDigits:2}),seconds=formatter.format(remaining%60);return{remaining:remaining,minutes:formatter.format(Math.floor((remaining-seconds)/60)),seconds:seconds}}getMaxUploadSize(){return this.config.maxrecsize}requestRecordingStop(){this.mediaRecorder&&"inactive"!==this.mediaRecorder.state?this.stopRequested=!0:this.cleanupStream()}stopRecorder(){this.mediaRecorder.stop(),this.player.muted=!1}cleanupStream(){this.stream&&this.stream.getTracks().filter((track=>"ended"!==track.readyState)).forEach((track=>track.stop()))}handleStopped(){this.onMediaStopped(),this.clearButtonTimer()}handleStarted(){this.startTime=(new Date).getTime(),this.setStopRecordingButton()}handleDataAvailable(event){if(this.isRecording()){const newSize=this.data.blobSize+event.data.size;newSize>=this.getMaxUploadSize()?(this.stopRecorder(),this.displayFileLimitHitMessage()):(this.data.chunks.push(event.data),this.data.blobSize=newSize,this.stopRequested&&this.stopRecorder())}}async displayFileLimitHitMessage(){(0,_toast.add)(await(0,_str.get_string)("maxfilesizehit",_common.component),{title:await(0,_str.get_string)("maxfilesizehit_title",_common.component),type:"error"})}isRecording(){var _this$mediaRecorder2;return"recording"===(null===(_this$mediaRecorder2=this.mediaRecorder)||void 0===_this$mediaRecorder2?void 0:_this$mediaRecorder2.state)}hasData(){var _this$data;return!(null===(_this$data=this.data)||void 0===_this$data||!_this$data.blobSize)}async startRecording(){if(this.mediaRecorder){if(this.isRecording()&&this.mediaRecorder.stop(),this.hasData()){if(!await this.recordAgainConfirmation())return;this.setUploadButtonVisibility(!1)}this.mediaRecorder=null}this.mediaRecorder=new MediaRecorder(this.stream,this.getParsedRecordingOptions()),this.mediaRecorder.addEventListener("dataavailable",this.handleDataAvailable.bind(this)),this.mediaRecorder.addEventListener("stop",this.handleStopped.bind(this)),this.mediaRecorder.addEventListener("start",this.handleStarted.bind(this)),this.data={chunks:[],blobSize:0},this.setupPlayerSource(),this.stopRequested=!1,this.mediaRecorder.start(50)}async recordAgainConfirmation(){try{return await(0,_notification.saveCancelPromise)(await(0,_str.get_string)("recordagain_title",_common.component),await(0,_str.get_string)("recordagain_desc",_common.component),await(0,_str.get_string)("confirm_yes",_common.component)),!0}catch{return!1}}async insertMedia(source){const{html:html}=await Templates.renderForPromise(this.getEmbedTemplateName(),this.getEmbedTemplateContext({source:source}));this.editor.insertContent(html)}getEmbedTemplateContext(templateContext){return templateContext}},_exports.default})); define("tiny_recordrtc/commands_audio",["exports","core/str","editor_tiny/utils","./common","./audio_recorder","./options"],(function(_exports,_str,_utils,_common,_audio_recorder,_options){var obj; /** * Tiny Record RTC - record audio command. * * @module tiny_recordrtc/recordAudioCommands * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_audio_recorder=(obj=_audio_recorder)&&obj.__esModule?obj:{default:obj};return _exports.default=async()=>{if(!_audio_recorder.default.isBrowserCompatible())return()=>!1;const[audioButtonTitle,audio]=await Promise.all([(0,_str.get_string)("audiobuttontitle",_common.component),(0,_utils.getButtonImage)("audio",_common.component)]);return editor=>{if(!(0,_options.isAudioAllowed)(editor))return;editor.ui.registry.addIcon("audio",audio.html),editor.ui.registry.addButton(_common.audioButtonName,{icon:"audio",tooltip:audioButtonTitle,onAction:()=>_audio_recorder.default.display(editor)}),editor.ui.registry.addMenuItem(_common.audioButtonName,{icon:"audio",text:audioButtonTitle,onAction:()=>_audio_recorder.default.display(editor)})}},_exports.default})); define("tiny_recordrtc/commands_video",["exports","core/str","editor_tiny/utils","./common","./options","./video_recorder"],(function(_exports,_str,_utils,_common,_options,_video_recorder){var obj; /** * Tiny Record RTC - record video command. * * @module tiny_recordrtc/recordVideoCommands * @copyright 2022, Stevani Andolo <stevani@hotmail.com.au> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_video_recorder=(obj=_video_recorder)&&obj.__esModule?obj:{default:obj};return _exports.default=async()=>{if(!_video_recorder.default.isBrowserCompatible())return()=>!1;const[videoButtonTitle,buttonImage]=await Promise.all([(0,_str.get_string)("videobuttontitle",_common.component),(0,_utils.getButtonImage)("video",_common.component)]);return editor=>{if(!(0,_options.isVideoAllowed)(editor))return;editor.ui.registry.addIcon("video",buttonImage.html),editor.ui.registry.addButton(_common.videoButtonName,{icon:"video",tooltip:videoButtonTitle,onAction:()=>_video_recorder.default.display(editor)}),editor.ui.registry.addMenuItem(_common.videoButtonName,{icon:"video",text:videoButtonTitle,onAction:()=>_video_recorder.default.display(editor)})}},_exports.default})); define("tiny_recordrtc/video_recorder",["exports","./base_recorder","tiny_recordrtc/modal","core/modal_registry","tiny_recordrtc/common"],(function(_exports,_base_recorder,_modal,_modal_registry,_common){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_base_recorder=_interopRequireDefault(_base_recorder),_modal=_interopRequireDefault(_modal),_modal_registry=_interopRequireDefault(_modal_registry);class Video extends _base_recorder.default{configurePlayer(){return this.modalRoot.querySelector("video")}getSupportedTypes(){return["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/mp4;codecs=h264,opus","video/mp4;codecs=h264,wav","video/mp4;codecs=v9,opus"]}getRecordingOptions(){return{audioBitsPerSecond:parseInt(this.config.audiobitrate),videoBitsPerSecond:parseInt(this.config.videobitrate)}}getMediaConstraints(){return{audio:!0,video:{width:{ideal:640},height:{ideal:480}}}}playOnCapture(){return!0}getRecordingType(){return"video"}getTimeLimit(){return this.config.videotimelimit}getEmbedTemplateName(){return"tiny_recordrtc/embed_video"}getFileName(prefix){return"".concat(prefix,"-video.").concat(this.getFileExtension())}getFileExtension(){return window.MediaRecorder.isTypeSupported("audio/webm")?"webm":window.MediaRecorder.isTypeSupported("audio/mp4")?"mp4":(window.console.warn("Unknown file type for MediaRecorder API"),"")}static getModalClass(){var _class;const modalType="".concat(_common.component,"/video_recorder"),registration=_modal_registry.default.get(modalType);if(registration)return registration.module;const VideoModal=(_defineProperty(_class=class extends _modal.default{},"TYPE",modalType),_defineProperty(_class,"TEMPLATE","".concat(_common.component,"/video_recorder")),_class);return _modal_registry.default.register(VideoModal.TYPE,VideoModal,VideoModal.TEMPLATE),VideoModal}}return _exports.default=Video,_exports.default}));