first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
/**
* 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}));
//# sourceMappingURL=actionselector.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}))}}}));
//# sourceMappingURL=competency_outcomes.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"competency_outcomes.min.js","sources":["../src/competency_outcomes.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Competency rule config.\n *\n * @module tool_lp/competency_outcomes\n * @copyright 2015 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery',\n 'core/str'],\n function($, Str) {\n\n var OUTCOME_NONE = 0,\n OUTCOME_EVIDENCE = 1,\n OUTCOME_COMPLETE = 2,\n OUTCOME_RECOMMEND = 3;\n\n return {\n\n NONE: OUTCOME_NONE,\n EVIDENCE: OUTCOME_EVIDENCE,\n COMPLETE: OUTCOME_COMPLETE,\n RECOMMEND: OUTCOME_RECOMMEND,\n\n /**\n * Get all the outcomes.\n *\n * @return {Object} Indexed by outcome code, contains code and name.\n * @method getAll\n */\n getAll: function() {\n var self = this;\n return Str.get_strings([\n {key: 'competencyoutcome_none', component: 'tool_lp'},\n {key: 'competencyoutcome_evidence', component: 'tool_lp'},\n {key: 'competencyoutcome_recommend', component: 'tool_lp'},\n {key: 'competencyoutcome_complete', component: 'tool_lp'},\n ]).then(function(strings) {\n var outcomes = {};\n outcomes[self.NONE] = {code: self.NONE, name: strings[0]};\n outcomes[self.EVIDENCE] = {code: self.EVIDENCE, name: strings[1]};\n outcomes[self.RECOMMEND] = {code: self.RECOMMEND, name: strings[2]};\n outcomes[self.COMPLETE] = {code: self.COMPLETE, name: strings[3]};\n return outcomes;\n });\n },\n\n /**\n * Get the string for an outcome.\n *\n * @param {Number} id The outcome code.\n * @return {Promise} Resolved with the string.\n * @method getString\n */\n getString: function(id) {\n var self = this,\n all = self.getAll();\n\n return all.then(function(outcomes) {\n if (typeof outcomes[id] === 'undefined') {\n return $.Deferred().reject().promise();\n }\n return outcomes[id].name;\n });\n }\n };\n});\n"],"names":["define","$","Str","NONE","EVIDENCE","COMPLETE","RECOMMEND","getAll","self","this","get_strings","key","component","then","strings","outcomes","code","name","getString","id","Deferred","reject","promise"],"mappings":";;;;;;;AAuBAA,qCAAO,CAAC,SACA,aACA,SAASC,EAAGC,WAOT,CAEHC,KAPe,EAQfC,SAPmB,EAQnBC,SAPmB,EAQnBC,UAPoB,EAepBC,OAAQ,eACAC,KAAOC,YACJP,IAAIQ,YAAY,CACnB,CAACC,IAAK,yBAA0BC,UAAW,WAC3C,CAACD,IAAK,6BAA8BC,UAAW,WAC/C,CAACD,IAAK,8BAA+BC,UAAW,WAChD,CAACD,IAAK,6BAA8BC,UAAW,aAChDC,MAAK,SAASC,aACTC,SAAW,UACfA,SAASP,KAAKL,MAAQ,CAACa,KAAMR,KAAKL,KAAMc,KAAMH,QAAQ,IACtDC,SAASP,KAAKJ,UAAY,CAACY,KAAMR,KAAKJ,SAAUa,KAAMH,QAAQ,IAC9DC,SAASP,KAAKF,WAAa,CAACU,KAAMR,KAAKF,UAAWW,KAAMH,QAAQ,IAChEC,SAASP,KAAKH,UAAY,CAACW,KAAMR,KAAKH,SAAUY,KAAMH,QAAQ,IACvDC,aAWfG,UAAW,SAASC,WACLV,KACIF,SAEJM,MAAK,SAASE,sBACO,IAAjBA,SAASI,IACTlB,EAAEmB,WAAWC,SAASC,UAE1BP,SAASI,IAAIF"}
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=competency_plan_navigation.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"competency_plan_navigation.min.js","sources":["../src/competency_plan_navigation.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Event click on selecting competency in the competency autocomplete.\n *\n * @module tool_lp/competency_plan_navigation\n * @copyright 2016 Issam Taboubi <issam.taboubi@umontreal.ca>\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery'], function($) {\n\n /**\n * CompetencyPlanNavigation\n *\n * @class\n * @param {String} competencySelector The selector of the competency element.\n * @param {String} baseUrl The base url for the page (no params).\n * @param {Number} userId The user id\n * @param {Number} competencyId The competency id\n * @param {Number} planId The plan id\n */\n var CompetencyPlanNavigation = function(competencySelector, baseUrl, userId, competencyId, planId) {\n this._baseUrl = baseUrl;\n this._userId = userId + '';\n this._competencyId = competencyId + '';\n this._planId = planId;\n this._ignoreFirstCompetency = true;\n\n $(competencySelector).on('change', this._competencyChanged.bind(this));\n };\n\n /**\n * The competency was changed in the select list.\n *\n * @method _competencyChanged\n * @param {Event} e\n */\n CompetencyPlanNavigation.prototype._competencyChanged = function(e) {\n if (this._ignoreFirstCompetency) {\n this._ignoreFirstCompetency = false;\n return;\n }\n var newCompetencyId = $(e.target).val();\n var queryStr = '?userid=' + this._userId + '&planid=' + this._planId + '&competencyid=' + newCompetencyId;\n document.location = this._baseUrl + queryStr;\n };\n\n /** @property {Number} The id of the competency. */\n CompetencyPlanNavigation.prototype._competencyId = null;\n /** @property {Number} The id of the user. */\n CompetencyPlanNavigation.prototype._userId = null;\n /** @property {Number} The id of the plan. */\n CompetencyPlanNavigation.prototype._planId = null;\n /** @property {String} Plugin base url. */\n CompetencyPlanNavigation.prototype._baseUrl = null;\n /** @property {Boolean} Ignore the first change event for competencies. */\n CompetencyPlanNavigation.prototype._ignoreFirstCompetency = null;\n\n return CompetencyPlanNavigation;\n});\n"],"names":["define","$","CompetencyPlanNavigation","competencySelector","baseUrl","userId","competencyId","planId","_baseUrl","_userId","_competencyId","_planId","_ignoreFirstCompetency","on","this","_competencyChanged","bind","prototype","e","newCompetencyId","target","val","queryStr","document","location"],"mappings":";;;;;;;AAuBAA,4CAAO,CAAC,WAAW,SAASC,OAYpBC,yBAA2B,SAASC,mBAAoBC,QAASC,OAAQC,aAAcC,aAClFC,SAAWJ,aACXK,QAAUJ,OAAS,QACnBK,cAAgBJ,aAAe,QAC/BK,QAAUJ,YACVK,wBAAyB,EAE9BX,EAAEE,oBAAoBU,GAAG,SAAUC,KAAKC,mBAAmBC,KAAKF,eASpEZ,yBAAyBe,UAAUF,mBAAqB,SAASG,MACzDJ,KAAKF,4BACAA,wBAAyB,WAG9BO,gBAAkBlB,EAAEiB,EAAEE,QAAQC,MAC9BC,SAAW,WAAaR,KAAKL,QAAU,WAAaK,KAAKH,QAAU,iBAAmBQ,gBAC1FI,SAASC,SAAWV,KAAKN,SAAWc,WAIxCpB,yBAAyBe,UAAUP,cAAgB,KAEnDR,yBAAyBe,UAAUR,QAAU,KAE7CP,yBAAyBe,UAAUN,QAAU,KAE7CT,yBAAyBe,UAAUT,SAAW,KAE9CN,yBAAyBe,UAAUL,uBAAyB,KAErDV"}
+10
View File
@@ -0,0 +1,10 @@
/**
* Competency rule base module.
*
* @module tool_lp/competency_rule
* @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}));
//# sourceMappingURL=competency_rule.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=competency_rule_all.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"competency_rule_all.min.js","sources":["../src/competency_rule_all.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Competency rule all module.\n *\n * @module tool_lp/competency_rule_all\n * @copyright 2015 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery',\n 'core/str',\n 'tool_lp/competency_rule',\n ],\n function($, Str, RuleBase) {\n\n /**\n * Competency rule all class.\n *\n * @class tool_lp/competency_rule_all\n */\n var Rule = function() {\n RuleBase.apply(this, arguments);\n };\n Rule.prototype = Object.create(RuleBase.prototype);\n\n /**\n * Return the type of the module.\n *\n * @return {String}\n * @method getType\n */\n Rule.prototype.getType = function() {\n return 'core_competency\\\\competency_rule_all';\n };\n\n /**\n * Whether or not the current config is valid.\n *\n * @return {Boolean}\n * @method isValid\n */\n Rule.prototype.isValid = function() {\n return true;\n };\n\n return Rule;\n});\n"],"names":["define","$","Str","RuleBase","Rule","apply","this","arguments","prototype","Object","create","getType","isValid"],"mappings":";;;;;;;AAuBAA,qCAAO,CAAC,SACA,WACA,4BAEA,SAASC,EAAGC,IAAKC,cAOjBC,KAAO,WACPD,SAASE,MAAMC,KAAMC,mBAEzBH,KAAKI,UAAYC,OAAOC,OAAOP,SAASK,YAQzBG,QAAU,iBACd,wCASXP,KAAKI,UAAUI,QAAU,kBACd,GAGJR"}
+10
View File
@@ -0,0 +1,10 @@
/**
* Competency rule points module.
*
* @module tool_lp/competency_rule_points
* @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}));
//# sourceMappingURL=competency_rule_points.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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)))}}}));
//# sourceMappingURL=competencydialogue.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,15 @@
/**
* 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}));
//# sourceMappingURL=competencypicker_user_plans.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* Handle selection changes on the competency tree.
*
* @module tool_lp/competencytree
* @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}}}));
//# sourceMappingURL=competencytree.min.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
/**
* Change the course competency settings in a popup.
*
* @module tool_lp/course_competency_settings
* @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}));
//# sourceMappingURL=course_competency_settings.min.js.map
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
/**
* 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}));
//# sourceMappingURL=dialogue.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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)})}))}))}}}));
//# sourceMappingURL=dragdrop-reorder.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=event_base.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"event_base.min.js","sources":["../src/event_base.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Event base javascript module.\n *\n * @module tool_lp/event_base\n * @copyright 2015 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery'], function($) {\n\n /**\n * Base class.\n */\n var Base = function() {\n this._eventNode = $('<div></div>');\n };\n\n /** @property {Node} The node we attach the events to. */\n Base.prototype._eventNode = null;\n\n /**\n * Register an event listener.\n *\n * @param {String} type The event type.\n * @param {Function} handler The event listener.\n * @method on\n */\n Base.prototype.on = function(type, handler) {\n this._eventNode.on(type, handler);\n };\n\n /**\n * Trigger an event.\n *\n * @param {String} type The type of event.\n * @param {Object} data The data to pass to the listeners.\n * @method _trigger\n */\n Base.prototype._trigger = function(type, data) {\n this._eventNode.trigger(type, [data]);\n };\n\n return /** @alias module:tool_lp/event_base */ Base;\n});\n"],"names":["define","$","Base","_eventNode","prototype","on","type","handler","_trigger","data","trigger"],"mappings":";;;;;;;AAsBAA,4BAAO,CAAC,WAAW,SAASC,OAKpBC,KAAO,gBACFC,WAAaF,EAAE,uBAIxBC,KAAKE,UAAUD,WAAa,KAS5BD,KAAKE,UAAUC,GAAK,SAASC,KAAMC,cAC1BJ,WAAWE,GAAGC,KAAMC,UAU7BL,KAAKE,UAAUI,SAAW,SAASF,KAAMG,WAChCN,WAAWO,QAAQJ,KAAM,CAACG,QAGYP"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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.")}})))}}}));
//# sourceMappingURL=evidence_delete.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"evidence_delete.min.js","sources":["../src/evidence_delete.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Evidence delete.\n *\n * @module tool_lp/evidence_delete\n * @copyright 2016 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery',\n 'core/notification',\n 'core/ajax',\n 'core/str',\n 'core/log'],\n function($, Notification, Ajax, Str, Log) {\n\n var selectors = {};\n\n /**\n * Register an event listener.\n *\n * @param {String} triggerSelector The node on which the click will happen.\n * @param {String} containerSelector The parent node that will be removed and contains the evidence ID.\n */\n var register = function(triggerSelector, containerSelector) {\n if (typeof selectors[triggerSelector] !== 'undefined') {\n return;\n }\n\n selectors[triggerSelector] = $('body').delegate(triggerSelector, 'click', function(e) {\n var parent = $(e.currentTarget).parents(containerSelector);\n if (!parent.length || parent.length > 1) {\n Log.error('None or too many evidence container were found.');\n return;\n }\n var evidenceId = parent.data('id');\n if (!evidenceId) {\n Log.error('Evidence ID was not found.');\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n Str.get_strings([\n {key: 'confirm', component: 'moodle'},\n {key: 'areyousure', component: 'moodle'},\n {key: 'delete', component: 'moodle'},\n {key: 'cancel', component: 'moodle'}\n ]).done(function(strings) {\n Notification.confirm(\n strings[0], // Confirm.\n strings[1], // Are you sure?\n strings[2], // Delete.\n strings[3], // Cancel.\n function() {\n var promise = Ajax.call([{\n methodname: 'core_competency_delete_evidence',\n args: {\n id: evidenceId\n }\n }]);\n promise[0].then(function() {\n parent.remove();\n return;\n }).fail(Notification.exception);\n }\n );\n }).fail(Notification.exception);\n\n\n });\n };\n\n return /** @alias module:tool_lp/evidence_delete */ {\n\n /**\n * Register an event listener.\n *\n * @param {String} triggerSelector The node on which the click will happen.\n * @param {String} containerSelector The parent node that will be removed and contains the evidence ID.\n * @return {Void}\n */\n register: register\n };\n\n});\n"],"names":["define","$","Notification","Ajax","Str","Log","selectors","register","triggerSelector","containerSelector","delegate","e","parent","currentTarget","parents","length","error","evidenceId","data","preventDefault","stopPropagation","get_strings","key","component","done","strings","confirm","call","methodname","args","id","then","remove","fail","exception"],"mappings":";;;;;;;AAuBAA,iCAAO,CAAC,SACA,oBACA,YACA,WACA,aACA,SAASC,EAAGC,aAAcC,KAAMC,IAAKC,SAErCC,UAAY,SA0DoC,CAShDC,SA3DW,SAASC,gBAAiBC,wBACK,IAA/BH,UAAUE,mBAIrBF,UAAUE,iBAAmBP,EAAE,QAAQS,SAASF,gBAAiB,SAAS,SAASG,OAC3EC,OAASX,EAAEU,EAAEE,eAAeC,QAAQL,uBACnCG,OAAOG,QAAUH,OAAOG,OAAS,EAClCV,IAAIW,MAAM,4DAGVC,WAAaL,OAAOM,KAAK,MACxBD,YAKLN,EAAEQ,iBACFR,EAAES,kBAEFhB,IAAIiB,YAAY,CACZ,CAACC,IAAK,UAAWC,UAAW,UAC5B,CAACD,IAAK,aAAcC,UAAW,UAC/B,CAACD,IAAK,SAAUC,UAAW,UAC3B,CAACD,IAAK,SAAUC,UAAW,YAC5BC,MAAK,SAASC,SACbvB,aAAawB,QACTD,QAAQ,GACRA,QAAQ,GACRA,QAAQ,GACRA,QAAQ,IACR,WACkBtB,KAAKwB,KAAK,CAAC,CACrBC,WAAY,kCACZC,KAAM,CACFC,GAAIb,eAGJ,GAAGc,MAAK,WACZnB,OAAOoB,YAERC,KAAK/B,aAAagC,iBAG9BD,KAAK/B,aAAagC,YA/BjB7B,IAAIW,MAAM"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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)}}}));
//# sourceMappingURL=form-user-selector.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"form-user-selector.min.js","sources":["../src/form-user-selector.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * User selector module.\n *\n * @module tool_lp/form-user-selector\n * @copyright 2015 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery', 'core/ajax', 'core/templates'], function($, Ajax, Templates) {\n\n return /** @alias module:tool_lp/form-user-selector */ {\n\n processResults: function(selector, results) {\n var users = [];\n $.each(results, function(index, user) {\n users.push({\n value: user.id,\n label: user._label\n });\n });\n return users;\n },\n\n transport: function(selector, query, success, failure) {\n var promise;\n var capability = $(selector).data('capability');\n if (typeof capability === \"undefined\") {\n capability = '';\n }\n\n promise = Ajax.call([{\n methodname: 'tool_lp_search_users',\n args: {\n query: query,\n capability: capability\n }\n }]);\n\n promise[0].then(function(results) {\n var promises = [],\n i = 0;\n\n // Render the label.\n $.each(results.users, function(index, user) {\n var ctx = user,\n identity = [];\n $.each(['idnumber', 'email', 'phone1', 'phone2', 'department', 'institution'], function(i, k) {\n if (typeof user[k] !== 'undefined' && user[k] !== '') {\n ctx.hasidentity = true;\n identity.push(user[k]);\n }\n });\n ctx.identity = identity.join(', ');\n promises.push(Templates.render('tool_lp/form-user-selector-suggestion', ctx));\n });\n\n // Apply the label to the results.\n return $.when.apply($.when, promises).then(function() {\n var args = arguments;\n $.each(results.users, function(index, user) {\n user._label = args[i];\n i++;\n });\n success(results.users);\n return;\n });\n\n }).catch(failure);\n }\n\n };\n\n});\n"],"names":["define","$","Ajax","Templates","processResults","selector","results","users","each","index","user","push","value","id","label","_label","transport","query","success","failure","capability","data","call","methodname","args","then","promises","i","ctx","identity","k","hasidentity","join","render","when","apply","arguments","catch"],"mappings":";;;;;;;AAuBAA,oCAAO,CAAC,SAAU,YAAa,mBAAmB,SAASC,EAAGC,KAAMC,iBAET,CAEnDC,eAAgB,SAASC,SAAUC,aAC3BC,MAAQ,UACZN,EAAEO,KAAKF,SAAS,SAASG,MAAOC,MAC5BH,MAAMI,KAAK,CACPC,MAAOF,KAAKG,GACZC,MAAOJ,KAAKK,YAGbR,OAGXS,UAAW,SAASX,SAAUY,MAAOC,QAASC,aAEtCC,WAAanB,EAAEI,UAAUgB,KAAK,mBACR,IAAfD,aACPA,WAAa,IAGPlB,KAAKoB,KAAK,CAAC,CACjBC,WAAY,uBACZC,KAAM,CACFP,MAAOA,MACPG,WAAYA,eAIZ,GAAGK,MAAK,SAASnB,aACjBoB,SAAW,GACXC,EAAI,SAGR1B,EAAEO,KAAKF,QAAQC,OAAO,SAASE,MAAOC,UAC9BkB,IAAMlB,KACNmB,SAAW,GACf5B,EAAEO,KAAK,CAAC,WAAY,QAAS,SAAU,SAAU,aAAc,gBAAgB,SAASmB,EAAGG,QAChE,IAAZpB,KAAKoB,IAAkC,KAAZpB,KAAKoB,KACvCF,IAAIG,aAAc,EAClBF,SAASlB,KAAKD,KAAKoB,QAG3BF,IAAIC,SAAWA,SAASG,KAAK,MAC7BN,SAASf,KAAKR,UAAU8B,OAAO,wCAAyCL,SAIrE3B,EAAEiC,KAAKC,MAAMlC,EAAEiC,KAAMR,UAAUD,MAAK,eACnCD,KAAOY,UACXnC,EAAEO,KAAKF,QAAQC,OAAO,SAASE,MAAOC,MAClCA,KAAKK,OAASS,KAAKG,GACnBA,OAEJT,QAAQZ,QAAQC,aAIrB8B,MAAMlB"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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)}}}));
//# sourceMappingURL=form_competency_element.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}}}));
//# sourceMappingURL=frameworkactions.min.js.map
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
/**
* 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)}}}));
//# sourceMappingURL=frameworks_datasource.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"frameworks_datasource.min.js","sources":["../src/frameworks_datasource.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Frameworks datasource.\n *\n * This module is compatible with core/form-autocomplete.\n *\n * @module tool_lp/frameworks_datasource\n * @copyright 2016 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery', 'core/ajax', 'core/notification'], function($, Ajax, Notification) {\n\n return /** @alias module:tool_lpmigrate/frameworks_datasource */ {\n\n /**\n * List frameworks.\n *\n * @param {Number} contextId The context ID.\n * @param {Object} options Additional parameters to pass to the external function.\n * @return {Promise}\n */\n list: function(contextId, options) {\n var args = {\n context: {\n contextid: contextId\n }\n };\n\n $.extend(args, typeof options === 'undefined' ? {} : options);\n return Ajax.call([{\n methodname: 'core_competency_list_competency_frameworks',\n args: args\n }])[0];\n },\n\n /**\n * Process the results for auto complete elements.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {Array} results An array or results.\n * @return {Array} New array of results.\n */\n processResults: function(selector, results) {\n var options = [];\n $.each(results, function(index, data) {\n options.push({\n value: data.id,\n label: data.shortname + ' ' + data.idnumber\n });\n });\n return options;\n },\n\n /**\n * Source of data for Ajax element.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {String} query The query string.\n * @param {Function} callback A callback function receiving an array of results.\n */\n /* eslint-disable promise/no-callback-in-promise */\n transport: function(selector, query, callback) {\n var el = $(selector),\n contextId = el.data('contextid'),\n onlyVisible = el.data('onlyvisible');\n\n if (!contextId) {\n throw new Error('The attribute data-contextid is required on ' + selector);\n }\n this.list(contextId, {\n query: query,\n onlyvisible: onlyVisible,\n }).then(callback).catch(Notification.exception);\n }\n };\n\n});\n"],"names":["define","$","Ajax","Notification","list","contextId","options","args","context","contextid","extend","call","methodname","processResults","selector","results","each","index","data","push","value","id","label","shortname","idnumber","transport","query","callback","el","onlyVisible","Error","onlyvisible","then","catch","exception"],"mappings":";;;;;;;;;AAyBAA,uCAAO,CAAC,SAAU,YAAa,sBAAsB,SAASC,EAAGC,KAAMC,oBAEF,CAS7DC,KAAM,SAASC,UAAWC,aAClBC,KAAO,CACHC,QAAS,CACLC,UAAWJ,mBAIvBJ,EAAES,OAAOH,UAAyB,IAAZD,QAA0B,GAAKA,SAC9CJ,KAAKS,KAAK,CAAC,CACdC,WAAY,6CACZL,KAAMA,QACN,IAURM,eAAgB,SAASC,SAAUC,aAC3BT,QAAU,UACdL,EAAEe,KAAKD,SAAS,SAASE,MAAOC,MAC5BZ,QAAQa,KAAK,CACTC,MAAOF,KAAKG,GACZC,MAAOJ,KAAKK,UAAY,IAAML,KAAKM,cAGpClB,SAWXmB,UAAW,SAASX,SAAUY,MAAOC,cAC7BC,GAAK3B,EAAEa,UACPT,UAAYuB,GAAGV,KAAK,aACpBW,YAAcD,GAAGV,KAAK,mBAErBb,gBACK,IAAIyB,MAAM,+CAAiDhB,eAEhEV,KAAKC,UAAW,CACjBqB,MAAOA,MACPK,YAAaF,cACdG,KAAKL,UAAUM,MAAM9B,aAAa+B"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=grade_dialogue.min.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=grade_user_competency_inline.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=module_navigation.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"module_navigation.min.js","sources":["../src/module_navigation.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Module to navigation between users in a course.\n *\n * @module tool_lp/module_navigation\n * @copyright 2019 Damyon Wiese\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery'], function($) {\n\n /**\n * ModuleNavigation\n *\n * @class tool_lp/module_navigation\n * @param {String} moduleSelector The selector of the module element.\n * @param {String} baseUrl The base url for the page (no params).\n * @param {Number} courseId The course id\n * @param {Number} moduleId The activity module (filter)\n */\n var ModuleNavigation = function(moduleSelector, baseUrl, courseId, moduleId) {\n this._baseUrl = baseUrl;\n this._moduleId = moduleId;\n this._courseId = courseId;\n\n $(moduleSelector).on('change', this._moduleChanged.bind(this));\n };\n\n /**\n * The module was changed in the select list.\n *\n * @method _moduleChanged\n * @param {Event} e the event\n */\n ModuleNavigation.prototype._moduleChanged = function(e) {\n var newModuleId = $(e.target).val();\n var queryStr = '?mod=' + newModuleId + '&courseid=' + this._courseId;\n document.location = this._baseUrl + queryStr;\n };\n\n /** @property {Number} The id of the course. */\n ModuleNavigation.prototype._courseId = null;\n /** @property {Number} The id of the module. */\n ModuleNavigation.prototype._moduleId = null;\n /** @property {String} Plugin base url. */\n ModuleNavigation.prototype._baseUrl = null;\n\n return ModuleNavigation;\n});\n"],"names":["define","$","ModuleNavigation","moduleSelector","baseUrl","courseId","moduleId","_baseUrl","_moduleId","_courseId","on","this","_moduleChanged","bind","prototype","e","queryStr","target","val","document","location"],"mappings":";;;;;;;AAuBAA,mCAAO,CAAC,WAAW,SAASC,OAWpBC,iBAAmB,SAASC,eAAgBC,QAASC,SAAUC,eAC1DC,SAAWH,aACXI,UAAYF,cACZG,UAAYJ,SAEjBJ,EAAEE,gBAAgBO,GAAG,SAAUC,KAAKC,eAAeC,KAAKF,eAS5DT,iBAAiBY,UAAUF,eAAiB,SAASG,OAE7CC,SAAW,QADGf,EAAEc,EAAEE,QAAQC,MACS,aAAeP,KAAKF,UAC3DU,SAASC,SAAWT,KAAKJ,SAAWS,UAIxCd,iBAAiBY,UAAUL,UAAY,KAEvCP,iBAAiBY,UAAUN,UAAY,KAEvCN,iBAAiBY,UAAUP,SAAW,KAE/BL"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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)}}}));
//# sourceMappingURL=parentcompetency_form.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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&&currentconfig.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)}}}));
//# sourceMappingURL=scaleconfig.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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()}}}));
//# sourceMappingURL=scalevalues.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"scalevalues.min.js","sources":["../src/scalevalues.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Module to get the scale values.\n *\n * @module tool_lp/scalevalues\n * @copyright 2016 Serge Gauthier\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/ajax'], function($, ajax) {\n var localCache = [];\n\n return {\n\n /**\n * Return a promise object that will be resolved into a string eventually (maybe immediately).\n *\n * @method get_values\n * @param {Number} scaleid The scale id\n * @return [] {Promise}\n */\n // eslint-disable-next-line camelcase\n get_values: function(scaleid) {\n\n var deferred = $.Deferred();\n\n if (typeof localCache[scaleid] === 'undefined') {\n ajax.call([{\n methodname: 'core_competency_get_scale_values',\n args: {scaleid: scaleid},\n done: function(scaleinfo) {\n localCache[scaleid] = scaleinfo;\n deferred.resolve(scaleinfo);\n },\n fail: (deferred.reject)\n }]);\n } else {\n deferred.resolve(localCache[scaleid]);\n }\n\n return deferred.promise();\n }\n };\n});\n"],"names":["define","$","ajax","localCache","get_values","scaleid","deferred","Deferred","call","methodname","args","done","scaleinfo","resolve","fail","reject","promise"],"mappings":";;;;;;;AAsBAA,6BAAO,CAAC,SAAU,cAAc,SAASC,EAAGC,UACpCC,WAAa,SAEV,CAUHC,WAAY,SAASC,aAEbC,SAAWL,EAAEM,uBAEkB,IAAxBJ,WAAWE,SAClBH,KAAKM,KAAK,CAAC,CACPC,WAAY,mCACZC,KAAM,CAACL,QAASA,SAChBM,KAAM,SAASC,WACXT,WAAWE,SAAWO,UACtBN,SAASO,QAAQD,YAErBE,KAAOR,SAASS,UAGpBT,SAASO,QAAQV,WAAWE,UAGzBC,SAASU"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}}}));
//# sourceMappingURL=templateactions.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=user_competency_course_navigation.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"user_competency_course_navigation.min.js","sources":["../src/user_competency_course_navigation.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Module to enable inline editing of a comptency grade.\n *\n * @module tool_lp/user_competency_course_navigation\n * @copyright 2015 Damyon Wiese\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery'], function($) {\n\n /**\n * UserCompetencyCourseNavigation\n *\n * @class tool_lp/user_competency_course_navigation\n * @param {String} userSelector The selector of the user element.\n * @param {String} competencySelector The selector of the competency element.\n * @param {String} baseUrl The base url for the page (no params).\n * @param {Number} userId The user id\n * @param {Number} competencyId The competency id\n * @param {Number} courseId The course id\n */\n var UserCompetencyCourseNavigation = function(userSelector, competencySelector, baseUrl, userId, competencyId, courseId) {\n this._baseUrl = baseUrl;\n this._userId = userId + '';\n this._competencyId = competencyId + '';\n this._courseId = courseId;\n\n $(userSelector).on('change', this._userChanged.bind(this));\n $(competencySelector).on('change', this._competencyChanged.bind(this));\n };\n\n /**\n * The user was changed in the select list.\n *\n * @method _userChanged\n * @param {Event} e\n */\n UserCompetencyCourseNavigation.prototype._userChanged = function(e) {\n var newUserId = $(e.target).val();\n var queryStr = '?userid=' + newUserId + '&courseid=' + this._courseId + '&competencyid=' + this._competencyId;\n document.location = this._baseUrl + queryStr;\n };\n\n /**\n * The competency was changed in the select list.\n *\n * @method _competencyChanged\n * @param {Event} e\n */\n UserCompetencyCourseNavigation.prototype._competencyChanged = function(e) {\n var newCompetencyId = $(e.target).val();\n var queryStr = '?userid=' + this._userId + '&courseid=' + this._courseId + '&competencyid=' + newCompetencyId;\n document.location = this._baseUrl + queryStr;\n };\n\n /** @property {Number} The id of the competency. */\n UserCompetencyCourseNavigation.prototype._competencyId = null;\n /** @property {Number} The id of the user. */\n UserCompetencyCourseNavigation.prototype._userId = null;\n /** @property {Number} The id of the course. */\n UserCompetencyCourseNavigation.prototype._courseId = null;\n /** @property {String} Plugin base url. */\n UserCompetencyCourseNavigation.prototype._baseUrl = null;\n /** @property {Boolean} Ignore the first change event for competencies. */\n UserCompetencyCourseNavigation.prototype._ignoreFirstCompetency = null;\n\n return UserCompetencyCourseNavigation;\n});\n"],"names":["define","$","UserCompetencyCourseNavigation","userSelector","competencySelector","baseUrl","userId","competencyId","courseId","_baseUrl","_userId","_competencyId","_courseId","on","this","_userChanged","bind","_competencyChanged","prototype","e","queryStr","target","val","document","location","newCompetencyId","_ignoreFirstCompetency"],"mappings":";;;;;;;AAuBAA,mDAAO,CAAC,WAAW,SAASC,OAapBC,+BAAiC,SAASC,aAAcC,mBAAoBC,QAASC,OAAQC,aAAcC,eACtGC,SAAWJ,aACXK,QAAUJ,OAAS,QACnBK,cAAgBJ,aAAe,QAC/BK,UAAYJ,SAEjBP,EAAEE,cAAcU,GAAG,SAAUC,KAAKC,aAAaC,KAAKF,OACpDb,EAAEG,oBAAoBS,GAAG,SAAUC,KAAKG,mBAAmBD,KAAKF,eASpEZ,+BAA+BgB,UAAUH,aAAe,SAASI,OAEzDC,SAAW,WADCnB,EAAEkB,EAAEE,QAAQC,MACY,aAAeR,KAAKF,UAAY,iBAAmBE,KAAKH,cAChGY,SAASC,SAAWV,KAAKL,SAAWW,UASxClB,+BAA+BgB,UAAUD,mBAAqB,SAASE,OAC/DM,gBAAkBxB,EAAEkB,EAAEE,QAAQC,MAC9BF,SAAW,WAAaN,KAAKJ,QAAU,aAAeI,KAAKF,UAAY,iBAAmBa,gBAC9FF,SAASC,SAAWV,KAAKL,SAAWW,UAIxClB,+BAA+BgB,UAAUP,cAAgB,KAEzDT,+BAA+BgB,UAAUR,QAAU,KAEnDR,+BAA+BgB,UAAUN,UAAY,KAErDV,+BAA+BgB,UAAUT,SAAW,KAEpDP,+BAA+BgB,UAAUQ,uBAAyB,KAE3DxB"}
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=user_competency_info.min.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=user_competency_plan_popup.min.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* 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}));
//# sourceMappingURL=user_competency_workflow.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+198
View File
@@ -0,0 +1,198 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/ajax',
'core/templates',
'tool_lp/dialogue',
'tool_lp/event_base'],
function($, Notification, Ajax, Templates, Dialogue, EventBase) {
/**
* Action selector class.
*
* @class tool_lp/actionselector
* @param {String} title The title of popup.
* @param {String} message The message to display.
* @param {object} actions The actions that can be selected.
* @param {String} confirm Text for confirm button.
* @param {String} cancel Text for cancel button.
*/
var ActionSelector = function(title, message, actions, confirm, cancel) {
var self = this;
EventBase.prototype.constructor.apply(this, []);
self._title = title;
self._message = message;
self._actions = actions;
self._confirm = confirm;
self._cancel = cancel;
self._selectedValue = null;
self._reset();
};
ActionSelector.prototype = Object.create(EventBase.prototype);
/** @property {String} The value that was selected. */
ActionSelector.prototype._selectedValue = null;
/** @property {Dialogue} The reference to the dialogue. */
ActionSelector.prototype._popup = null;
/** @property {String} The title of popup. */
ActionSelector.prototype._title = null;
/** @property {String} The message in popup. */
ActionSelector.prototype._message = null;
/** @property {object} The information for radion buttons. */
ActionSelector.prototype._actions = null;
/** @property {String} The text for confirm button. */
ActionSelector.prototype._confirm = null;
/** @property {String} The text for cancel button. */
ActionSelector.prototype._cancel = null;
/**
* Hook to executed after the view is rendered.
*
* @method _afterRender
*/
ActionSelector.prototype._afterRender = function() {
var self = this;
// Confirm button is disabled until a choice is done.
self._find('[data-action="action-selector-confirm"]').attr('disabled', 'disabled');
// Add listener for radio buttons change.
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);
});
// Add listener for cancel.
self._find('[data-action="action-selector-cancel"]').click(function(e) {
e.preventDefault();
self.close();
});
// Add listener for confirm.
self._find('[data-action="action-selector-confirm"]').click(function(e) {
e.preventDefault();
if (!self._selectedValue.length) {
return;
}
self._trigger('save', {action: self._selectedValue});
self.close();
});
};
/**
* Close the dialogue.
*
* @method close
*/
ActionSelector.prototype.close = function() {
var self = this;
self._popup.close();
self._reset();
};
/**
* Opens the action selector.
*
* @method display
* @return {Promise}
*/
ActionSelector.prototype.display = function() {
var self = this;
return self._render().then(function(html) {
self._popup = new Dialogue(
self._title,
html,
self._afterRender.bind(self)
);
return;
}).fail(Notification.exception);
};
/**
* Find a node in the dialogue.
*
* @param {String} selector
* @return {JQuery} The node
* @method _find
*/
ActionSelector.prototype._find = function(selector) {
return $(this._popup.getContent()).find(selector);
};
/**
* Refresh the view.
*
* @method _refresh
* @return {Promise}
*/
ActionSelector.prototype._refresh = function() {
var self = this;
return self._render().then(function(html) {
self._find('[data-region="action-selector"]').replaceWith(html);
self._afterRender();
return;
});
};
/**
* Render the dialogue.
*
* @method _render
* @return {Promise}
*/
ActionSelector.prototype._render = function() {
var self = this;
var choices = [];
for (var i in self._actions) {
choices.push(self._actions[i]);
}
var content = {'message': self._message, 'choices': choices,
'confirm': self._confirm, 'cancel': self._cancel};
return Templates.render('tool_lp/action_selector', content);
};
/**
* Reset the dialogue properties.
*
* This does not reset everything, just enough to reset the UI.
*
* @method _reset
*/
ActionSelector.prototype._reset = function() {
this._popup = null;
this._selectedValue = '';
};
return ActionSelector;
});
+352
View File
@@ -0,0 +1,352 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['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) {
/**
* Constructor
*
* @class tool_lp/competencies
* @param {Number} itemid
* @param {String} itemtype
* @param {Number} pagectxid
*/
var competencies = function(itemid, itemtype, pagectxid) {
this.itemid = itemid;
this.itemtype = itemtype;
this.pageContextId = pagectxid;
this.pickerInstance = null;
$('[data-region="actions"] button').prop('disabled', false);
this.registerEvents();
this.registerDragDrop();
};
/**
* Initialise the drag/drop code.
* @method registerDragDrop
*/
competencies.prototype.registerDragDrop = function() {
var localthis = this;
// Init this module.
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);
};
/**
* Handle a drop from a drag/drop operation.
*
* @method handleDrop
* @param {DOMNode} drag The dragged node.
* @param {DOMNode} drop The dropped on node.
*/
competencies.prototype.handleDrop = function(drag, drop) {
var fromid = $(drag).data('id');
var toid = $(drop).data('id');
var localthis = this;
var requests = [];
if (localthis.itemtype == 'course') {
requests = ajax.call([
{
methodname: 'core_competency_reorder_course_competency',
args: {courseid: localthis.itemid, competencyidfrom: fromid, competencyidto: toid}
}
]);
} else if (localthis.itemtype == 'template') {
requests = ajax.call([
{
methodname: 'core_competency_reorder_template_competency',
args: {templateid: localthis.itemid, competencyidfrom: fromid, competencyidto: toid}
}
]);
} else if (localthis.itemtype == 'plan') {
requests = ajax.call([
{
methodname: 'core_competency_reorder_plan_competency',
args: {planid: localthis.itemid, competencyidfrom: fromid, competencyidto: toid}
}
]);
} else {
return;
}
requests[0].fail(notification.exception);
};
/**
* Pick a competency
*
* @method pickCompetency
* @return {Promise}
*/
competencies.prototype.pickCompetency = function() {
var self = this;
var requests;
var pagerender;
var pageregion;
var pageContextIncludes;
if (!self.pickerInstance) {
if (self.itemtype === 'template' || self.itemtype === 'course') {
pageContextIncludes = 'parents';
}
self.pickerInstance = new Picker(self.pageContextId, false, pageContextIncludes);
self.pickerInstance.on('save', function(e, data) {
var compIds = data.competencyIds;
var pendingPromise = new Pending();
if (self.itemtype === "course") {
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';
} else if (self.itemtype === "template") {
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';
} else if (self.itemtype === "plan") {
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);
return;
})
.then(pendingPromise.resolve)
.catch(notification.exception);
});
}
return self.pickerInstance.display();
};
/**
* Delete the link between competency and course, template or plan. Reload the page.
*
* @method doDelete
* @param {int} deleteid The id of record to delete.
*/
competencies.prototype.doDelete = function(deleteid) {
var localthis = this;
var requests = [],
pagerender = '',
pageregion = '';
// Delete the link and reload the page template.
if (localthis.itemtype == 'course') {
requests = ajax.call([
{methodname: 'core_competency_remove_competency_from_course',
args: {courseid: localthis.itemid, competencyid: deleteid}},
{methodname: 'tool_lp_data_for_course_competencies_page',
args: {courseid: localthis.itemid, moduleid: 0}}
]);
pagerender = 'tool_lp/course_competencies_page';
pageregion = 'coursecompetenciespage';
} else if (localthis.itemtype == 'template') {
requests = ajax.call([
{methodname: 'core_competency_remove_competency_from_template',
args: {templateid: localthis.itemid, competencyid: deleteid}},
{methodname: 'tool_lp_data_for_template_competencies_page',
args: {templateid: localthis.itemid, pagecontext: {contextid: localthis.pageContextId}}}
]);
pagerender = 'tool_lp/template_competencies_page';
pageregion = 'templatecompetenciespage';
} else if (localthis.itemtype == 'plan') {
requests = ajax.call([
{methodname: 'core_competency_remove_competency_from_plan',
args: {planid: localthis.itemid, competencyid: deleteid}},
{methodname: 'tool_lp_data_for_plan_page',
args: {planid: localthis.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);
};
/**
* Show a confirm dialogue before deleting a competency.
*
* @method deleteHandler
* @param {int} deleteid The id of record to delete.
*/
competencies.prototype.deleteHandler = function(deleteid) {
var localthis = this;
var requests = [];
var message;
if (localthis.itemtype == 'course') {
message = 'unlinkcompetencycourse';
} else if (localthis.itemtype == 'template') {
message = 'unlinkcompetencytemplate';
} else if (localthis.itemtype == 'plan') {
message = 'unlinkcompetencyplan';
} else {
return;
}
requests = ajax.call([{
methodname: 'core_competency_read_competency',
args: {id: deleteid}
}]);
requests[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], // Confirm.
strings[1], // Unlink the competency X from the course?
strings[2], // Confirm.
strings[3], // Cancel.
function() {
localthis.doDelete(deleteid);
}
);
}).fail(notification.exception);
}).fail(notification.exception);
};
/**
* Register the javascript event handlers for this page.
*
* @method registerEvents
*/
competencies.prototype.registerEvents = function() {
var localthis = this;
if (localthis.itemtype == 'course') {
// Course completion rule handling.
$('[data-region="coursecompetenciespage"]').on('change', 'select[data-field="ruleoutcome"]', function(e) {
var pendingPromise = new Pending();
var requests = [];
var pagerender = 'tool_lp/course_competencies_page';
var pageregion = 'coursecompetenciespage';
var coursecompetencyid = $(e.target).data('id');
var ruleoutcome = $(e.target).val();
requests = 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}}
]);
requests[1].then(function(context) {
return templates.render(pagerender, context);
})
.then(function(html, js) {
return templates.replaceNode($('[data-region="' + pageregion + '"]'), 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);
});
};
return /** @alias module:tool_lp/competencies */ competencies;
});
@@ -0,0 +1,82 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/str'],
function($, Str) {
var OUTCOME_NONE = 0,
OUTCOME_EVIDENCE = 1,
OUTCOME_COMPLETE = 2,
OUTCOME_RECOMMEND = 3;
return {
NONE: OUTCOME_NONE,
EVIDENCE: OUTCOME_EVIDENCE,
COMPLETE: OUTCOME_COMPLETE,
RECOMMEND: OUTCOME_RECOMMEND,
/**
* Get all the outcomes.
*
* @return {Object} Indexed by outcome code, contains code and name.
* @method getAll
*/
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 = {};
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]};
return outcomes;
});
},
/**
* Get the string for an outcome.
*
* @param {Number} id The outcome code.
* @return {Promise} Resolved with the string.
* @method getString
*/
getString: function(id) {
var self = this,
all = self.getAll();
return all.then(function(outcomes) {
if (typeof outcomes[id] === 'undefined') {
return $.Deferred().reject().promise();
}
return outcomes[id].name;
});
}
};
});
@@ -0,0 +1,74 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery'], function($) {
/**
* CompetencyPlanNavigation
*
* @class
* @param {String} competencySelector The selector of the competency element.
* @param {String} baseUrl The base url for the page (no params).
* @param {Number} userId The user id
* @param {Number} competencyId The competency id
* @param {Number} planId The plan id
*/
var CompetencyPlanNavigation = function(competencySelector, baseUrl, userId, competencyId, planId) {
this._baseUrl = baseUrl;
this._userId = userId + '';
this._competencyId = competencyId + '';
this._planId = planId;
this._ignoreFirstCompetency = true;
$(competencySelector).on('change', this._competencyChanged.bind(this));
};
/**
* The competency was changed in the select list.
*
* @method _competencyChanged
* @param {Event} e
*/
CompetencyPlanNavigation.prototype._competencyChanged = function(e) {
if (this._ignoreFirstCompetency) {
this._ignoreFirstCompetency = false;
return;
}
var newCompetencyId = $(e.target).val();
var queryStr = '?userid=' + this._userId + '&planid=' + this._planId + '&competencyid=' + newCompetencyId;
document.location = this._baseUrl + queryStr;
};
/** @property {Number} The id of the competency. */
CompetencyPlanNavigation.prototype._competencyId = null;
/** @property {Number} The id of the user. */
CompetencyPlanNavigation.prototype._userId = null;
/** @property {Number} The id of the plan. */
CompetencyPlanNavigation.prototype._planId = null;
/** @property {String} Plugin base url. */
CompetencyPlanNavigation.prototype._baseUrl = null;
/** @property {Boolean} Ignore the first change event for competencies. */
CompetencyPlanNavigation.prototype._ignoreFirstCompetency = null;
return CompetencyPlanNavigation;
});
+174
View File
@@ -0,0 +1,174 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Competency rule base module.
*
* @module tool_lp/competency_rule
* @copyright 2015 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery'], function($) {
/**
* Competency rule abstract class.
*
* Any competency rule should extend this object. The event 'change' should be
* triggered on the instance when the configuration has changed. This will allow
* the components using the rule to gather the config, or check its validity.
*
* this._triggerChange();
*
* @param {Tree} tree The competency tree.
*/
var Rule = function(tree) {
this._eventNode = $('<div>');
this._ready = $.Deferred();
this._tree = tree;
};
/** @property {Object} The current competency. */
Rule.prototype._competency = null;
/** @property {Node} The node we attach the events to. */
Rule.prototype._eventNode = null;
/** @property {Promise} Resolved when the object is ready. */
Rule.prototype._ready = null;
/** @property {Tree} The competency tree. */
Rule.prototype._tree = null;
/**
* Whether or not the current competency can be configured using this rule.
*
* @return {Boolean}
* @method canConfig
*/
Rule.prototype.canConfig = function() {
return this._tree.hasChildren(this._competency.id);
};
/**
* The config established by this rule.
*
* To override in subclasses when relevant.
*
* @return {String|null}
* @method getConfig
*/
Rule.prototype.getConfig = function() {
return null;
};
/**
* Return the type of the module.
*
* @return {String}
* @method getType
*/
Rule.prototype.getType = function() {
throw new Error('Not implemented');
};
/**
* The init process.
*
* Do not override this, instead override _load.
*
* @return {Promise} Revoled when the plugin is initialised.
* @method init
*/
Rule.prototype.init = function() {
return this._load();
};
/**
* Callback to inject the template.
*
* @returns {Promise} Resolved when done.
* @method injectTemplate
*/
Rule.prototype.injectTemplate = function() {
return $.Deferred().reject().promise();
};
/**
* Whether or not the current config is valid.
*
* Plugins should override this.
*
* @return {Boolean}
* @method _isValid
*/
Rule.prototype.isValid = function() {
return false;
};
/**
* Load the class.
*
* @return {Promise}
* @method _load
* @protected
*/
Rule.prototype._load = function() {
return $.when();
};
/**
* Register an event listener.
*
* @param {String} type The event type.
* @param {Function} handler The event listener.
* @method on
*/
Rule.prototype.on = function(type, handler) {
this._eventNode.on(type, handler);
};
/**
* Sets the current competency.
*
* @param {Competency} competency
* @method setTargetCompetency
*/
Rule.prototype.setTargetCompetency = function(competency) {
this._competency = competency;
};
/**
* Trigger an event.
*
* @param {String} type The type of event.
* @param {Object} data The data to pass to the listeners.
* @method _trigger
* @protected
*/
Rule.prototype._trigger = function(type, data) {
this._eventNode.trigger(type, [data]);
};
/**
* Trigger the change event.
*
* @method _triggerChange
* @protected
*/
Rule.prototype._triggerChange = function() {
this._trigger('change', this);
};
return /** @alias module:tool_lp/competency_rule */ Rule;
});
@@ -0,0 +1,61 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/str',
'tool_lp/competency_rule',
],
function($, Str, RuleBase) {
/**
* Competency rule all class.
*
* @class tool_lp/competency_rule_all
*/
var Rule = function() {
RuleBase.apply(this, arguments);
};
Rule.prototype = Object.create(RuleBase.prototype);
/**
* Return the type of the module.
*
* @return {String}
* @method getType
*/
Rule.prototype.getType = function() {
return 'core_competency\\competency_rule_all';
};
/**
* Whether or not the current config is valid.
*
* @return {Boolean}
* @method isValid
*/
Rule.prototype.isValid = function() {
return true;
};
return Rule;
});
@@ -0,0 +1,200 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Competency rule points module.
*
* @module tool_lp/competency_rule_points
* @copyright 2015 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery',
'core/str',
'core/templates',
'tool_lp/competency_rule',
],
function($, Str, Templates, RuleBase) {
/**
* Competency rule points class.
*/
var Rule = function() {
RuleBase.apply(this, arguments);
};
Rule.prototype = Object.create(RuleBase.prototype);
/** @property {Node} Reference to the container in which the template was included. */
Rule.prototype._container = null;
/** @property {Boolean} Whether or not the template was included. */
Rule.prototype._templateLoaded = false;
/**
* The config established by this rule.
*
* @return {String}
* @method getConfig
*/
Rule.prototype.getConfig = function() {
return JSON.stringify({
base: {
points: this._getRequiredPoints(),
},
competencies: this._getCompetenciesConfig()
});
};
/**
* Gathers the input provided by the user for competencies.
*
* @return {Array} Containing id, points and required.
* @method _getCompetenciesConfig
* @protected
*/
Rule.prototype._getCompetenciesConfig = function() {
var competencies = [];
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
});
});
return competencies;
};
/**
* Fetches the required points set by the user.
*
* @return {Number}
* @method _getRequiredPoints
* @protected
*/
Rule.prototype._getRequiredPoints = function() {
return parseInt(this._container.find('[name="requiredpoints"]').val() || 1, 10);
};
/**
* Return the type of the module.
*
* @return {String}
* @method getType
*/
Rule.prototype.getType = function() {
return 'core_competency\\competency_rule_points';
};
/**
* Callback to inject the template.
*
* @param {Node} container Node to inject in.
* @return {Promise} Resolved when done.
* @method injectTemplate
*/
Rule.prototype.injectTemplate = function(container) {
var self = this,
children = this._tree.getChildren(this._competency.id),
context,
config = {
base: {points: 2},
competencies: []
};
this._templateLoaded = false;
// Only pre-load the configuration when the competency is using this rule.
if (self._competency.ruletype == self.getType()) {
try {
config = JSON.parse(self._competency.ruleconfig);
} catch (e) {
// eslint-disable-line no-empty
}
}
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: false,
points: 0
};
if (config) {
$.each(config.competencies, function(index, comp) {
if (comp.id == competency.id) {
competency.required = comp.required ? true : false;
competency.points = comp.points;
}
});
}
context.children.push(competency);
});
return Templates.render('tool_lp/competency_rule_points', context).then(function(html) {
self._container = container;
container.html(html);
container.find('input').change(function() {
self._triggerChange();
});
// We're done, let's trigger a change.
self._templateLoaded = true;
self._triggerChange();
return;
});
};
/**
* Whether or not the current config is valid.
*
* @return {Boolean}
* @method isValid
*/
Rule.prototype.isValid = function() {
if (!this._templateLoaded) {
return false;
}
var required = this._getRequiredPoints(),
max = 0,
valid = true;
$.each(this._getCompetenciesConfig(), function(index, competency) {
if (competency.points < 0) {
valid = false;
}
max += competency.points;
});
valid = valid && max >= required;
return valid;
};
return Rule;
});
+867
View File
@@ -0,0 +1,867 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['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
) {
// Private variables and functions.
/** @var {Object} treeModel - This is an object representing the nodes in the tree. */
var treeModel = null;
/** @var {Node} moveSource - The start of a drag operation */
var moveSource = null;
/** @var {Node} moveTarget - The end of a drag operation */
var moveTarget = null;
/** @var {Number} pageContextId The page context ID. */
var pageContextId;
/** @var {Object} Picker instance. */
var pickerInstance;
/** @var {Object} Rule config instance. */
var ruleConfigInstance;
/** @var {Object} The competency we're picking a relation to. */
var relatedTarget;
/** @var {Object} Taxonomy constants indexed per level. */
var taxonomiesConstants;
/** @var {Array} The rules modules. Values are object containing type, namd and amd. */
var rulesModules;
/** @var {Number} the selected competency ID. */
var selectedCompetencyId = null;
/**
* Respond to choosing the "Add" menu item for the selected node in the tree.
* @method addHandler
*/
var addHandler = function() {
var parent = $('[data-region="competencyactions"]').data('competency');
var params = {
competencyframeworkid: treeModel.getCompetencyFrameworkId(),
pagecontextid: pageContextId
};
if (parent !== null) {
// We are adding at a sub node.
params.parentid = parent.id;
}
var relocate = function() {
var queryparams = $.param(params);
window.location = url.relativeUrl('/admin/tool/lp/editcompetency.php?' + queryparams);
};
if (parent !== null && 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);
} else {
relocate();
}
};
/**
* A source and destination has been chosen - so time to complete a move.
* @method doMove
*/
var doMove = function() {
var frameworkid = $('[data-region="filtercompetencies"]').data('frameworkid');
var requests = 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()}
}]);
requests[1].done(reloadPage).fail(notification.exception);
};
/**
* Confirms a competency move.
*
* @method confirmMove
*/
var confirmMove = function() {
moveTarget = typeof moveTarget === "undefined" ? 0 : moveTarget;
if (moveTarget == moveSource) {
// No move to do.
return;
}
var targetComp = treeModel.getCompetency(moveTarget) || {},
sourceComp = treeModel.getCompetency(moveSource) || {},
confirmMessage = 'movecompetencywillresetrules',
showConfirm = false;
// We shouldn't be moving the competency to the same parent.
if (sourceComp.parentid == moveTarget) {
return;
}
// If we are moving to a child of self.
if (targetComp.path && targetComp.path.indexOf('/' + sourceComp.id + '/') >= 0) {
confirmMessage = 'movecompetencytochildofselfwillresetrules';
// Show a confirmation if self has rules, as they'll disappear.
showConfirm = showConfirm || treeModel.hasRule(sourceComp.id);
}
// Show a confirmation if the current parent, or the destination have rules.
showConfirm = showConfirm || (treeModel.hasRule(targetComp.id) || treeModel.hasRule(sourceComp.parentid));
// Show confirm, and/or do the things.
if (showConfirm) {
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], // Confirm.
strings[1], // Delete competency X?
strings[2], // Delete.
strings[3], // Cancel.
doMove
);
}).fail(notification.exception);
} else {
doMove();
}
};
/**
* A move competency popup was opened - initialise the aria tree in it.
* @method initMovePopup
* @param {dialogue} popup The tool_lp/dialogue that was created.
*/
var initMovePopup = function(popup) {
var body = $(popup.getContent());
var treeRoot = body.find('[data-enhance=movetree]');
var tree = new Ariatree(treeRoot, false);
tree.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();
});
};
/**
* Turn a flat list of competencies into a tree structure (recursive).
* @method addCompetencyChildren
* @param {Object} parent The current parent node in the tree
* @param {Object[]} competencies The flat list of competencies
*/
var addCompetencyChildren = function(parent, competencies) {
var i;
for (i = 0; i < competencies.length; i++) {
if (competencies[i].parentid == parent.id) {
parent.haschildren = true;
competencies[i].children = [];
competencies[i].haschildren = false;
parent.children[parent.children.length] = competencies[i];
addCompetencyChildren(competencies[i], competencies);
}
}
};
/**
* A node was chosen and "Move" was selected from the menu. Open a popup to select the target.
* @param {Event} e
* @method moveHandler
*/
var moveHandler = function(e) {
e.preventDefault();
var competency = $('[data-region="competencyactions"]').data('competency');
// Remember what we are moving.
moveSource = competency.id;
// Load data for the template.
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 all data has arrived, continue.
$.when.apply(null, requests).done(function(competencies, framework) {
// Expand the list of competencies into a tree.
var i;
var competenciestree = [];
for (i = 0; i < competencies.length; i++) {
var onecompetency = competencies[i];
if (onecompetency.parentid == "0") {
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], // Move competency x.
tree, // The move tree.
initMovePopup
);
}).fail(notification.exception);
}).fail(notification.exception);
}).fail(notification.exception);
};
/**
* Edit the selected competency.
* @method editHandler
*/
var editHandler = function() {
var competency = $('[data-region="competencyactions"]').data('competency');
var params = {
competencyframeworkid: treeModel.getCompetencyFrameworkId(),
id: competency.id,
parentid: competency.parentid,
pagecontextid: pageContextId
};
var queryparams = $.param(params);
window.location = url.relativeUrl('/admin/tool/lp/editcompetency.php?' + queryparams);
};
/**
* Re-render the page with the latest data.
* @param {Object} context
* @method reloadPage
*/
var 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);
};
/**
* Perform a search and render the page with the new search results.
* @param {Event} e
* @method updateSearchHandler
*/
var updateSearchHandler = function(e) {
e.preventDefault();
var frameworkid = $('[data-region="filtercompetencies"]').data('frameworkid');
var requests = ajax.call([{
methodname: 'tool_lp_data_for_competencies_manage_page',
args: {competencyframeworkid: frameworkid,
search: $('[data-region="filtercompetencies"] input').val()}
}]);
requests[0].done(reloadPage).fail(notification.exception);
};
/**
* Move a competency "up". This only affects the sort order within the same branch of the tree.
* @method moveUpHandler
*/
var moveUpHandler = function() {
// We are chaining ajax requests here.
var competency = $('[data-region="competencyactions"]').data('competency');
var requests = 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()}
}]);
requests[1].done(reloadPage).fail(notification.exception);
};
/**
* Move a competency "down". This only affects the sort order within the same branch of the tree.
* @method moveDownHandler
*/
var moveDownHandler = function() {
// We are chaining ajax requests here.
var competency = $('[data-region="competencyactions"]').data('competency');
var requests = 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()}
}]);
requests[1].done(reloadPage).fail(notification.exception);
};
/**
* Open a dialogue to show all the courses using the selected competency.
* @method seeCoursesHandler
*/
var seeCoursesHandler = function() {
var competency = $('[data-region="competencyactions"]').data('competency');
var requests = ajax.call([{
methodname: 'tool_lp_list_courses_using_competency',
args: {id: competency.id}
}]);
requests[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, // Title.
html, // The linked courses.
initMovePopup
);
}).fail(notification.exception);
}).fail(notification.exception);
}).fail(notification.exception);
};
/**
* Open a competencies popup to relate competencies.
*
* @method relateCompetenciesHandler
*/
var relateCompetenciesHandler = function() {
relatedTarget = $('[data-region="competencyactions"]').data('competency');
if (!pickerInstance) {
pickerInstance = new Picker(pageContextId, relatedTarget.competencyframeworkid);
pickerInstance.on('save', function(e, data) {
var pendingPromise = new Pending();
var compIds = data.competencyIds;
var 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}
});
var promises = ajax.call(calls);
promises[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();
return;
})
.then(pendingPromise.resolve)
.catch(notification.exception);
});
}
pickerInstance.setDisallowedCompetencyIDs([relatedTarget.id]);
pickerInstance.display();
};
var ruleConfigHandler = function(e) {
e.preventDefault();
relatedTarget = $('[data-region="competencyactions"]').data('competency');
ruleConfigInstance.setTargetCompetencyId(relatedTarget.id);
ruleConfigInstance.display();
};
var 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
};
var promise = ajax.call([{
methodname: 'core_competency_update_competency',
args: {competency: update}
}]);
promise[0].then(function(result) {
if (result) {
relatedTarget.ruletype = config.ruletype;
relatedTarget.ruleoutcome = config.ruleoutcome;
relatedTarget.ruleconfig = config.ruleconfig;
renderCompetencySummary(relatedTarget);
}
return;
}).catch(notification.exception);
};
/**
* Delete a competency.
* @method doDelete
*/
var doDelete = function() {
// We are chaining ajax requests here.
var competency = $('[data-region="competencyactions"]').data('competency');
var 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) {
if (success === false) {
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);
};
/**
* Show a confirm dialogue before deleting a competency.
* @method deleteCompetencyHandler
*/
var deleteCompetencyHandler = function() {
var competency = $('[data-region="competencyactions"]').data('competency'),
confirmMessage = 'deletecompetency';
if (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], // Confirm.
strings[1], // Delete competency X?
strings[2], // Delete.
strings[3], // Cancel.
doDelete
);
}).fail(notification.exception);
};
/**
* HTML5 implementation of drag/drop (there is an accesible alternative in the menus).
* @method dragStart
* @param {Event} e
*/
var dragStart = function(e) {
e.originalEvent.dataTransfer.setData('text', $(e.target).parent().data('id'));
};
/**
* HTML5 implementation of drag/drop (there is an accesible alternative in the menus).
* @method allowDrop
* @param {Event} e
*/
var allowDrop = function(e) {
e.originalEvent.dataTransfer.dropEffect = 'move';
e.preventDefault();
};
/**
* HTML5 implementation of drag/drop (there is an accesible alternative in the menus).
* @method dragEnter
* @param {Event} e
*/
var dragEnter = function(e) {
e.preventDefault();
$(this).addClass('currentdragtarget');
};
/**
* HTML5 implementation of drag/drop (there is an accesible alternative in the menus).
* @method dragLeave
* @param {Event} e
*/
var dragLeave = function(e) {
e.preventDefault();
$(this).removeClass('currentdragtarget');
};
/**
* HTML5 implementation of drag/drop (there is an accesible alternative in the menus).
* @method dropOver
* @param {Event} e
*/
var dropOver = function(e) {
e.preventDefault();
moveSource = e.originalEvent.dataTransfer.getData('text');
moveTarget = $(e.target).parent().data('id');
$(this).removeClass('currentdragtarget');
confirmMove();
};
/**
* Deletes a related competency without confirmation.
*
* @param {Event} e The event that triggered the action.
* @method deleteRelatedHandler
*/
var deleteRelatedHandler = function(e) {
e.preventDefault();
var relatedid = this.id.substr(11);
var competency = $('[data-region="competencyactions"]').data('competency');
var removeRelated = 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}}
]);
removeRelated[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);
};
/**
* Updates the competencies list (with relations) and add listeners.
*
* @method updatedRelatedCompetencies
*/
var updatedRelatedCompetencies = function() {
// Listeners to newly loaded related competencies.
$('[data-action="deleterelation"]').on('click', deleteRelatedHandler);
};
/**
* Log the competency viewed event.
*
* @param {Object} competency The competency.
* @method triggerCompetencyViewedEvent
*/
var triggerCompetencyViewedEvent = function(competency) {
if (competency.id !== selectedCompetencyId) {
// Set the selected competency id.
selectedCompetencyId = competency.id;
ajax.call([{
methodname: 'core_competency_competency_viewed',
args: {id: competency.id}
}]);
}
};
/**
* Return the taxonomy constant for a level.
*
* @param {Number} level The level.
* @return {String}
* @function getTaxonomyAtLevel
*/
var getTaxonomyAtLevel = function(level) {
var constant = taxonomiesConstants[level];
if (!constant) {
constant = 'competency';
}
return constant;
};
/**
* Render the competency summary.
*
* @param {Object} competency The competency.
*/
var renderCompetencySummary = function(competency) {
var promise = $.Deferred().resolve().promise(),
context = {};
context.competency = competency;
context.showdeleterelatedaction = true;
context.showrelatedcompetencies = true;
context.showrule = false;
context.pluginbaseurl = url.relativeUrl('/admin/tool/lp');
if (competency.ruleoutcome != Outcomes.NONE) {
// Get the outcome and rule name.
promise = Outcomes.getString(competency.ruleoutcome).then(function(str) {
var name;
$.each(rulesModules, function(index, modInfo) {
if (modInfo.type == competency.ruletype) {
name = modInfo.name;
}
});
return [str, name];
});
}
promise.then(function(strs) {
if (typeof strs !== 'undefined') {
context.showrule = true;
context.rule = {
outcome: strs[0],
type: strs[1]
};
}
return context;
}).then(function(context) {
return templates.render('tool_lp/competency_summary', context);
}).then(function(html) {
$('[data-region="competencyinfo"]').html(html);
$('[data-action="deleterelation"]').on('click', deleteRelatedHandler);
return templates.render('tool_lp/loading', {});
}).then(function(html, js) {
templates.replaceNodeContents('[data-region="relatedcompetencies"]', html, js);
return 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();
return;
}).catch(notification.exception);
};
/**
* Return the string "Add <taxonomy>".
*
* @param {Number} level The level.
* @return {String}
* @function strAddTaxonomy
*/
var strAddTaxonomy = function(level) {
return str.get_string('taxonomy_add_' + getTaxonomyAtLevel(level), 'tool_lp');
};
/**
* Return the string "Selected <taxonomy>".
*
* @param {Number} level The level.
* @return {String}
* @function strSelectedTaxonomy
*/
var strSelectedTaxonomy = function(level) {
return str.get_string('taxonomy_selected_' + getTaxonomyAtLevel(level), 'tool_lp');
};
/**
* Handler when a node in the aria tree is selected.
* @method selectionChanged
* @param {Event} evt The event that triggered the selection change.
* @param {Object} params The parameters for the event. Contains a list of selected nodes.
* @return {Boolean}
*/
var 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;
menubar.closeAll();
if (typeof id === "undefined") {
// Assume this is the root of the tree.
// Here we are only getting the text from the top of the tree, to do it we clone the tree,
// remove all children and then call text on the result.
$('[data-region="competencyinfo"]').html(node.clone().children().remove().end().text());
$('[data-region="competencyactions"]').data('competency', null);
actionMenu.hide();
} else {
var competency = treeModel.getCompetency(id);
level = treeModel.getCompetencyLevel(id);
sublevel = level + 1;
actionMenu.show();
$('[data-region="competencyactions"]').data('competency', competency);
renderCompetencySummary(competency);
// Log Competency viewed event.
triggerCompetencyViewedEvent(competency);
}
strSelectedTaxonomy(level).then(function(str) {
selectedTitle.text(str);
return;
}).catch(notification.exception);
strAddTaxonomy(sublevel).then(function(str) {
btn.show()
.find('[data-region="term"]')
.text(str);
return;
}).catch(notification.exception);
// We handled this event so consume it.
evt.preventDefault();
return false;
};
/**
* Return the string "Selected <taxonomy>".
*
* @function parseTaxonomies
* @param {String} taxonomiesstr Comma separated list of taxonomies.
* @return {Array} of level => taxonomystr
*/
var parseTaxonomies = function(taxonomiesstr) {
var all = taxonomiesstr.split(',');
all.unshift("");
delete all[0];
// Note we don't need to fill holes, because other functions check for empty anyway.
return all;
};
return {
/**
* Initialise this page (attach event handlers etc).
*
* @method init
* @param {Object} model The tree model provides some useful functions for loading and searching competencies.
* @param {Number} pagectxid The page context ID.
* @param {Object} taxonomies Constants indexed by level.
* @param {Object} rulesMods The modules of the rules.
*/
init: function(model, pagectxid, taxonomies, rulesMods) {
treeModel = model;
pageContextId = pagectxid;
taxonomiesConstants = parseTaxonomies(taxonomies);
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);
// Simple html5 drag drop because we already added an accessible alternative.
var top = $('[data-region="managecompetencies"] [data-enhance="tree"]');
top.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);
// Prepare the configuration tool.
ruleConfigInstance = new RuleConfig(treeModel, rulesModules);
ruleConfigInstance.on('save', ruleConfigSaveHandler.bind(this));
}
};
});
+173
View File
@@ -0,0 +1,173 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/ajax',
'core/templates',
'core/str',
'tool_lp/dialogue'],
function($, notification, ajax, templates, str, Dialogue) {
/**
* The main instance we'll be working with.
*
* @type {Competencydialogue}
*/
var instance;
/**
* Constructor for CompetencyDialogue.
*/
var Competencydialogue = function() {
// Intentionally left empty.
};
/**
* Log the competency viewed event.
*
* @param {Number} competencyId The competency ID.
* @method triggerCompetencyViewedEvent
*/
Competencydialogue.prototype.triggerCompetencyViewedEvent = function(competencyId) {
ajax.call([{
methodname: 'core_competency_competency_viewed',
args: {id: competencyId}
}]);
};
/**
* Display a dialogue box by competencyid.
*
* @param {Number} competencyid The competency ID.
* @param {Object} options The options.
* @method showDialogue
*/
Competencydialogue.prototype.showDialogue = function(competencyid, options) {
var datapromise = this.getCompetencyDataPromise(competencyid, options);
var localthis = this;
datapromise.done(function(data) {
// Inner Html in the dialogue content.
templates.render('tool_lp/competency_summary', data)
.done(function(html) {
// Log competency viewed event.
localthis.triggerCompetencyViewedEvent(competencyid);
// Show the dialogue.
new Dialogue(
data.competency.shortname,
html
);
}).fail(notification.exception);
}).fail(notification.exception);
};
/**
* Display a dialogue box from data.
*
* @param {Object} dataSource data to be used to display dialogue box
* @method showDialogueFromData
*/
Competencydialogue.prototype.showDialogueFromData = function(dataSource) {
var localthis = this;
// Inner Html in the dialogue content.
templates.render('tool_lp/competency_summary', dataSource)
.done(function(html) {
// Log competency viewed event.
localthis.triggerCompetencyViewedEvent(dataSource.id);
// Show the dialogue.
new Dialogue(
dataSource.shortname,
html,
localthis.enhanceDialogue
);
}).fail(notification.exception);
};
/**
* The action on the click event.
*
* @param {Event} e event click
* @method clickEventHandler
*/
Competencydialogue.prototype.clickEventHandler = function(e) {
var compdialogue = e.data.compdialogue;
var currentTarget = $(e.currentTarget);
var competencyid = currentTarget.data('id');
var includerelated = !(currentTarget.data('excluderelated'));
var includecourses = currentTarget.data('includecourses');
// Show the dialogue box.
compdialogue.showDialogue(competencyid, {
includerelated: includerelated,
includecourses: includecourses
});
e.preventDefault();
};
/**
* Get a promise on data competency.
*
* @param {Number} competencyid
* @param {Object} options
* @return {Promise} return promise on data request
* @method getCompetencyDataPromise
*/
Competencydialogue.prototype.getCompetencyDataPromise = function(competencyid, options) {
var requests = ajax.call([
{methodname: 'tool_lp_data_for_competency_summary',
args: {competencyid: competencyid,
includerelated: options.includerelated || false,
includecourses: options.includecourses || false
}
}
]);
return requests[0].then(function(context) {
return context;
}).fail(notification.exception);
};
return /** @alias module:tool_lp/competencydialogue */ {
/**
* Initialise the competency dialogue module.
*
* Only the first call matters.
*/
init: function() {
if (typeof instance !== 'undefined') {
return;
}
// Instantiate the one instance and delegate event on the body.
instance = new Competencydialogue();
$('body').delegate('[data-action="competency-dialogue"]', 'click', {compdialogue: instance},
instance.clickEventHandler.bind(instance));
}
};
});
+473
View File
@@ -0,0 +1,473 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['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) {
/**
* Competency picker class.
* @param {Number} pageContextId The page context ID.
* @param {Number|false} singleFramework The ID of the framework when limited to one.
* @param {String} pageContextIncludes One of 'children', 'parents', 'self'.
* @param {Boolean} multiSelect Support multi-select in the tree.
*/
var Picker = function(pageContextId, singleFramework, pageContextIncludes, multiSelect) {
var self = this;
self._eventNode = $('<div></div>');
self._frameworks = [];
self._reset();
self._pageContextId = pageContextId;
self._pageContextIncludes = pageContextIncludes || 'children';
self._multiSelect = (typeof multiSelect === 'undefined' || multiSelect === true);
if (singleFramework) {
self._frameworkId = singleFramework;
self._singleFramework = true;
}
};
/** @property {Array} The competencies fetched. */
Picker.prototype._competencies = null;
/** @property {Array} The competencies that cannot be picked. */
Picker.prototype._disallowedCompetencyIDs = null;
/** @property {Node} The node we attach the events to. */
Picker.prototype._eventNode = null;
/** @property {Array} The list of frameworks fetched. */
Picker.prototype._frameworks = null;
/** @property {Number} The current framework ID. */
Picker.prototype._frameworkId = null;
/** @property {Number} The page context ID. */
Picker.prototype._pageContextId = null;
/** @property {Number} Relevant contexts inclusion. */
Picker.prototype._pageContextIncludes = null;
/** @property {Dialogue} The reference to the dialogue. */
Picker.prototype._popup = null;
/** @property {String} The string we filter the competencies with. */
Picker.prototype._searchText = '';
/** @property {Object} The competency that was selected. */
Picker.prototype._selectedCompetencies = null;
/** @property {Boolean} Whether we can browse frameworks or not. */
Picker.prototype._singleFramework = false;
/** @property {Boolean} Do we allow multi select? */
Picker.prototype._multiSelect = true;
/** @property {Boolean} Do we allow to display hidden framework? */
Picker.prototype._onlyVisible = true;
/**
* Hook to executed after the view is rendered.
*
* @method _afterRender
*/
Picker.prototype._afterRender = function() {
var self = this;
// Initialise the tree.
var tree = new Tree(self._find('[data-enhance=linktree]'), self._multiSelect);
// To prevent jiggling we only show the tree after it is enhanced.
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 = true;
if (typeof compId === 'undefined') {
// Do not allow picking nodes with no id.
valid = false;
} else {
$.each(self._disallowedCompetencyIDs, function(i, id) {
if (id == compId) {
valid = false;
}
});
}
if (valid) {
validIds.push(compId);
}
});
self._selectedCompetencies = validIds;
// TODO Implement disabling of nodes in the tree module somehow.
if (!self._selectedCompetencies.length) {
self._find('[data-region="competencylinktree"] [data-action="add"]').attr('disabled', 'disabled');
} else {
self._find('[data-region="competencylinktree"] [data-action="add"]').removeAttr('disabled');
}
});
// Add listener for framework change.
if (!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);
});
}
// Add listener for search.
self._find('[data-region="filtercompetencies"] button').click(function(e) {
e.preventDefault();
$(e.target).attr('disabled', 'disabled');
self._searchText = self._find('[data-region="filtercompetencies"] input').val() || '';
return self._refresh().always(function() {
$(e.target).removeAttr('disabled');
});
});
// Add listener for cancel.
self._find('[data-region="competencylinktree"] [data-action="cancel"]').click(function(e) {
e.preventDefault();
self.close();
});
// Add listener for add.
self._find('[data-region="competencylinktree"] [data-action="add"]').click(function(e) {
e.preventDefault();
var pendingPromise = new Pending();
if (!self._selectedCompetencies.length) {
return;
}
if (self._multiSelect) {
self._trigger('save', {competencyIds: self._selectedCompetencies});
} else {
// We checked above that the array has at least one value.
self._trigger('save', {competencyId: self._selectedCompetencies[0]});
}
// The dialogue here is a YUI dialogue and doesn't support Promises at all.
// However, it is typically synchronous so this shoudl suffice.
self.close();
pendingPromise.resolve();
});
// The list of selected competencies will be modified while looping (because of the listeners above).
var currentItems = self._selectedCompetencies.slice(0);
$.each(currentItems, function(index, id) {
var node = self._find('[data-id=' + id + ']');
if (node.length) {
tree.toggleItem(node);
tree.updateFocus(node);
}
});
};
/**
* Close the dialogue.
*
* @method close
*/
Picker.prototype.close = function() {
var self = this;
self._popup.close();
self._reset();
};
/**
* Opens the picker.
*
* @method display
* @return {Promise}
*/
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)
);
return;
}).catch(Notification.exception);
};
/**
* Fetch the competencies.
*
* @param {Number} frameworkId The frameworkId.
* @param {String} searchText Limit the competencies to those matching the text.
* @method _fetchCompetencies
* @return {Promise}
*/
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) {
/**
* @param {Object} parent
* @param {Array} competencies
*/
function addCompetencyChildren(parent, competencies) {
for (var i = 0; i < competencies.length; i++) {
if (competencies[i].parentid == parent.id) {
parent.haschildren = true;
competencies[i].children = [];
competencies[i].haschildren = false;
parent.children[parent.children.length] = competencies[i];
addCompetencyChildren(competencies[i], competencies);
}
}
}
// Expand the list of competencies into a tree.
var i, comp;
var tree = [];
for (i = 0; i < competencies.length; i++) {
comp = competencies[i];
if (comp.parentid == "0") { // Loose check for now, because WS returns a string.
comp.children = [];
comp.haschildren = 0;
tree[tree.length] = comp;
addCompetencyChildren(comp, competencies);
}
}
self._competencies = tree;
}).fail(Notification.exception);
};
/**
* Find a node in the dialogue.
*
* @param {String} selector
* @return {JQuery}
* @method _find
*/
Picker.prototype._find = function(selector) {
return $(this._popup.getContent()).find(selector);
};
/**
* Convenience method to get a framework object.
*
* @param {Number} fid The framework ID.
* @return {Object}
* @method _getFramework
*/
Picker.prototype._getFramework = function(fid) {
var frm;
$.each(this._frameworks, function(i, f) {
if (f.id == fid) {
frm = f;
return;
}
});
return frm;
};
/**
* Load the competencies.
*
* @method _loadCompetencies
* @return {Promise}
*/
Picker.prototype._loadCompetencies = function() {
return this._fetchCompetencies(this._frameworkId, this._searchText);
};
/**
* Load the frameworks.
*
* @method _loadFrameworks
* @return {Promise}
*/
Picker.prototype._loadFrameworks = function() {
var promise,
self = this;
// Quit early because we already have the data.
if (self._frameworks.length > 0) {
return $.when();
}
if (self._singleFramework) {
promise = Ajax.call([
{methodname: 'core_competency_read_competency_framework', args: {
id: this._frameworkId
}}
])[0].then(function(framework) {
return [framework];
});
} else {
promise = Ajax.call([
{methodname: 'core_competency_list_competency_frameworks', args: {
sort: 'shortname',
context: {contextid: self._pageContextId},
includes: self._pageContextIncludes,
onlyvisible: self._onlyVisible
}}
])[0];
}
return promise.done(function(frameworks) {
self._frameworks = frameworks;
}).fail(Notification.exception);
};
/**
* Register an event listener.
*
* @param {String} type The event type.
* @param {Function} handler The event listener.
* @method on
*/
Picker.prototype.on = function(type, handler) {
this._eventNode.on(type, handler);
};
/**
* Hook to executed before render.
*
* @method _preRender
* @return {Promise}
*/
Picker.prototype._preRender = function() {
var self = this;
return self._loadFrameworks().then(function() {
if (!self._frameworkId && self._frameworks.length > 0) {
self._frameworkId = self._frameworks[0].id;
}
// We could not set a framework ID, that probably means there are no frameworks accessible.
if (!self._frameworkId) {
self._frameworks = [];
return $.when();
}
return self._loadCompetencies();
});
};
/**
* Refresh the view.
*
* @method _refresh
* @return {Promise}
*/
Picker.prototype._refresh = function() {
var self = this;
return self._render().then(function(html) {
self._find('[data-region="competencylinktree"]').replaceWith(html);
self._afterRender();
return;
});
};
/**
* Render the dialogue.
*
* @method _render
* @return {Promise}
*/
Picker.prototype._render = function() {
var self = this;
return self._preRender().then(function() {
if (!self._singleFramework) {
$.each(self._frameworks, function(i, framework) {
if (framework.id == self._frameworkId) {
framework.selected = true;
} else {
framework.selected = false;
}
});
}
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);
});
};
/**
* Reset the dialogue properties.
*
* This does not reset everything, just enough to reset the UI.
*
* @method _reset
*/
Picker.prototype._reset = function() {
this._competencies = [];
this._disallowedCompetencyIDs = [];
this._popup = null;
this._searchText = '';
this._selectedCompetencies = [];
};
/**
* Set what competencies cannot be picked.
*
* This needs to be set after reset/close.
*
* @param {Number[]} ids The IDs.
* @method _setDisallowedCompetencyIDs
*/
Picker.prototype.setDisallowedCompetencyIDs = function(ids) {
this._disallowedCompetencyIDs = ids;
};
/**
* Trigger an event.
*
* @param {String} type The type of event.
* @param {Object} data The data to pass to the listeners.
* @method _reset
*/
Picker.prototype._trigger = function(type, data) {
this._eventNode.trigger(type, [data]);
};
return Picker;
});
@@ -0,0 +1,242 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/ajax',
'core/templates',
'core/str',
'tool_lp/tree',
'tool_lp/competencypicker'
],
function($, Notification, Ajax, Templates, Str, Tree, PickerBase) {
/**
* Competency picker in plan class.
*
* @class tool_lp/competencypicker_user_plans
* @param {Number} userId
* @param {Number|false} singlePlan The ID of the plan when limited to one.
* @param {Boolean} multiSelect Support multi-select in the tree.
*/
var Picker = function(userId, singlePlan, multiSelect) {
PickerBase.prototype.constructor.apply(this, [1, false, 'self', multiSelect]);
this._userId = userId;
this._plans = [];
if (singlePlan) {
this._planId = singlePlan;
this._singlePlan = true;
}
};
Picker.prototype = Object.create(PickerBase.prototype);
/** @property {Array} The list of plans fetched. */
Picker.prototype._plans = null;
/** @property {Number} The current plan ID. */
Picker.prototype._planId = null;
/** @property {Boolean} Whether we can browse plans or not. */
Picker.prototype._singlePlan = false;
/** @property {Number} The user the plans belongs to. */
Picker.prototype._userId = null;
/**
* Hook to executed after the view is rendered.
*
* @method _afterRender
*/
Picker.prototype._afterRender = function() {
var self = this;
PickerBase.prototype._afterRender.apply(self, arguments);
// Add listener for framework change.
if (!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);
});
}
};
/**
* Fetch the competencies.
*
* @param {Number} planId The planId.
* @param {String} searchText Limit the competencies to those matching the text.
* @method _fetchCompetencies
* @return {Promise} The promise object.
*/
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) {
// Expand the list of competencies into a fake tree.
var i, comp;
var tree = [];
for (i = 0; i < competencies.length; i++) {
comp = competencies[i].competency;
if (comp.shortname.toLowerCase().indexOf(searchText.toLowerCase()) < 0) {
continue;
}
comp.children = [];
comp.haschildren = 0;
tree.push(comp);
}
self._competencies = tree;
}).fail(Notification.exception);
};
/**
* Convenience method to get a plan object.
*
* @param {Number} id The plan ID.
* @return {Object|undefined} The plan.
* @method _getPlan
*/
Picker.prototype._getPlan = function(id) {
var plan;
$.each(this._plans, function(i, f) {
if (f.id == id) {
plan = f;
return;
}
});
return plan;
};
/**
* Load the competencies.
*
* @method _loadCompetencies
* @return {Promise}
*/
Picker.prototype._loadCompetencies = function() {
return this._fetchCompetencies(this._planId, this._searchText);
};
/**
* Load the plans.
*
* @method _loadPlans
* @return {Promise}
*/
Picker.prototype._loadPlans = function() {
var promise,
self = this;
// Quit early because we already have the data.
if (self._plans.length > 0) {
return $.when();
}
if (self._singlePlan) {
promise = Ajax.call([
{methodname: 'core_competency_read_plan', args: {
id: this._planId
}}
])[0].then(function(plan) {
return [plan];
});
} else {
promise = Ajax.call([
{methodname: 'core_competency_list_user_plans', args: {
userid: self._userId
}}
])[0];
}
return promise.done(function(plans) {
self._plans = plans;
}).fail(Notification.exception);
};
/**
* Hook to executed before render.
*
* @method _preRender
* @return {Promise}
*/
Picker.prototype._preRender = function() {
var self = this;
return self._loadPlans().then(function() {
if (!self._planId && self._plans.length > 0) {
self._planId = self._plans[0].id;
}
// We could not set a framework ID, that probably means there are no frameworks accessible.
if (!self._planId) {
self._plans = [];
return $.when();
}
return self._loadCompetencies();
});
};
/**
* Render the dialogue.
*
* @method _render
* @return {Promise}
*/
Picker.prototype._render = function() {
var self = this;
return self._preRender().then(function() {
if (!self._singlePlan) {
$.each(self._plans, function(i, plan) {
if (plan.id == self._planId) {
plan.selected = true;
} else {
plan.selected = false;
}
});
}
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);
});
};
return Picker;
});
@@ -0,0 +1,547 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/templates',
'tool_lp/dialogue',
'tool_lp/competency_outcomes',
'core/str'],
function($, Notification, Templates, Dialogue, Outcomes, Str) {
/**
* Competency rule class.
*
* When implementing this you should attach a listener to the event 'save'
* on the instance. E.g.
*
* var config = new RuleConfig(tree, modules);
* config.on('save', function(e, config) { ... });
*
* @param {competencytree} tree The competency tree.
* @param {Array} rulesModules The modules containing the rules: [{ typeName: { amd: amdModule, name: ruleName }}].
*/
var RuleConfig = function(tree, rulesModules) {
this._eventNode = $('<div></div>');
this._tree = tree;
this._rulesModules = rulesModules;
this._setUp();
};
/** @property {Object} The current competency. */
RuleConfig.prototype._competency = null;
/** @property {Node} The node we attach the events to. */
RuleConfig.prototype._eventNode = null;
/** @property {Array} Outcomes options. */
RuleConfig.prototype._outcomesOption = null;
/** @property {Dialogue} The dialogue. */
RuleConfig.prototype._popup = null;
/** @property {Promise} Resolved when the module is ready. */
RuleConfig.prototype._ready = null;
/** @property {Array} The rules. */
RuleConfig.prototype._rules = null;
/** @property {Array} The rules modules. */
RuleConfig.prototype._rulesModules = null;
/** @property {competencytree} The competency tree. */
RuleConfig.prototype._tree = null;
/**
* After change.
*
* Triggered when a change occured.
*
* @method _afterChange
* @protected
*/
RuleConfig.prototype._afterChange = function() {
if (!this._isValid()) {
this._find('[data-action="save"]').prop('disabled', true);
} else {
this._find('[data-action="save"]').prop('disabled', false);
}
};
/**
* After change in rule's config.
*
* Triggered when a change occured in a specific rule config.
*
* @method _afterRuleConfigChange
* @protected
* @param {Event} e
* @param {Rule} rule
*/
RuleConfig.prototype._afterRuleConfigChange = function(e, rule) {
if (rule != this._getRule()) {
// This rule is not the current one any more, we can ignore.
return;
}
this._afterChange();
};
/**
* After render hook.
*
* @method _afterRender
* @protected
*/
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();
});
};
/**
* Whether the current competency can be configured.
*
* @return {Boolean}
* @method canBeConfigured
*/
RuleConfig.prototype.canBeConfigured = function() {
var can = false;
$.each(this._rules, function(index, rule) {
if (rule.canConfig()) {
can = true;
return;
}
});
return can;
};
/**
* Close the dialogue.
*
* @method close
*/
RuleConfig.prototype.close = function() {
this._popup.close();
this._popup = null;
};
/**
* Opens the picker.
*
* @method display
* @returns {Promise}
*/
RuleConfig.prototype.display = function() {
var self = this;
if (!self._competency) {
return false;
}
return $.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,
false,
'515px'
);
return;
}).fail(Notification.exception);
};
/**
* Find a node in the dialogue.
*
* @param {String} selector
* @return {JQuery}
* @method _find
* @protected
*/
RuleConfig.prototype._find = function(selector) {
return $(this._popup.getContent()).find(selector);
};
/**
* Get the applicable outcome options.
*
* @return {Array}
* @method _getApplicableOutcomesOptions
* @protected
*/
RuleConfig.prototype._getApplicableOutcomesOptions = function() {
var self = this,
options = [];
$.each(self._outcomesOption, function(index, outcome) {
options.push({
code: outcome.code,
name: outcome.name,
selected: (outcome.code == self._competency.ruleoutcome) ? true : false,
});
});
return options;
};
/**
* Get the applicable rules options.
*
* @return {Array}
* @method _getApplicableRulesOptions
* @protected
*/
RuleConfig.prototype._getApplicableRulesOptions = function() {
var self = this,
options = [];
$.each(self._rules, function(index, rule) {
if (!rule.canConfig()) {
return;
}
options.push({
name: self._getRuleName(rule.getType()),
type: rule.getType(),
selected: (rule.getType() == self._competency.ruletype) ? true : false,
});
});
return options;
};
/**
* Get the full config for the competency.
*
* @return {Object} Contains rule, ruleoutcome and ruleconfig.
* @method _getConfig
* @protected
*/
RuleConfig.prototype._getConfig = function() {
var rule = this._getRule();
return {
ruletype: rule ? rule.getType() : null,
ruleconfig: rule ? rule.getConfig() : null,
ruleoutcome: this._getOutcome()
};
};
/**
* Get the selected outcome code.
*
* @return {String}
* @method _getOutcome
* @protected
*/
RuleConfig.prototype._getOutcome = function() {
return this._find('[name="outcome"]').val();
};
/**
* Get the selected rule.
*
* @return {null|Rule}
* @method _getRule
* @protected
*/
RuleConfig.prototype._getRule = function() {
var result,
type = this._find('[name="rule"]').val();
$.each(this._rules, function(index, rule) {
if (rule.getType() == type) {
result = rule;
return;
}
});
return result;
};
/**
* Return the name of a rule.
*
* @param {String} type The type of a rule.
* @return {String}
* @method _getRuleName
* @protected
*/
RuleConfig.prototype._getRuleName = function(type) {
var self = this,
name;
$.each(self._rulesModules, function(index, modInfo) {
if (modInfo.type == type) {
name = modInfo.name;
return;
}
});
return name;
};
/**
* Initialise the outcomes.
*
* @return {Promise}
* @method _initOutcomes
* @protected
*/
RuleConfig.prototype._initOutcomes = function() {
var self = this;
return Outcomes.getAll().then(function(outcomes) {
self._outcomesOption = outcomes;
return;
});
};
/**
* Initialise the rules.
*
* @return {Promise}
* @method _initRules
* @protected
*/
RuleConfig.prototype._initRules = function() {
var self = this,
promises = [];
$.each(self._rules, function(index, rule) {
var promise = rule.init().then(function() {
rule.setTargetCompetency(self._competency);
rule.on('change', self._afterRuleConfigChange.bind(self));
return;
}, function() {
// Upon failure remove the rule, and resolve the promise.
self._rules.splice(index, 1);
return $.when();
});
promises.push(promise);
});
return $.when.apply($.when, promises);
};
/**
* Whether or not the current config is valid.
*
* @return {Boolean}
* @method _isValid
* @protected
*/
RuleConfig.prototype._isValid = function() {
var outcome = this._getOutcome(),
rule = this._getRule();
if (outcome == Outcomes.NONE) {
return true;
} else if (!rule) {
return false;
}
return rule.isValid();
};
/**
* Register an event listener.
*
* @param {String} type The event type.
* @param {Function} handler The event listener.
* @method on
*/
RuleConfig.prototype.on = function(type, handler) {
this._eventNode.on(type, handler);
};
/**
* Hook to executed before render.
*
* @method _preRender
* @protected
* @return {Promise}
*/
RuleConfig.prototype._preRender = function() {
// We need to have all the information about the rule plugins first.
return this.ready();
};
/**
* Returns a promise that is resolved when the module is ready.
*
* @return {Promise}
* @method ready
* @protected
*/
RuleConfig.prototype.ready = function() {
return this._ready.promise();
};
/**
* Render the dialogue.
*
* @method _render
* @protected
* @return {Promise}
*/
RuleConfig.prototype._render = function() {
var self = this;
return this._preRender().then(function() {
var config;
if (!self.canBeConfigured()) {
config = false;
} else {
config = {};
config.outcomes = self._getApplicableOutcomesOptions();
config.rules = self._getApplicableRulesOptions();
}
var context = {
competencyshortname: self._competency.shortname,
config: config
};
return Templates.render('tool_lp/competency_rule_config', context);
});
};
/**
* Set the target competency.
*
* @param {Number} competencyId The target competency Id.
* @method setTargetCompetencyId
*/
RuleConfig.prototype.setTargetCompetencyId = function(competencyId) {
var self = this;
self._competency = self._tree.getCompetency(competencyId);
$.each(self._rules, function(index, rule) {
rule.setTargetCompetency(self._competency);
});
};
/**
* Set up the instance.
*
* @method _setUp
* @protected
*/
RuleConfig.prototype._setUp = function() {
var self = this,
promises = [],
modules = [];
self._ready = $.Deferred();
self._rules = [];
$.each(self._rulesModules, function(index, rule) {
modules.push(rule.amd);
});
// Load all the modules.
require(modules, function() {
$.each(arguments, function(index, Module) {
// Instantiate the rule and listen to it.
var rule = new Module(self._tree);
self._rules.push(rule);
});
// Load all the option values.
promises.push(self._initRules());
promises.push(self._initOutcomes());
// Ready when everything is done.
$.when.apply($.when, promises).always(function() {
self._ready.resolve();
});
});
};
/**
* Called when the user switches outcome.
*
* @method _switchedOutcome
* @protected
*/
RuleConfig.prototype._switchedOutcome = function() {
var self = this,
type = self._getOutcome();
if (type == Outcomes.NONE) {
// Reset to defaults.
self._find('[data-region="rule-type"]').hide()
.find('[name="rule"]').val(-1);
self._find('[data-region="rule-config"]').empty().hide();
self._afterChange();
return;
}
self._find('[data-region="rule-type"]').show();
self._find('[data-region="rule-config"]').show();
self._afterChange();
};
/**
* Called when the user switches rule.
*
* @method _switchedRule
* @protected
*/
RuleConfig.prototype._switchedRule = function() {
var self = this,
container = self._find('[data-region="rule-config"]'),
rule = self._getRule();
if (!rule) {
container.empty().hide();
self._afterChange();
return;
}
rule.injectTemplate(container).then(function() {
container.show();
return;
}).always(function() {
self._afterChange();
}).catch(function() {
container.empty().hide();
});
};
/**
* Trigger an event.
*
* @param {String} type The type of event.
* @param {Object} data The data to pass to the listeners.
* @method _trigger
* @protected
*/
RuleConfig.prototype._trigger = function(type, data) {
this._eventNode.trigger(type, [data]);
};
return /** @alias module:tool_lp/competencyruleconfig */ RuleConfig;
});
+265
View File
@@ -0,0 +1,265 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Handle selection changes on the competency tree.
*
* @module tool_lp/competencytree
* @copyright 2015 Damyon Wiese <damyon@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['core/ajax', 'core/notification', 'core/templates', 'tool_lp/tree', 'tool_lp/competency_outcomes', 'jquery'],
function(ajax, notification, templates, Ariatree, CompOutcomes, $) {
// Private variables and functions.
/** @var {Object[]} competencies - Cached list of competencies */
var competencies = {};
/** @var {Number} competencyFrameworkId - The current framework id */
var competencyFrameworkId = 0;
/** @var {String} competencyFrameworkShortName - The current framework short name */
var competencyFrameworkShortName = '';
/** @var {String} treeSelector - The selector for the root of the tree. */
var treeSelector = '';
/** @var {String} currentNodeId - The data-id of the current node in the tree. */
var currentNodeId = '';
/** @var {Boolean} competencyFramworkCanManage - Can manage the competencies framework */
var competencyFramworkCanManage = false;
/**
* Build a tree from the flat list of competencies.
* @param {Object} parent The parent competency.
* @param {Array} all The list of all competencies.
*/
var addChildren = function(parent, all) {
var i = 0;
var current = false;
parent.haschildren = false;
parent.children = [];
for (i = 0; i < all.length; i++) {
current = all[i];
if (current.parentid == parent.id) {
parent.haschildren = true;
parent.children.push(current);
addChildren(current, all);
}
}
};
/**
* Load the list of competencies via ajax. Competencies are filtered by the searchtext.
* @param {String} searchtext The text to filter on.
* @return {promise}
*/
var loadCompetencies = function(searchtext) {
var deferred = $.Deferred();
templates.render('tool_lp/loading', {}).done(function(loadinghtml, loadingjs) {
templates.replaceNodeContents($(treeSelector), loadinghtml, loadingjs);
var promises = ajax.call([{
methodname: 'core_competency_search_competencies',
args: {
searchtext: searchtext,
competencyframeworkid: competencyFrameworkId
}
}]);
promises[0].done(function(result) {
competencies = {};
var i = 0;
for (i = 0; i < result.length; i++) {
competencies[result[i].id] = result[i];
}
var children = [];
var competency = false;
for (i = 0; i < result.length; i++) {
competency = result[i];
if (parseInt(competency.parentid, 10) === 0) {
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, false);
if (currentNodeId) {
var node = $(treeSelector).find('[data-id=' + currentNodeId + ']');
if (node.length) {
tree.selectItem(node);
tree.updateFocus(node);
}
}
deferred.resolve(competencies);
}).fail(deferred.reject);
}).fail(deferred.reject);
});
return deferred.promise();
};
/**
* Whenever the current item in the tree is changed - remember the "id".
* @param {Event} evt
* @param {Object} params The parameters for the event (This is the selected node).
*/
var rememberCurrent = function(evt, params) {
var node = params.selected;
currentNodeId = node.attr('data-id');
};
return /** @alias module:tool_lp/competencytree */ {
// Public variables and functions.
/**
* Initialise the tree.
*
* @param {Number} id The competency framework id.
* @param {String} shortname The framework shortname
* @param {String} search The current search string
* @param {String} selector The selector for the tree div
* @param {Boolean} canmanage Can manage the competencies
* @param {Number} competencyid The id of the competency to show first
*/
init: function(id, shortname, search, selector, canmanage, competencyid) {
competencyFrameworkId = id;
competencyFrameworkShortName = shortname;
competencyFramworkCanManage = canmanage;
treeSelector = selector;
loadCompetencies(search).fail(notification.exception);
if (competencyid > 0) {
currentNodeId = competencyid;
}
this.on('selectionchanged', rememberCurrent);
},
/**
* Add an event handler for custom events emitted by the tree.
*
* @param {String} eventname The name of the event - only "selectionchanged" for now
* @param {Function} handler The handler for the event.
*/
on: function(eventname, handler) {
// We can't use the tree on function directly
// because the tree gets rebuilt whenever the search string changes,
// instead we attach the listner to the root node of the tree which never
// gets destroyed (same as "on()" code in the tree.js).
$(treeSelector).on(eventname, handler);
},
/**
* Get the children of a competency.
*
* @param {Number} id The competency ID.
* @return {Array}
* @method getChildren
*/
getChildren: function(id) {
var children = [];
$.each(competencies, function(index, competency) {
if (competency.parentid == id) {
children.push(competency);
}
});
return children;
},
/**
* Get the competency framework id this model was initiliased with.
*
* @return {Number}
*/
getCompetencyFrameworkId: function() {
return competencyFrameworkId;
},
/**
* Get a competency by id
*
* @param {Number} id The competency id
* @return {Object}
*/
getCompetency: function(id) {
return competencies[id];
},
/**
* Get the competency level.
*
* @param {Number} id The competency ID.
* @return {Number}
*/
getCompetencyLevel: function(id) {
var competency = this.getCompetency(id),
level = competency.path.replace(/^\/|\/$/g, '').split('/').length;
return level;
},
/**
* Whether a competency has children.
*
* @param {Number} id The competency ID.
* @return {Boolean}
* @method hasChildren
*/
hasChildren: function(id) {
return this.getChildren(id).length > 0;
},
/**
* Does the competency have a rule?
*
* @param {Number} id The competency ID.
* @return {Boolean}
*/
hasRule: function(id) {
var comp = this.getCompetency(id);
if (comp) {
return comp.ruleoutcome != CompOutcomes.OUTCOME_NONE
&& comp.ruletype;
}
return false;
},
/**
* Reload all the page competencies framework competencies.
* @method reloadCompetencies
* @return {Promise}
*/
reloadCompetencies: function() {
return loadCompetencies('').fail(notification.exception);
},
/**
* Get all competencies for this framework.
*
* @return {Object[]}
*/
listCompetencies: function() {
return competencies;
},
};
});
@@ -0,0 +1,164 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Change the course competency settings in a popup.
*
* @module tool_lp/course_competency_settings
* @copyright 2015 Damyon Wiese <damyon@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery',
'core/notification',
'tool_lp/dialogue',
'core/str',
'core/ajax',
'core/templates',
'core/pending'
],
function($, notification, Dialogue, str, ajax, templates, Pending) {
/**
* Constructor
*
* @param {String} selector - selector for the links to open the dialogue.
*/
var settingsMod = function(selector) {
$(selector).on('click', this.configureSettings.bind(this));
};
/** @property {Dialogue} Reference to the dialogue that we opened. */
settingsMod.prototype._dialogue = null;
/**
* Open the configure settings dialogue.
*
* @param {Event} e
* @method configureSettings
*/
settingsMod.prototype.configureSettings = function(e) {
var pendingPromise = new Pending();
var courseid = $(e.target).closest('a').data('courseid');
var currentValue = $(e.target).closest('a').data('pushratingstouserplans');
var context = {
courseid: courseid,
settings: {pushratingstouserplans: currentValue}
};
e.preventDefault();
$.when(
str.get_string('configurecoursecompetencysettings', 'tool_lp'),
templates.render('tool_lp/course_competency_settings', context),
)
.then(function(title, templateResult) {
this._dialogue = new Dialogue(
title,
templateResult[0],
this.addListeners.bind(this)
);
return this._dialogue;
}.bind(this))
.then(pendingPromise.resolve)
.catch(notification.exception);
};
/**
* Add the save listener to the form.
*
* @method addSaveListener
*/
settingsMod.prototype.addListeners = function() {
var save = this._find('[data-action="save"]');
save.on('click', this.saveSettings.bind(this));
var cancel = this._find('[data-action="cancel"]');
cancel.on('click', this.cancelChanges.bind(this));
};
/**
* Cancel the changes.
*
* @param {Event} e
* @method cancelChanges
*/
settingsMod.prototype.cancelChanges = function(e) {
e.preventDefault();
this._dialogue.close();
};
/**
* Cancel the changes.
*
* @param {String} selector
* @return {JQuery}
*/
settingsMod.prototype._find = function(selector) {
return $('[data-region="coursecompetencysettings"]').find(selector);
};
/**
* Save the settings.
*
* @param {Event} e
* @method saveSettings
*/
settingsMod.prototype.saveSettings = function(e) {
var pendingPromise = new Pending();
e.preventDefault();
var newValue = this._find('input[name="pushratingstouserplans"]:checked').val();
var courseId = this._find('input[name="courseid"]').val();
var 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);
};
/**
* Refresh the course competencies page.
*
* @method saveSettings
*/
settingsMod.prototype.refreshCourseCompetenciesPage = function() {
var courseId = this._find('input[name="courseid"]').val();
var 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();
return;
}.bind(this))
.then(pendingPromise.resolve)
.catch(notification.exception);
};
return /** @alias module:tool_lp/configurecoursecompetencysettings */ settingsMod;
});
+120
View File
@@ -0,0 +1,120 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['core/yui'], function(Y) {
// Private variables and functions.
/**
* Constructor
*
* @param {String} title Title for the window.
* @param {String} content The content for the window.
* @param {function} afterShow Callback executed after the window is opened.
* @param {function} afterHide Callback executed after the window is closed.
* @param {Boolean} wide Specify we want an extra wide dialogue (the size is standard, but wider than the default).
* @param {String} height The height of the dialogue.
*/
var dialogue = function(title, content, afterShow, afterHide, wide, height) {
M.util.js_pending('tool_lp/dialogue:dialogue');
this.yuiDialogue = null;
var parent = this;
// Default for wide is false.
if (typeof wide == 'undefined') {
wide = false;
}
Y.use('moodle-core-notification', 'timers', function() {
var width = '480px';
if (wide) {
width = '800px';
}
if (!height) {
height = 'auto';
}
parent.yuiDialogue = new M.core.dialogue({
headerContent: title,
bodyContent: content,
draggable: true,
visible: false,
center: true,
modal: true,
width: width,
height: height
});
parent.yuiDialogue.before('visibleChange', function() {
M.util.js_pending('tool_lp/dialogue:before:visibleChange');
});
parent.yuiDialogue.after('visibleChange', function(e) {
if (e.newVal) {
// Delay the callback call to the next tick, otherwise it can happen that it is
// executed before the dialogue constructor returns.
if ((typeof afterShow !== 'undefined')) {
Y.soon(function() {
afterShow(parent);
parent.yuiDialogue.centerDialogue();
M.util.js_complete('tool_lp/dialogue:before:visibleChange');
});
} else {
M.util.js_complete('tool_lp/dialogue:before:visibleChange');
}
} else {
if ((typeof afterHide !== 'undefined')) {
Y.soon(function() {
afterHide(parent);
M.util.js_complete('tool_lp/dialogue:before:visibleChange');
});
} else {
M.util.js_complete('tool_lp/dialogue:before:visibleChange');
}
}
});
parent.yuiDialogue.show();
M.util.js_complete('tool_lp/dialogue:dialogue');
});
};
/**
* Close this window.
*/
dialogue.prototype.close = function() {
this.yuiDialogue.hide();
this.yuiDialogue.destroy();
};
/**
* Get content.
* @return {node}
*/
dialogue.prototype.getContent = function() {
return this.yuiDialogue.bodyNode.getDOMNode();
};
return /** @alias module:tool_lp/dialogue */ dialogue;
});
+96
View File
@@ -0,0 +1,96 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['core/str', 'core/yui'], function(str, Y) {
// Private variables and functions.
/**
* Store the current instance of the core drag drop.
*
* @property {object} dragDropInstance M.tool_lp.dragdrop_reorder
*/
var dragDropInstance = null;
/**
* Translate the drophit event from YUI
* into simple drag and drop nodes.
* @param {Y.Event} e The yui drop event.
*/
var proxyCallback = function(e) {
var dragNode = e.drag.get('node');
var dropNode = e.drop.get('node');
this.callback(dragNode.getDOMNode(), dropNode.getDOMNode());
};
return /** @alias module:tool_lp/dragdrop-reorder */ {
// Public variables and functions.
/**
* Create an instance of M.tool_lp.dragdrop
*
* @param {String} group Unique string to identify this interaction.
* @param {String} dragHandleText Alt text for the drag handle.
* @param {String} sameNodeText Used in keyboard drag drop for the list of items target.
* @param {String} parentNodeText Used in keyboard drag drop for the parent target.
* @param {String} sameNodeClass class used to find the each of the list of items.
* @param {String} parentNodeClass class used to find the container for the list of items.
* @param {String} dragHandleInsertClass class used to find the location to insert the drag handles.
* @param {function} callback Drop hit handler.
*/
dragdrop: function(group,
dragHandleText,
sameNodeText,
parentNodeText,
sameNodeClass,
parentNodeClass,
dragHandleInsertClass,
callback) {
// Here we are wrapping YUI. This allows us to start transitioning, but
// wait for a good alternative without having inconsistent UIs.
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
};
if (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)
});
});
});
}
};
});
+58
View File
@@ -0,0 +1,58 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery'], function($) {
/**
* Base class.
*/
var Base = function() {
this._eventNode = $('<div></div>');
};
/** @property {Node} The node we attach the events to. */
Base.prototype._eventNode = null;
/**
* Register an event listener.
*
* @param {String} type The event type.
* @param {Function} handler The event listener.
* @method on
*/
Base.prototype.on = function(type, handler) {
this._eventNode.on(type, handler);
};
/**
* Trigger an event.
*
* @param {String} type The type of event.
* @param {Object} data The data to pass to the listeners.
* @method _trigger
*/
Base.prototype._trigger = function(type, data) {
this._eventNode.trigger(type, [data]);
};
return /** @alias module:tool_lp/event_base */ Base;
});
+101
View File
@@ -0,0 +1,101 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/ajax',
'core/str',
'core/log'],
function($, Notification, Ajax, Str, Log) {
var selectors = {};
/**
* Register an event listener.
*
* @param {String} triggerSelector The node on which the click will happen.
* @param {String} containerSelector The parent node that will be removed and contains the evidence ID.
*/
var register = function(triggerSelector, containerSelector) {
if (typeof selectors[triggerSelector] !== 'undefined') {
return;
}
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.');
return;
}
var evidenceId = parent.data('id');
if (!evidenceId) {
Log.error('Evidence ID was not found.');
return;
}
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], // Confirm.
strings[1], // Are you sure?
strings[2], // Delete.
strings[3], // Cancel.
function() {
var promise = Ajax.call([{
methodname: 'core_competency_delete_evidence',
args: {
id: evidenceId
}
}]);
promise[0].then(function() {
parent.remove();
return;
}).fail(Notification.exception);
}
);
}).fail(Notification.exception);
});
};
return /** @alias module:tool_lp/evidence_delete */ {
/**
* Register an event listener.
*
* @param {String} triggerSelector The node on which the click will happen.
* @param {String} containerSelector The parent node that will be removed and contains the evidence ID.
* @return {Void}
*/
register: register
};
});
@@ -0,0 +1,88 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery', 'core/ajax', 'core/templates'], function($, Ajax, Templates) {
return /** @alias module:tool_lp/form-user-selector */ {
processResults: function(selector, results) {
var users = [];
$.each(results, function(index, user) {
users.push({
value: user.id,
label: user._label
});
});
return users;
},
transport: function(selector, query, success, failure) {
var promise;
var capability = $(selector).data('capability');
if (typeof capability === "undefined") {
capability = '';
}
promise = Ajax.call([{
methodname: 'tool_lp_search_users',
args: {
query: query,
capability: capability
}
}]);
promise[0].then(function(results) {
var promises = [],
i = 0;
// Render the label.
$.each(results.users, function(index, user) {
var ctx = user,
identity = [];
$.each(['idnumber', 'email', 'phone1', 'phone2', 'department', 'institution'], function(i, k) {
if (typeof user[k] !== 'undefined' && user[k] !== '') {
ctx.hasidentity = true;
identity.push(user[k]);
}
});
ctx.identity = identity.join(', ');
promises.push(Templates.render('tool_lp/form-user-selector-suggestion', ctx));
});
// Apply the label to the results.
return $.when.apply($.when, promises).then(function() {
var args = arguments;
$.each(results.users, function(index, user) {
user._label = args[i];
i++;
});
success(results.users);
return;
});
}).catch(failure);
}
};
});
@@ -0,0 +1,137 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery', 'tool_lp/competencypicker', 'core/ajax', 'core/notification', 'core/templates'],
function($, Picker, Ajax, Notification, Templates) {
var pickerInstance = null;
var pageContextId = 1;
/**
* Re-render the list of selected competencies.
*
* @method renderCompetencies
* @return {boolean}
*/
var renderCompetencies = function() {
var currentCompetencies = $('[data-action="competencies"]').val();
var requests = [];
var i = 0;
if (currentCompetencies != '') {
currentCompetencies = currentCompetencies.split(',');
for (i = 0; i < currentCompetencies.length; i++) {
requests[requests.length] = {
methodname: 'core_competency_read_competency',
args: {id: currentCompetencies[i]}
};
}
}
$.when.apply($, Ajax.call(requests, false)).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) {
Templates.replaceNode($('[data-region="competencies"]'), html, js);
return true;
}).fail(Notification.exception);
return true;
};
/**
* Deselect a competency
*
* @method unpickCompetenciesHandler
* @param {Event} e
* @return {boolean}
*/
var unpickCompetenciesHandler = function(e) {
var currentCompetencies = $('[data-action="competencies"]').val().split(','),
newCompetencies = [],
i,
toRemove = $(e.currentTarget).data('id');
for (i = 0; i < currentCompetencies.length; i++) {
if (currentCompetencies[i] != toRemove) {
newCompetencies[newCompetencies.length] = currentCompetencies[i];
}
}
$('[data-action="competencies"]').val(newCompetencies.join(','));
return renderCompetencies();
};
/**
* Open a competencies popup to relate competencies.
*
* @method pickCompetenciesHandler
*/
var pickCompetenciesHandler = function() {
var currentCompetencies = $('[data-action="competencies"]').val().split(',');
if (!pickerInstance) {
pickerInstance = new Picker(pageContextId, false, 'parents', true);
pickerInstance.on('save', function(e, data) {
var before = $('[data-action="competencies"]').val();
var compIds = data.competencyIds;
if (before != '') {
compIds = compIds.concat(before.split(','));
}
var value = compIds.join(',');
$('[data-action="competencies"]').val(value);
return renderCompetencies();
});
}
pickerInstance.setDisallowedCompetencyIDs(currentCompetencies);
pickerInstance.display();
};
return /** @alias module:tool_lp/form_competency_element */ {
/**
* Listen for clicks on the competency picker and push the changes to the form element.
*
* @method init
* @param {Integer} contextId
*/
init: function(contextId) {
pageContextId = contextId;
renderCompetencies();
$('[data-action="select-competencies"]').on('click', pickCompetenciesHandler);
$('body').on('click', '[data-action="deselect-competency"]', unpickCompetenciesHandler);
}
};
});
+178
View File
@@ -0,0 +1,178 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery', 'core/templates', 'core/ajax', 'core/notification', 'core/str'], function($, templates, ajax, notification, str) {
// Private variables and functions.
/** @var {Number} pagecontextid The id of the context */
var pagecontextid = 0;
/** @var {Number} frameworkid The id of the framework */
var frameworkid = 0;
/**
* Callback to replace the dom element with the rendered template.
*
* @param {String} newhtml The new html to insert.
* @param {String} newjs The new js to run.
*/
var updatePage = function(newhtml, newjs) {
$('[data-region="managecompetencies"]').replaceWith(newhtml);
templates.runTemplateJS(newjs);
};
/**
* Callback to render the page template again and update the page.
*
* @param {Object} context The context for the template.
*/
var reloadList = function(context) {
templates.render('tool_lp/manage_competency_frameworks_page', context)
.done(updatePage)
.fail(notification.exception);
};
/**
* Duplicate a framework and reload the page.
* @method doDuplicate
* @param {Event} e
*/
var doDuplicate = function(e) {
e.preventDefault();
frameworkid = $(this).attr('data-frameworkid');
// We are chaining ajax requests here.
var requests = ajax.call([{
methodname: 'core_competency_duplicate_competency_framework',
args: {id: frameworkid}
}, {
methodname: 'tool_lp_data_for_competency_frameworks_manage_page',
args: {
pagecontext: {
contextid: pagecontextid
}
}
}]);
requests[1].done(reloadList).fail(notification.exception);
};
/**
* Delete a framework and reload the page.
*/
var doDelete = function() {
// We are chaining ajax requests here.
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) {
if (success === false) {
var req = ajax.call([{
methodname: 'core_competency_read_competency_framework',
args: {id: frameworkid}
}]);
req[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);
};
/**
* Handler for "Delete competency framework" actions.
* @param {Event} e
*/
var confirmDelete = function(e) {
e.preventDefault();
var id = $(this).attr('data-frameworkid');
frameworkid = id;
var requests = ajax.call([{
methodname: 'core_competency_read_competency_framework',
args: {id: frameworkid}
}]);
requests[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], // Confirm.
strings[1], // Delete competency framework X?
strings[2], // Delete.
strings[3], // Cancel.
doDelete
);
}).fail(notification.exception);
}).fail(notification.exception);
};
return /** @alias module:tool_lp/frameworkactions */ {
// Public variables and functions.
/**
* Expose the event handler for delete.
* @method deleteHandler
* @param {Event} e
*/
deleteHandler: confirmDelete,
/**
* Expose the event handler for duplicate.
* @method duplicateHandler
* @param {Event} e
*/
duplicateHandler: doDuplicate,
/**
* Initialise the module.
* @method init
* @param {Number} contextid The context id of the page.
*/
init: function(contextid) {
pagecontextid = contextid;
}
};
});
@@ -0,0 +1,92 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery', 'core/ajax', 'core/notification'], function($, Ajax, Notification) {
return /** @alias module:tool_lpmigrate/frameworks_datasource */ {
/**
* List frameworks.
*
* @param {Number} contextId The context ID.
* @param {Object} options Additional parameters to pass to the external function.
* @return {Promise}
*/
list: function(contextId, options) {
var args = {
context: {
contextid: contextId
}
};
$.extend(args, typeof options === 'undefined' ? {} : options);
return Ajax.call([{
methodname: 'core_competency_list_competency_frameworks',
args: args
}])[0];
},
/**
* Process the results for auto complete elements.
*
* @param {String} selector The selector of the auto complete element.
* @param {Array} results An array or results.
* @return {Array} New array of results.
*/
processResults: function(selector, results) {
var options = [];
$.each(results, function(index, data) {
options.push({
value: data.id,
label: data.shortname + ' ' + data.idnumber
});
});
return options;
},
/**
* Source of data for Ajax element.
*
* @param {String} selector The selector of the auto complete element.
* @param {String} query The query string.
* @param {Function} callback A callback function receiving an array of results.
*/
/* eslint-disable promise/no-callback-in-promise */
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);
}
};
});
+154
View File
@@ -0,0 +1,154 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery',
'core/notification',
'core/templates',
'tool_lp/dialogue',
'tool_lp/event_base',
'core/str'],
function($, Notification, Templates, Dialogue, EventBase, Str) {
/**
* Grade dialogue class.
*
* @class tool_lp/grade_dialogue
* @param {Array} ratingOptions
*/
var Grade = function(ratingOptions) {
EventBase.prototype.constructor.apply(this, []);
this._ratingOptions = ratingOptions;
};
Grade.prototype = Object.create(EventBase.prototype);
/** @property {Dialogue} The dialogue. */
Grade.prototype._popup = null;
/** @property {Array} Array of objects containing, 'value', 'name' and optionally 'selected'. */
Grade.prototype._ratingOptions = null;
/**
* After render hook.
*
* @method _afterRender
* @protected
*/
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() {
var node = $(this);
if (!node.val()) {
btnRate.prop('disabled', true);
} else {
btnRate.prop('disabled', false);
}
}).change();
btnRate.click(function(e) {
e.preventDefault();
var val = lstRating.val();
if (!val) {
return;
}
this._trigger('rated', {
'rating': val,
'note': txtComment.val()
});
this.close();
}.bind(this));
};
/**
* Close the dialogue.
*
* @method close
*/
Grade.prototype.close = function() {
this._popup.close();
this._popup = null;
};
/**
* Opens the picker.
*
* @method display
* @return {Promise}
*/
Grade.prototype.display = function() {
M.util.js_pending('tool_lp/grade_dialogue:display');
return $.when(
Str.get_string('rate', 'tool_lp'),
this._render()
)
.then(function(title, templateResult) {
this._popup = new Dialogue(
title,
templateResult[0],
function() {
this._afterRender();
M.util.js_complete('tool_lp/grade_dialogue:display');
}.bind(this)
);
return this._popup;
}.bind(this))
.catch(Notification.exception);
};
/**
* Find a node in the dialogue.
*
* @param {String} selector
* @method _find
* @returns {node} The node
* @protected
*/
Grade.prototype._find = function(selector) {
return $(this._popup.getContent()).find(selector);
};
/**
* Render the dialogue.
*
* @method _render
* @protected
* @return {Promise}
*/
Grade.prototype._render = function() {
var context = {
cangrade: this._canGrade,
ratings: this._ratingOptions
};
return Templates.render('tool_lp/competency_grader', context);
};
return Grade;
});
@@ -0,0 +1,161 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['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) {
/**
* InlineEditor
*
* @class tool_lp/grade_user_competency_inline
* @param {String} selector The selector to trigger the grading.
* @param {Number} scaleId The id of the scale for this competency.
* @param {Number} competencyId The id of the competency.
* @param {Number} userId The id of the user.
* @param {Number} planId The id of the plan.
* @param {Number} courseId The id of the course.
* @param {String} chooseStr Language string for choose a rating.
*/
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));
if (this._planId) {
this._methodName = 'core_competency_grade_competency_in_plan';
this._args = {
competencyid: this._competencyId,
planid: this._planId
};
} else if (this._courseId) {
this._methodName = 'core_competency_grade_competency_in_course';
this._args = {
competencyid: this._competencyId,
courseid: this._courseId,
userid: this._userId
};
} else {
this._methodName = 'core_competency_grade_competency';
this._args = {
userid: this._userId,
competencyid: this._competencyId
};
}
};
InlineEditor.prototype = Object.create(EventBase.prototype);
/**
* Setup.
*
* @method _setUp
*/
InlineEditor.prototype._setUp = function() {
var options = [],
self = this;
M.util.js_pending('tool_lp/grade_user_competency_inline:_setUp');
var promise = ScaleValues.get_values(self._scaleId);
promise.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) {
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
}]);
});
return dialogue;
})
.then(function(dialogue) {
self._dialogue = dialogue;
M.util.js_complete('tool_lp/grade_user_competency_inline:_setUp');
return;
})
.fail(notification.exception);
};
/** @property {Number} The scale id for this competency. */
InlineEditor.prototype._scaleId = null;
/** @property {Number} The id of the competency. */
InlineEditor.prototype._competencyId = null;
/** @property {Number} The id of the user. */
InlineEditor.prototype._userId = null;
/** @property {Number} The id of the plan. */
InlineEditor.prototype._planId = null;
/** @property {Number} The id of the course. */
InlineEditor.prototype._courseId = null;
/** @property {String} The text for Choose rating. */
InlineEditor.prototype._chooseStr = null;
/** @property {GradeDialogue} The grading dialogue. */
InlineEditor.prototype._dialogue = null;
return InlineEditor;
});
+842
View File
@@ -0,0 +1,842 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery'], function($) {
/** @property {boolean} Flag to indicate if we have already registered a click event handler for the document. */
var documentClickHandlerRegistered = false;
/** @property {boolean} Flag to indicate whether there's an active, open menu. */
var menuActive = false;
/**
* Close all open submenus anywhere in the page (there should only ever be one open at a time).
*
* @method closeAllSubMenus
*/
var closeAllSubMenus = function() {
$('.tool-lp-menu .tool-lp-sub-menu').attr('aria-hidden', 'true');
// Every menu's closed at this point, so set the menu active flag to false.
menuActive = false;
};
/**
* Constructor
*
* @param {jQuery} menuRoot Jquery collection matching the root of the menu.
* @param {Function[]} handlers called when a menu item is chosen.
*/
var Menubar = function(menuRoot, handlers) {
// Setup private class variables.
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 = false;
this.keys = {
tab: 9,
enter: 13,
esc: 27,
space: 32,
left: 37,
up: 38,
right: 39,
down: 40
};
this.addAriaAttributes();
// Add the event listeners.
this.addEventListeners();
};
/**
* Open a submenu, first it closes all other sub-menus and sets the open direction.
* @method openSubMenu
* @param {Node} menu
*/
Menubar.prototype.openSubMenu = function(menu) {
this.setOpenDirection();
closeAllSubMenus();
menu.attr('aria-hidden', 'false');
// Set menu active flag to true when a menu is opened.
menuActive = true;
};
/**
* Bind the event listeners to the DOM
* @method addEventListeners
*/
Menubar.prototype.addEventListeners = function() {
var currentThis = this;
// When clicking outside the menubar.
if (documentClickHandlerRegistered === false) {
$(document).click(function() {
// Check if a menu is opened.
if (menuActive) {
// Close menu.
closeAllSubMenus();
}
});
// Set this flag to true so that we won't need to add a document click handler for the other Menubar instances.
documentClickHandlerRegistered = true;
}
// Hovers.
this.subMenuItems.mouseenter(function() {
$(this).addClass('menu-hover');
return true;
});
this.subMenuItems.mouseout(function() {
$(this).removeClass('menu-hover');
return true;
});
// Mouse listeners.
this.allItems.click(function(e) {
return currentThis.handleClick($(this), e);
});
// Key listeners.
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));
});
};
/**
* Process click events for the top menus.
*
* @method handleClick
* @param {Object} item is the jquery object of the item firing the event
* @param {Event} e is the associated event object
* @return {boolean} Returns false
*/
Menubar.prototype.handleClick = function(item, e) {
e.stopPropagation();
var parentUL = item.parent();
if (parentUL.is('.tool-lp-menu')) {
// Toggle the child menu open/closed.
if (item.children('ul').first().attr('aria-hidden') == 'true') {
this.openSubMenu(item.children('ul').first());
} else {
item.children('ul').first().attr('aria-hidden', 'true');
}
} else {
// Remove hover and focus styling.
this.allItems.removeClass('menu-hover menu-focus');
// Clear the active item.
this.activeItem = null;
// Close the menu.
this.menuRoot.find('ul').not('.root-level').attr('aria-hidden', 'true');
// Follow any link, or call the click handlers.
var anchor = item.find('a').first();
var clickEvent = new $.Event('click');
clickEvent.target = anchor;
var eventHandled = false;
if (this.handlers) {
$.each(this.handlers, function(selector, handler) {
if (eventHandled) {
return;
}
if (item.find(selector).length > 0) {
var callable = $.proxy(handler, anchor);
// False means stop propogatting events.
eventHandled = (callable(clickEvent) === false) || clickEvent.isDefaultPrevented();
}
});
}
// If we didn't find a handler, and the HREF is # that probably means that
// we are handling it from somewhere else. Let's just do nothing in that case.
if (!eventHandled && anchor.attr('href') !== '#') {
window.location.href = anchor.attr('href');
}
}
return false;
};
/*
* Process focus events for the menu.
*
* @method handleFocus
* @param {Object} item is the jquery object of the item firing the event
* @return boolean Returns false
*/
Menubar.prototype.handleFocus = function(item) {
// If activeItem is null, we are getting focus from outside the menu. Store
// the item that triggered the event.
if (this.activeItem === null) {
this.activeItem = item;
} else if (item[0] != this.activeItem[0]) {
return true;
}
// Get the set of jquery objects for all the parent items of the active item.
var parentItems = this.activeItem.parentsUntil('ul.tool-lp-menu').filter('li');
// Remove focus styling from all other menu items.
this.allItems.removeClass('menu-focus');
// Add focus styling to the active item.
this.activeItem.addClass('menu-focus');
// Add focus styling to all parent items.
parentItems.addClass('menu-focus');
// If the bChildOpen flag has been set, open the active item's child menu (if applicable).
if (this.isChildOpen === true) {
var itemUL = item.parent();
// If the itemUL is a root-level menu and item is a parent item,
// show the child menu.
if (itemUL.is('.tool-lp-menu') && (item.attr('aria-haspopup') == 'true')) {
this.openSubMenu(item.children('ul').first());
}
}
return true;
};
/*
* Process blur events for the menu.
*
* @method handleBlur
* @param {Object} item is the jquery object of the item firing the event
* @return boolean Returns false
*/
Menubar.prototype.handleBlur = function(item) {
item.removeClass('menu-focus');
return true;
};
/*
* Determine if the menu should open to the left, or the right,
* based on the screen size and menu position.
* @method setOpenDirection
*/
Menubar.prototype.setOpenDirection = function() {
var pos = this.menuRoot.offset();
var isRTL = $(document.body).hasClass('dir-rtl');
var openLeft = true;
var heightmenuRoot = this.rootMenus.outerHeight();
var widthmenuRoot = this.rootMenus.outerWidth();
// Sometimes the menuMinWidth is not enough to figure out if menu exceeds the window width.
// So we have to calculate the real menu width.
var subMenuContainer = this.rootMenus.find('ul.tool-lp-sub-menu');
// Reset margins.
subMenuContainer.css('margin-right', '');
subMenuContainer.css('margin-left', '');
subMenuContainer.css('margin-top', '');
subMenuContainer.attr('aria-hidden', false);
var menuRealWidth = subMenuContainer.outerWidth(),
menuRealHeight = subMenuContainer.outerHeight();
var margintop = null,
marginright = null,
marginleft = null;
var top = pos.top - $(window).scrollTop();
// Top is the same for RTL and LTR.
if (top + menuRealHeight > $(window).height()) {
margintop = menuRealHeight + heightmenuRoot;
subMenuContainer.css('margin-top', '-' + margintop + 'px');
}
if (isRTL) {
if (pos.left - menuRealWidth < 0) {
marginright = menuRealWidth - widthmenuRoot;
subMenuContainer.css('margin-right', '-' + marginright + 'px');
}
} else {
if (pos.left + menuRealWidth > $(window).width()) {
marginleft = menuRealWidth - widthmenuRoot;
subMenuContainer.css('margin-left', '-' + marginleft + 'px');
}
}
if (openLeft) {
this.menuRoot.addClass('tool-lp-menu-open-left');
} else {
this.menuRoot.removeClass('tool-lp-menu-open-left');
}
};
/*
* Process keyDown events for the menu.
*
* @method handleKeyDown
* @param {Object} item is the jquery object of the item firing the event
* @param {Event} e is the associated event object
* @return boolean Returns false if consuming the event
*/
Menubar.prototype.handleKeyDown = function(item, e) {
if (e.altKey || e.ctrlKey) {
// Modifier key pressed: Do not process.
return true;
}
switch (e.keyCode) {
case this.keys.tab: {
// Hide all menu items and update their aria attributes.
this.menuRoot.find('ul').attr('aria-hidden', 'true');
// Remove focus styling from all menu items.
this.allItems.removeClass('menu-focus');
this.activeItem = null;
this.isChildOpen = false;
break;
}
case this.keys.esc: {
var itemUL = item.parent();
if (itemUL.is('.tool-lp-menu')) {
// Hide the child menu and update the aria attributes.
item.children('ul').first().attr('aria-hidden', 'true');
} else {
// Move up one level.
this.activeItem = itemUL.parent();
// Reset the isChildOpen flag.
this.isChildOpen = false;
// Set focus on the new item.
this.activeItem.focus();
// Hide the active menu and update the aria attributes.
itemUL.attr('aria-hidden', 'true');
}
e.stopPropagation();
return false;
}
case this.keys.enter:
case this.keys.space: {
// Trigger click handler.
return this.handleClick(item, e);
}
case this.keys.left: {
this.activeItem = this.moveToPrevious(item);
this.activeItem.focus();
e.stopPropagation();
return false;
}
case this.keys.right: {
this.activeItem = this.moveToNext(item);
this.activeItem.focus();
e.stopPropagation();
return false;
}
case this.keys.up: {
this.activeItem = this.moveUp(item);
this.activeItem.focus();
e.stopPropagation();
return false;
}
case this.keys.down: {
this.activeItem = this.moveDown(item);
this.activeItem.focus();
e.stopPropagation();
return false;
}
}
return true;
};
/**
* Move to the next menu level.
* This will be either the next root-level menu or the child of a menu parent. If
* at the root level and the active item is the last in the menu, this function will loop
* to the first menu item.
*
* If the menu is a horizontal menu, the first child element of the newly selected menu will
* be selected
*
* @method moveToNext
* @param {Object} item is the active menu item
* @return {Object} Returns the item to move to. Returns item is no move is possible
*/
Menubar.prototype.moveToNext = function(item) {
// Item's containing menu.
var itemUL = item.parent();
// The items in the currently active menu.
var menuItems = itemUL.children('li');
// The number of items in the active menu.
var menuNum = menuItems.length;
// The items index in its menu.
var menuIndex = menuItems.index(item);
var newItem = null;
var childMenu = null;
if (itemUL.is('.tool-lp-menu')) {
// This is the root level move to next sibling. This will require closing
// the current child menu and opening the new one.
if (menuIndex < menuNum - 1) {
// Not the last root menu.
newItem = item.next();
} else { // Wrap to first item.
newItem = menuItems.first();
}
// Close the current child menu (if applicable).
if (item.attr('aria-haspopup') == 'true') {
childMenu = item.children('ul').first();
if (childMenu.attr('aria-hidden') == 'false') {
// Update the child menu's aria-hidden attribute.
childMenu.attr('aria-hidden', 'true');
this.isChildOpen = true;
}
}
// Remove the focus styling from the current menu.
item.removeClass('menu-focus');
// Open the new child menu (if applicable).
if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {
childMenu = newItem.children('ul').first();
// Update the child's aria-hidden attribute.
this.openSubMenu(childMenu);
}
} else {
// This is not the root level. If there is a child menu to be moved into, do that;
// otherwise, move to the next root-level menu if there is one.
if (item.attr('aria-haspopup') == 'true') {
childMenu = item.children('ul').first();
newItem = childMenu.children('li').first();
// Show the child menu and update its aria attributes.
this.openSubMenu(childMenu);
} else {
// At deepest level, move to the next root-level menu.
var parentMenus = null;
var rootItem = null;
// Get list of all parent menus for item, up to the root level.
parentMenus = item.parentsUntil('ul.tool-lp-menu').filter('ul').not('.tool-lp-menu');
// Hide the current menu and update its aria attributes accordingly.
parentMenus.attr('aria-hidden', 'true');
// Remove the focus styling from the active menu.
parentMenus.find('li').removeClass('menu-focus');
parentMenus.last().parent().removeClass('menu-focus');
// The containing root for the menu.
rootItem = parentMenus.last().parent();
menuIndex = this.rootMenus.index(rootItem);
// If this is not the last root menu item, move to the next one.
if (menuIndex < this.rootMenus.length - 1) {
newItem = rootItem.next();
} else {
// Loop.
newItem = this.rootMenus.first();
}
// Add the focus styling to the new menu.
newItem.addClass('menu-focus');
if (newItem.attr('aria-haspopup') == 'true') {
childMenu = newItem.children('ul').first();
newItem = childMenu.children('li').first();
// Show the child menu and update it's aria attributes.
this.openSubMenu(childMenu);
this.isChildOpen = true;
}
}
}
return newItem;
};
/**
* Member function to move to the previous menu level.
* This will be either the previous root-level menu or the child of a menu parent. If
* at the root level and the active item is the first in the menu, this function will loop
* to the last menu item.
*
* If the menu is a horizontal menu, the first child element of the newly selected menu will
* be selected
*
* @method moveToPrevious
* @param {Object} item is the active menu item
* @return {Object} Returns the item to move to. Returns item is no move is possible
*/
Menubar.prototype.moveToPrevious = function(item) {
// Item's containing menu.
var itemUL = item.parent();
// The items in the currently active menu.
var menuItems = itemUL.children('li');
// The items index in its menu.
var menuIndex = menuItems.index(item);
var newItem = null;
var childMenu = null;
if (itemUL.is('.tool-lp-menu')) {
// This is the root level move to previous sibling. This will require closing
// the current child menu and opening the new one.
if (menuIndex > 0) {
// Not the first root menu.
newItem = item.prev();
} else {
// Wrap to last item.
newItem = menuItems.last();
}
// Close the current child menu (if applicable).
if (item.attr('aria-haspopup') == 'true') {
childMenu = item.children('ul').first();
if (childMenu.attr('aria-hidden') == 'false') {
// Update the child menu's aria-hidden attribute.
childMenu.attr('aria-hidden', 'true');
this.isChildOpen = true;
}
}
// Remove the focus styling from the current menu.
item.removeClass('menu-focus');
// Open the new child menu (if applicable).
if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {
childMenu = newItem.children('ul').first();
// Update the child's aria-hidden attribute.
this.openSubMenu(childMenu);
}
} else {
// This is not the root level. If there is a parent menu that is not the
// root menu, move up one level; otherwise, move to first item of the previous
// root menu.
var parentLI = itemUL.parent();
var parentUL = parentLI.parent();
// If this is a vertical menu or is not the first child menu
// of the root-level menu, move up one level.
if (!parentUL.is('.tool-lp-menu')) {
newItem = itemUL.parent();
// Hide the active menu and update aria-hidden.
itemUL.attr('aria-hidden', 'true');
// Remove the focus highlight from the item.
item.removeClass('menu-focus');
} else {
// Move to previous root-level menu.
// Hide the current menu and update the aria attributes accordingly.
itemUL.attr('aria-hidden', 'true');
// Remove the focus styling from the active menu.
item.removeClass('menu-focus');
parentLI.removeClass('menu-focus');
menuIndex = this.rootMenus.index(parentLI);
if (menuIndex > 0) {
// Move to the previous root-level menu.
newItem = parentLI.prev();
} else {
// Loop to last root-level menu.
newItem = this.rootMenus.last();
}
// Add the focus styling to the new menu.
newItem.addClass('menu-focus');
if (newItem.attr('aria-haspopup') == 'true') {
childMenu = newItem.children('ul').first();
// Show the child menu and update it's aria attributes.
this.openSubMenu(childMenu);
this.isChildOpen = true;
newItem = childMenu.children('li').first();
}
}
}
return newItem;
};
/**
* Member function to select the next item in a menu.
* If the active item is the last in the menu, this function will loop to the
* first menu item.
*
* @method moveDown
* @param {Object} item is the active menu item
* @param {String} startChr is the character to attempt to match against the beginning of the
* menu item titles. If found, focus moves to the next menu item beginning with that character.
* @return {Object} Returns the item to move to. Returns item is no move is possible
*/
Menubar.prototype.moveDown = function(item, startChr) {
// Item's containing menu.
var itemUL = item.parent();
// The items in the currently active menu.
var menuItems = itemUL.children('li').not('.separator');
// The number of items in the active menu.
var menuNum = menuItems.length;
// The items index in its menu.
var menuIndex = menuItems.index(item);
var newItem = null;
var newItemUL = null;
if (itemUL.is('.tool-lp-menu')) {
// This is the root level menu.
if (item.attr('aria-haspopup') != 'true') {
// No child menu to move to.
return item;
}
// Move to the first item in the child menu.
newItemUL = item.children('ul').first();
newItem = newItemUL.children('li').first();
// Make sure the child menu is visible.
this.openSubMenu(newItemUL);
return newItem;
}
// If $item is not the last item in its menu, move to the next item. If startChr is specified, move
// to the next item with a title that begins with that character.
if (startChr) {
var match = false;
var curNdx = menuIndex + 1;
// Check if the active item was the last one on the list.
if (curNdx == menuNum) {
curNdx = 0;
}
// Iterate through the menu items (starting from the current item and wrapping) until a match is found
// or the loop returns to the current menu item.
while (curNdx != menuIndex) {
var titleChr = menuItems.eq(curNdx).html().charAt(0);
if (titleChr.toLowerCase() == startChr) {
match = true;
break;
}
curNdx = curNdx + 1;
if (curNdx == menuNum) {
// Reached the end of the list, start again at the beginning.
curNdx = 0;
}
}
if (match === true) {
newItem = menuItems.eq(curNdx);
// Remove the focus styling from the current item.
item.removeClass('menu-focus');
return newItem;
} else {
return item;
}
} else {
if (menuIndex < menuNum - 1) {
newItem = menuItems.eq(menuIndex + 1);
} else {
newItem = menuItems.first();
}
}
// Remove the focus styling from the current item.
item.removeClass('menu-focus');
return newItem;
};
/**
* Function moveUp() is a member function to select the previous item in a menu.
* If the active item is the first in the menu, this function will loop to the
* last menu item.
*
* @method moveUp
* @param {Object} item is the active menu item
* @return {Object} Returns the item to move to. Returns item is no move is possible
*/
Menubar.prototype.moveUp = function(item) {
// Item's containing menu.
var itemUL = item.parent();
// The items in the currently active menu.
var menuItems = itemUL.children('li').not('.separator');
// The items index in its menu.
var menuIndex = menuItems.index(item);
var newItem = null;
if (itemUL.is('.tool-lp-menu')) {
// This is the root level menu.
// Nothing to do.
return item;
}
// If item is not the first item in its menu, move to the previous item.
if (menuIndex > 0) {
newItem = menuItems.eq(menuIndex - 1);
} else {
// Loop to top of menu.
newItem = menuItems.last();
}
// Remove the focus styling from the current item.
item.removeClass('menu-focus');
return newItem;
};
/**
* Enhance the dom with aria attributes.
* @method addAriaAttributes
*/
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');
// For CSS styling and effects.
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');
};
return /** @alias module:tool_lp/menubar */ {
/**
* Create a menu bar object for every node matching the selector.
*
* The expected DOM structure is shown below.
* <ul> <- This is the target of the selector parameter.
* <li> <- This is repeated for each top level menu.
* Text <- This is the text for the top level menu.
* <ul> <- This is a list of the entries in this top level menu.
* <li> <- This is repeated for each menu entry.
* <a href="someurl">Choice 1</a> <- The anchor for the menu.
* </li>
* </ul>
* </li>
* </ul>
*
* @method enhance
* @param {String} selector - The selector for the outer most menu node.
* @param {Function} handler - Javascript handler for when a menu item was chosen. If the
* handler returns true (or does not exist), the
* menu will look for an anchor with a link to follow.
* For example, if the menu entry has a "data-action" attribute
* and we want to call a javascript function when that entry is chosen,
* we could pass a list of handlers like this:
* { "[data-action='add']" : callAddFunction }
*/
enhance: function(selector, handler) {
$(selector).each(function(index, element) {
var menuRoot = $(element);
// Don't enhance the same menu twice.
if (menuRoot.data("menubarEnhanced") !== true) {
(new Menubar(menuRoot, handler));
menuRoot.data("menubarEnhanced", true);
}
});
},
/**
* Handy function to close all open menus anywhere on the page.
* @method closeAll
*/
closeAll: closeAllSubMenus
};
});
@@ -0,0 +1,63 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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(['jquery'], function($) {
/**
* ModuleNavigation
*
* @class tool_lp/module_navigation
* @param {String} moduleSelector The selector of the module element.
* @param {String} baseUrl The base url for the page (no params).
* @param {Number} courseId The course id
* @param {Number} moduleId The activity module (filter)
*/
var ModuleNavigation = function(moduleSelector, baseUrl, courseId, moduleId) {
this._baseUrl = baseUrl;
this._moduleId = moduleId;
this._courseId = courseId;
$(moduleSelector).on('change', this._moduleChanged.bind(this));
};
/**
* The module was changed in the select list.
*
* @method _moduleChanged
* @param {Event} e the event
*/
ModuleNavigation.prototype._moduleChanged = function(e) {
var newModuleId = $(e.target).val();
var queryStr = '?mod=' + newModuleId + '&courseid=' + this._courseId;
document.location = this._baseUrl + queryStr;
};
/** @property {Number} The id of the course. */
ModuleNavigation.prototype._courseId = null;
/** @property {Number} The id of the module. */
ModuleNavigation.prototype._moduleId = null;
/** @property {String} Plugin base url. */
ModuleNavigation.prototype._baseUrl = null;
return ModuleNavigation;
});

Some files were not shown because too many files have changed in this diff Show More