diff --git a/admin/tool/lp/amd/build/competency_rule.min.js.map b/admin/tool/lp/amd/build/competency_rule.min.js.map index c3ec4debeb38f..1ca5191e83602 100644 --- a/admin/tool/lp/amd/build/competency_rule.min.js.map +++ b/admin/tool/lp/amd/build/competency_rule.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/competency_rule.js"],"names":["define","$","Rule","tree","_eventNode","_ready","Deferred","_tree","prototype","_competency","canConfig","hasChildren","id","getConfig","getType","Error","init","_load","injectTemplate","reject","promise","isValid","when","on","type","handler","setTargetCompetency","competency","_trigger","data","trigger","_triggerChange"],"mappings":"AAuBAA,OAAM,2BAAC,CAAC,QAAD,CAAD,CAAa,SAASC,CAAT,CAAY,CAa3B,GAAIC,CAAAA,CAAI,CAAG,SAASC,CAAT,CAAe,CACtB,KAAKC,UAAL,CAAkBH,CAAC,CAAC,OAAD,CAAnB,CACA,KAAKI,MAAL,CAAcJ,CAAC,CAACK,QAAF,EAAd,CACA,KAAKC,KAAL,CAAaJ,CAChB,CAJD,CAOAD,CAAI,CAACM,SAAL,CAAeC,WAAf,CAA6B,IAA7B,CAEAP,CAAI,CAACM,SAAL,CAAeJ,UAAf,CAA4B,IAA5B,CAEAF,CAAI,CAACM,SAAL,CAAeH,MAAf,CAAwB,IAAxB,CAEAH,CAAI,CAACM,SAAL,CAAeD,KAAf,CAAuB,IAAvB,CAQAL,CAAI,CAACM,SAAL,CAAeE,SAAf,CAA2B,UAAW,CAClC,MAAO,MAAKH,KAAL,CAAWI,WAAX,CAAuB,KAAKF,WAAL,CAAiBG,EAAxC,CACV,CAFD,CAYAV,CAAI,CAACM,SAAL,CAAeK,SAAf,CAA2B,UAAW,CAClC,MAAO,KACV,CAFD,CAYAX,CAAI,CAACM,SAAL,CAAeM,OAAf,CAAyB,UAAW,CAChC,KAAM,IAAIC,CAAAA,KAAJ,CAAU,iBAAV,CACT,CAFD,CAYAb,CAAI,CAACM,SAAL,CAAeQ,IAAf,CAAsB,UAAW,CAC7B,MAAO,MAAKC,KAAL,EACV,CAFD,CAWAf,CAAI,CAACM,SAAL,CAAeU,cAAf,CAAgC,UAAW,CACvC,MAAOjB,CAAAA,CAAC,CAACK,QAAF,GAAaa,MAAb,GAAsBC,OAAtB,EACV,CAFD,CAYAlB,CAAI,CAACM,SAAL,CAAea,OAAf,CAAyB,UAAW,CAChC,QACH,CAFD,CAWAnB,CAAI,CAACM,SAAL,CAAeS,KAAf,CAAuB,UAAW,CAC9B,MAAOhB,CAAAA,CAAC,CAACqB,IAAF,EACV,CAFD,CAWApB,CAAI,CAACM,SAAL,CAAee,EAAf,CAAoB,SAASC,CAAT,CAAeC,CAAf,CAAwB,CACxC,KAAKrB,UAAL,CAAgBmB,EAAhB,CAAmBC,CAAnB,CAAyBC,CAAzB,CACH,CAFD,CAUAvB,CAAI,CAACM,SAAL,CAAekB,mBAAf,CAAqC,SAASC,CAAT,CAAqB,CACtD,KAAKlB,WAAL,CAAmBkB,CACtB,CAFD,CAYAzB,CAAI,CAACM,SAAL,CAAeoB,QAAf,CAA0B,SAASJ,CAAT,CAAeK,CAAf,CAAqB,CAC3C,KAAKzB,UAAL,CAAgB0B,OAAhB,CAAwBN,CAAxB,CAA8B,CAACK,CAAD,CAA9B,CACH,CAFD,CAUA3B,CAAI,CAACM,SAAL,CAAeuB,cAAf,CAAgC,UAAW,CACvC,KAAKH,QAAL,CAAc,QAAd,CAAwB,IAAxB,CACH,CAFD,CAIA,MAAoD1B,CAAAA,CAEvD,CAzJK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Competency rule base module.\n *\n * @module tool_lp/competencyrule\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'], function($) {\n\n /**\n * Competency rule abstract class.\n *\n * Any competency rule should extend this object. The event 'change' should be\n * triggered on the instance when the configuration has changed. This will allow\n * the components using the rule to gather the config, or check its validity.\n *\n * this._triggerChange();\n *\n * @param {Tree} tree The competency tree.\n */\n var Rule = function(tree) {\n this._eventNode = $('
');\n this._ready = $.Deferred();\n this._tree = tree;\n };\n\n /** @property {Object} The current competency. */\n Rule.prototype._competency = null;\n /** @property {Node} The node we attach the events to. */\n Rule.prototype._eventNode = null;\n /** @property {Promise} Resolved when the object is ready. */\n Rule.prototype._ready = null;\n /** @property {Tree} The competency tree. */\n Rule.prototype._tree = null;\n\n /**\n * Whether or not the current competency can be configured using this rule.\n *\n * @return {Boolean}\n * @method canConfig\n */\n Rule.prototype.canConfig = function() {\n return this._tree.hasChildren(this._competency.id);\n };\n\n /**\n * The config established by this rule.\n *\n * To override in subclasses when relevant.\n *\n * @return {String|null}\n * @method getConfig\n */\n Rule.prototype.getConfig = function() {\n return null;\n };\n\n // eslint-disable-line valid-jsdoc\n /**\n * Return the type of the module.\n *\n * @return {String}\n * @method getType\n */\n // eslint-enable-line valid-jsdoc\n Rule.prototype.getType = function() {\n throw new Error('Not implemented');\n };\n\n /**\n * The init process.\n *\n * Do not override this, instead override _load.\n *\n * @return {Promise} Revoled when the plugin is initialised.\n * @method init\n */\n Rule.prototype.init = function() {\n return this._load();\n };\n\n /**\n * Callback to inject the template.\n *\n * @param {Node} container Node to inject in.\n * @return {Promise} Resolved when done.\n * @method injectTemplate\n */\n Rule.prototype.injectTemplate = function() {\n return $.Deferred().reject().promise();\n };\n\n /**\n * Whether or not the current config is valid.\n *\n * Plugins should override this.\n *\n * @return {Boolean}\n * @method _isValid\n */\n Rule.prototype.isValid = function() {\n return false;\n };\n\n /**\n * Load the class.\n *\n * @return {Promise}\n * @method _load\n * @protected\n */\n Rule.prototype._load = function() {\n return $.when();\n };\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 Rule.prototype.on = function(type, handler) {\n this._eventNode.on(type, handler);\n };\n\n /**\n * Sets the current competency.\n *\n * @param {Competency} competency\n * @method setTargetCompetency\n */\n Rule.prototype.setTargetCompetency = function(competency) {\n this._competency = competency;\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 * @protected\n */\n Rule.prototype._trigger = function(type, data) {\n this._eventNode.trigger(type, [data]);\n };\n\n /**\n * Trigger the change event.\n *\n * @method _triggerChange\n * @protected\n */\n Rule.prototype._triggerChange = function() {\n this._trigger('change', this);\n };\n\n return /** @alias module:tool_lp/competency_rule */ Rule;\n\n});\n"],"file":"competency_rule.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/competency_rule.js"],"names":["define","$","Rule","tree","_eventNode","_ready","Deferred","_tree","prototype","_competency","canConfig","hasChildren","id","getConfig","getType","Error","init","_load","injectTemplate","reject","promise","isValid","when","on","type","handler","setTargetCompetency","competency","_trigger","data","trigger","_triggerChange"],"mappings":"AAuBAA,OAAM,2BAAC,CAAC,QAAD,CAAD,CAAa,SAASC,CAAT,CAAY,CAa3B,GAAIC,CAAAA,CAAI,CAAG,SAASC,CAAT,CAAe,CACtB,KAAKC,UAAL,CAAkBH,CAAC,CAAC,OAAD,CAAnB,CACA,KAAKI,MAAL,CAAcJ,CAAC,CAACK,QAAF,EAAd,CACA,KAAKC,KAAL,CAAaJ,CAChB,CAJD,CAOAD,CAAI,CAACM,SAAL,CAAeC,WAAf,CAA6B,IAA7B,CAEAP,CAAI,CAACM,SAAL,CAAeJ,UAAf,CAA4B,IAA5B,CAEAF,CAAI,CAACM,SAAL,CAAeH,MAAf,CAAwB,IAAxB,CAEAH,CAAI,CAACM,SAAL,CAAeD,KAA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,KAAKH,QAAL,CAAc,QAAd,CAAwB,IAAxB,CACH,CAFD,CAIA,MAAoD1B,CAAAA,CAEvD,CAxJK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Competency rule base module.\n *\n * @module tool_lp/competencyrule\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'], function($) {\n\n /**\n * Competency rule abstract class.\n *\n * Any competency rule should extend this object. The event 'change' should be\n * triggered on the instance when the configuration has changed. This will allow\n * the components using the rule to gather the config, or check its validity.\n *\n * this._triggerChange();\n *\n * @param {Tree} tree The competency tree.\n */\n var Rule = function(tree) {\n this._eventNode = $('
');\n this._ready = $.Deferred();\n this._tree = tree;\n };\n\n /** @property {Object} The current competency. */\n Rule.prototype._competency = null;\n /** @property {Node} The node we attach the events to. */\n Rule.prototype._eventNode = null;\n /** @property {Promise} Resolved when the object is ready. */\n Rule.prototype._ready = null;\n /** @property {Tree} The competency tree. */\n Rule.prototype._tree = null;\n\n /**\n * Whether or not the current competency can be configured using this rule.\n *\n * @return {Boolean}\n * @method canConfig\n */\n Rule.prototype.canConfig = function() {\n return this._tree.hasChildren(this._competency.id);\n };\n\n /**\n * The config established by this rule.\n *\n * To override in subclasses when relevant.\n *\n * @return {String|null}\n * @method getConfig\n */\n Rule.prototype.getConfig = function() {\n return null;\n };\n\n // eslint-disable-line valid-jsdoc\n /**\n * Return the type of the module.\n *\n * @return {String}\n * @method getType\n */\n // eslint-enable-line valid-jsdoc\n Rule.prototype.getType = function() {\n throw new Error('Not implemented');\n };\n\n /**\n * The init process.\n *\n * Do not override this, instead override _load.\n *\n * @return {Promise} Revoled when the plugin is initialised.\n * @method init\n */\n Rule.prototype.init = function() {\n return this._load();\n };\n\n /**\n * Callback to inject the template.\n *\n * @returns {Promise} Resolved when done.\n * @method injectTemplate\n */\n Rule.prototype.injectTemplate = function() {\n return $.Deferred().reject().promise();\n };\n\n /**\n * Whether or not the current config is valid.\n *\n * Plugins should override this.\n *\n * @return {Boolean}\n * @method _isValid\n */\n Rule.prototype.isValid = function() {\n return false;\n };\n\n /**\n * Load the class.\n *\n * @return {Promise}\n * @method _load\n * @protected\n */\n Rule.prototype._load = function() {\n return $.when();\n };\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 Rule.prototype.on = function(type, handler) {\n this._eventNode.on(type, handler);\n };\n\n /**\n * Sets the current competency.\n *\n * @param {Competency} competency\n * @method setTargetCompetency\n */\n Rule.prototype.setTargetCompetency = function(competency) {\n this._competency = competency;\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 * @protected\n */\n Rule.prototype._trigger = function(type, data) {\n this._eventNode.trigger(type, [data]);\n };\n\n /**\n * Trigger the change event.\n *\n * @method _triggerChange\n * @protected\n */\n Rule.prototype._triggerChange = function() {\n this._trigger('change', this);\n };\n\n return /** @alias module:tool_lp/competency_rule */ Rule;\n\n});\n"],"file":"competency_rule.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/competencydialogue.min.js.map b/admin/tool/lp/amd/build/competencydialogue.min.js.map index fda23b89f55a8..9ed99d48920cb 100644 --- a/admin/tool/lp/amd/build/competencydialogue.min.js.map +++ b/admin/tool/lp/amd/build/competencydialogue.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/competencydialogue.js"],"names":["define","$","notification","ajax","templates","str","Dialogue","instance","Competencydialogue","prototype","triggerCompetencyViewedEvent","competencyId","call","methodname","args","id","showDialogue","competencyid","options","datapromise","getCompetencyDataPromise","localthis","done","data","render","html","competency","shortname","fail","exception","showDialogueFromData","dataSource","enhanceDialogue","clickEventHandler","e","compdialogue","currentTarget","includerelated","includecourses","preventDefault","requests","then","context","init","delegate","bind"],"mappings":"AAsBAA,OAAM,8BAAC,CAAC,QAAD,CACC,mBADD,CAEC,WAFD,CAGC,gBAHD,CAIC,UAJD,CAKC,kBALD,CAAD,CAMC,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAgCC,CAAhC,CAA2CC,CAA3C,CAAgDC,CAAhD,CAA0D,IAOzDC,CAAAA,CAPyD,CAezDC,CAAkB,CAAG,UAAW,CAEnC,CAjB4D,CAyB7DA,CAAkB,CAACC,SAAnB,CAA6BC,4BAA7B,CAA4D,SAASC,CAAT,CAAuB,CAC/ER,CAAI,CAACS,IAAL,CAAU,CAAC,CACHC,UAAU,CAAE,mCADT,CAEHC,IAAI,CAAE,CAACC,EAAE,CAAEJ,CAAL,CAFH,CAAD,CAAV,CAIH,CALD,CAcAH,CAAkB,CAACC,SAAnB,CAA6BO,YAA7B,CAA4C,SAASC,CAAT,CAAuBC,CAAvB,CAAgC,IAEpEC,CAAAA,CAAW,CAAG,KAAKC,wBAAL,CAA8BH,CAA9B,CAA4CC,CAA5C,CAFsD,CAGpEG,CAAS,CAAG,IAHwD,CAIxEF,CAAW,CAACG,IAAZ,CAAiB,SAASC,CAAT,CAAe,CAE5BnB,CAAS,CAACoB,MAAV,CAAiB,4BAAjB,CAA+CD,CAA/C,EACKD,IADL,CACU,SAASG,CAAT,CAAe,CAEjBJ,CAAS,CAACX,4BAAV,CAAuCO,CAAvC,EAGA,GAAIX,CAAAA,CAAJ,CACIiB,CAAI,CAACG,UAAL,CAAgBC,SADpB,CAEIF,CAFJ,CAIH,CAVL,EAUOG,IAVP,CAUY1B,CAAY,CAAC2B,SAVzB,CAWH,CAbD,EAaGD,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A,CAAf,CACEoB,cAAc,CAAEnB,CAAO,CAACmB,cAAR,IADlB,CAEEC,cAAc,CAAEpB,CAAO,CAACoB,cAAR,IAFlB,CADR,CADqB,CAAV,CAAf,CASA,MAAOE,CAAAA,CAAQ,CAAC,CAAD,CAAR,CAAYC,IAAZ,CAAiB,SAASC,CAAT,CAAkB,CACvC,MAAOA,CAAAA,CACT,CAFM,EAEJd,IAFI,CAEC1B,CAAY,CAAC2B,SAFd,CAGV,CAdD,CAgBA,MAAuD,CAOnDc,IAAI,CAAE,eAAW,CACb,GAAwB,WAApB,QAAOpC,CAAAA,CAAX,CAAqC,CACjC,MACH,CAGDA,CAAQ,CAAG,GAAIC,CAAAA,CAAf,CACAP,CAAC,CAAC,MAAD,CAAD,CAAU2C,QAAV,CAAmB,uCAAnB,CAA0D,OAA1D,CAAmE,CAACT,YAAY,CAAE5B,CAAf,CAAnE,CACIA,CAAQ,CAAC0B,iBAAT,CAA2BY,IAA3B,CAAgCtC,CAAhC,CADJ,CAEH,CAhBkD,CAkB1D,CAzJK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Display Competency in dialogue box.\n *\n * @module tool_lp/Competencydialogue\n * @copyright 2015 Issam Taboubi \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery',\n 'core/notification',\n 'core/ajax',\n 'core/templates',\n 'core/str',\n 'tool_lp/dialogue'],\n function($, notification, ajax, templates, str, Dialogue) {\n\n /**\n * The main instance we'll be working with.\n *\n * @type {Competencydialogue}\n */\n var instance;\n\n /**\n * Constructor for CompetencyDialogue.\n *\n * @param {Object} options\n *\n */\n var Competencydialogue = function() {\n // Intentionally left empty.\n };\n\n /**\n * Log the competency viewed event.\n *\n * @param {Number} competencyId The competency ID.\n * @method triggerCompetencyViewedEvent\n */\n Competencydialogue.prototype.triggerCompetencyViewedEvent = function(competencyId) {\n ajax.call([{\n methodname: 'core_competency_competency_viewed',\n args: {id: competencyId}\n }]);\n };\n\n /**\n * Display a dialogue box by competencyid.\n *\n * @param {Number} competencyid The competency ID.\n * @param {Object} options The options.\n * @method showDialogue\n */\n Competencydialogue.prototype.showDialogue = function(competencyid, options) {\n\n var datapromise = this.getCompetencyDataPromise(competencyid, options);\n var localthis = this;\n datapromise.done(function(data) {\n // Inner Html in the dialogue content.\n templates.render('tool_lp/competency_summary', data)\n .done(function(html) {\n // Log competency viewed event.\n localthis.triggerCompetencyViewedEvent(competencyid);\n\n // Show the dialogue.\n new Dialogue(\n data.competency.shortname,\n html\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n };\n\n /**\n * Display a dialogue box from data.\n *\n * @param {Object} dataSource data to be used to display dialogue box\n * @method showDialogueFromData\n */\n Competencydialogue.prototype.showDialogueFromData = function(dataSource) {\n\n var localthis = this;\n // Inner Html in the dialogue content.\n templates.render('tool_lp/competency_summary', dataSource)\n .done(function(html) {\n // Log competency viewed event.\n localthis.triggerCompetencyViewedEvent(dataSource.id);\n\n // Show the dialogue.\n new Dialogue(\n dataSource.shortname,\n html,\n localthis.enhanceDialogue\n );\n }).fail(notification.exception);\n };\n\n /**\n * The action on the click event.\n *\n * @param {Event} e event click\n * @method clickEventHandler\n */\n Competencydialogue.prototype.clickEventHandler = function(e) {\n\n var compdialogue = e.data.compdialogue;\n var currentTarget = $(e.currentTarget);\n var competencyid = currentTarget.data('id');\n var includerelated = !(currentTarget.data('excluderelated'));\n var includecourses = currentTarget.data('includecourses');\n\n // Show the dialogue box.\n compdialogue.showDialogue(competencyid, {\n includerelated: includerelated,\n includecourses: includecourses\n });\n e.preventDefault();\n };\n\n /**\n * Get a promise on data competency.\n *\n * @param {Number} competencyid\n * @param {Object} options\n * @return {Promise} return promise on data request\n * @method getCompetencyDataPromise\n */\n Competencydialogue.prototype.getCompetencyDataPromise = function(competencyid, options) {\n\n var requests = ajax.call([\n {methodname: 'tool_lp_data_for_competency_summary',\n args: {competencyid: competencyid,\n includerelated: options.includerelated || false,\n includecourses: options.includecourses || false\n }\n }\n ]);\n\n return requests[0].then(function(context) {\n return context;\n }).fail(notification.exception);\n };\n\n return /** @alias module:tool_lp/competencydialogue */ {\n\n /**\n * Initialise the competency dialogue module.\n *\n * Only the first call matters.\n */\n init: function() {\n if (typeof instance !== 'undefined') {\n return;\n }\n\n // Instantiate the one instance and delegate event on the body.\n instance = new Competencydialogue();\n $('body').delegate('[data-action=\"competency-dialogue\"]', 'click', {compdialogue: instance},\n instance.clickEventHandler.bind(instance));\n }\n };\n});\n"],"file":"competencydialogue.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/competencydialogue.js"],"names":["define","$","notification","ajax","templates","str","Dialogue","instance","Competencydialogue","prototype","triggerCompetencyViewedEvent","competencyId","call","methodname","args","id","showDialogue","competencyid","options","datapromise","getCompetencyDataPromise","localthis","done","data","render","html","competency","shortname","fail","exception","showDialogueFromData","dataSource","enhanceDialogue","clickEventHandler","e","compdialogue","currentTarget","includerelated","includecourses","preventDefault","requests","then","context","init","delegate","bind"],"mappings":"AAsBAA,OAAM,8BAAC,CAAC,QAAD,CACC,mBADD,CAEC,WAFD,CAGC,gBAHD,CAIC,UAJD,CAKC,kBALD,CAAD,CAMC,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAgCC,CAAhC,CAA2CC,CAA3C,CAAgDC,CAAhD,CAA0D,IAOzDC,CAAAA,CAPyD,CAYzDC,CAAkB,CAAG,UAAW,CAEnC,CAd4D,CAsB7DA,CAAkB,CAACC,SAAnB,CAA6BC,4BAA7B,CAA4D,SAASC,CAAT,CA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nE,CACIA,CAAQ,CAAC0B,iBAAT,CAA2BY,IAA3B,CAAgCtC,CAAhC,CADJ,CAEH,CAhBkD,CAkB1D,CAtJK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Display Competency in dialogue box.\n *\n * @module tool_lp/Competencydialogue\n * @copyright 2015 Issam Taboubi \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery',\n 'core/notification',\n 'core/ajax',\n 'core/templates',\n 'core/str',\n 'tool_lp/dialogue'],\n function($, notification, ajax, templates, str, Dialogue) {\n\n /**\n * The main instance we'll be working with.\n *\n * @type {Competencydialogue}\n */\n var instance;\n\n /**\n * Constructor for CompetencyDialogue.\n */\n var Competencydialogue = function() {\n // Intentionally left empty.\n };\n\n /**\n * Log the competency viewed event.\n *\n * @param {Number} competencyId The competency ID.\n * @method triggerCompetencyViewedEvent\n */\n Competencydialogue.prototype.triggerCompetencyViewedEvent = function(competencyId) {\n ajax.call([{\n methodname: 'core_competency_competency_viewed',\n args: {id: competencyId}\n }]);\n };\n\n /**\n * Display a dialogue box by competencyid.\n *\n * @param {Number} competencyid The competency ID.\n * @param {Object} options The options.\n * @method showDialogue\n */\n Competencydialogue.prototype.showDialogue = function(competencyid, options) {\n\n var datapromise = this.getCompetencyDataPromise(competencyid, options);\n var localthis = this;\n datapromise.done(function(data) {\n // Inner Html in the dialogue content.\n templates.render('tool_lp/competency_summary', data)\n .done(function(html) {\n // Log competency viewed event.\n localthis.triggerCompetencyViewedEvent(competencyid);\n\n // Show the dialogue.\n new Dialogue(\n data.competency.shortname,\n html\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n };\n\n /**\n * Display a dialogue box from data.\n *\n * @param {Object} dataSource data to be used to display dialogue box\n * @method showDialogueFromData\n */\n Competencydialogue.prototype.showDialogueFromData = function(dataSource) {\n\n var localthis = this;\n // Inner Html in the dialogue content.\n templates.render('tool_lp/competency_summary', dataSource)\n .done(function(html) {\n // Log competency viewed event.\n localthis.triggerCompetencyViewedEvent(dataSource.id);\n\n // Show the dialogue.\n new Dialogue(\n dataSource.shortname,\n html,\n localthis.enhanceDialogue\n );\n }).fail(notification.exception);\n };\n\n /**\n * The action on the click event.\n *\n * @param {Event} e event click\n * @method clickEventHandler\n */\n Competencydialogue.prototype.clickEventHandler = function(e) {\n\n var compdialogue = e.data.compdialogue;\n var currentTarget = $(e.currentTarget);\n var competencyid = currentTarget.data('id');\n var includerelated = !(currentTarget.data('excluderelated'));\n var includecourses = currentTarget.data('includecourses');\n\n // Show the dialogue box.\n compdialogue.showDialogue(competencyid, {\n includerelated: includerelated,\n includecourses: includecourses\n });\n e.preventDefault();\n };\n\n /**\n * Get a promise on data competency.\n *\n * @param {Number} competencyid\n * @param {Object} options\n * @return {Promise} return promise on data request\n * @method getCompetencyDataPromise\n */\n Competencydialogue.prototype.getCompetencyDataPromise = function(competencyid, options) {\n\n var requests = ajax.call([\n {methodname: 'tool_lp_data_for_competency_summary',\n args: {competencyid: competencyid,\n includerelated: options.includerelated || false,\n includecourses: options.includecourses || false\n }\n }\n ]);\n\n return requests[0].then(function(context) {\n return context;\n }).fail(notification.exception);\n };\n\n return /** @alias module:tool_lp/competencydialogue */ {\n\n /**\n * Initialise the competency dialogue module.\n *\n * Only the first call matters.\n */\n init: function() {\n if (typeof instance !== 'undefined') {\n return;\n }\n\n // Instantiate the one instance and delegate event on the body.\n instance = new Competencydialogue();\n $('body').delegate('[data-action=\"competency-dialogue\"]', 'click', {compdialogue: instance},\n instance.clickEventHandler.bind(instance));\n }\n };\n});\n"],"file":"competencydialogue.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/competencyruleconfig.min.js.map b/admin/tool/lp/amd/build/competencyruleconfig.min.js.map index d4bd21fbe3d66..27dcc816d1807 100644 --- a/admin/tool/lp/amd/build/competencyruleconfig.min.js.map +++ b/admin/tool/lp/amd/build/competencyruleconfig.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/competencyruleconfig.js"],"names":["define","$","Notification","Templates","Dialogue","Outcomes","Str","RuleConfig","tree","rulesModules","_eventNode","_tree","_rulesModules","_setUp","prototype","_competency","_outcomesOption","_popup","_ready","_rules","_afterChange","_isValid","_find","prop","_afterRuleConfigChange","e","rule","_getRule","_afterRender","self","on","_switchedOutcome","trigger","_switchedRule","_trigger","_getConfig","close","canBeConfigured","can","each","index","canConfig","display","when","get_string","_render","then","title","render","bind","fail","exception","selector","getContent","find","_getApplicableOutcomesOptions","options","outcome","push","code","name","selected","ruleoutcome","_getApplicableRulesOptions","_getRuleName","getType","type","ruletype","ruleconfig","getConfig","_getOutcome","val","result","modInfo","_initOutcomes","getAll","outcomes","_initRules","promises","promise","init","setTargetCompetency","splice","apply","NONE","isValid","handler","_preRender","ready","config","rules","context","competencyshortname","shortname","setTargetCompetencyId","competencyId","getCompetency","modules","Deferred","amd","require","arguments","Module","always","resolve","hide","empty","show","container","injectTemplate","catch","data"],"mappings":"AAuBAA,OAAM,gCAAC,CAAC,QAAD,CACC,mBADD,CAEC,gBAFD,CAGC,kBAHD,CAIC,6BAJD,CAKC,UALD,CAAD,CAME,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAqCC,CAArC,CAA+CC,CAA/C,CAAyDC,CAAzD,CAA8D,CAclE,GAAIC,CAAAA,CAAU,CAAG,SAASC,CAAT,CAAeC,CAAf,CAA6B,CAC1C,KAAKC,UAAL,CAAkBT,CAAC,CAAC,aAAD,CAAnB,CACA,KAAKU,KAAL,CAAaH,CAAb,CACA,KAAKI,aAA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H,CAlBD,CA4BAlG,CAAU,CAACO,SAAX,CAAqBoB,QAArB,CAAgC,SAASgC,CAAT,CAAe6C,CAAf,CAAqB,CACjD,KAAKrG,UAAL,CAAgBsB,OAAhB,CAAwBkC,CAAxB,CAA8B,CAAC6C,CAAD,CAA9B,CACH,CAFD,CAIA,MAAyDxG,CAAAA,CAE5D,CAzgBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Competency rule config.\n *\n * @module tool_lp/competencyruleconfig\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/notification',\n 'core/templates',\n 'tool_lp/dialogue',\n 'tool_lp/competency_outcomes',\n 'core/str'],\n function($, Notification, Templates, Dialogue, Outcomes, Str) {\n\n /**\n * Competency rule class.\n *\n * When implementing this you should attach a listener to the event 'save'\n * on the instance. E.g.\n *\n * var config = new RuleConfig(tree, modules);\n * config.on('save', function(e, config) { ... });\n *\n * @param {competencytree} tree The competency tree.\n * @param {Array} rulesModules The modules containing the rules: [{ typeName: { amd: amdModule, name: ruleName }}].\n */\n var RuleConfig = function(tree, rulesModules) {\n this._eventNode = $('
');\n this._tree = tree;\n this._rulesModules = rulesModules;\n this._setUp();\n };\n\n /** @property {Object} The current competency. */\n RuleConfig.prototype._competency = null;\n /** @property {Node} The node we attach the events to. */\n RuleConfig.prototype._eventNode = null;\n /** @property {Array} Outcomes options. */\n RuleConfig.prototype._outcomesOption = null;\n /** @property {Dialogue} The dialogue. */\n RuleConfig.prototype._popup = null;\n /** @property {Promise} Resolved when the module is ready. */\n RuleConfig.prototype._ready = null;\n /** @property {Array} The rules. */\n RuleConfig.prototype._rules = null;\n /** @property {Array} The rules modules. */\n RuleConfig.prototype._rulesModules = null;\n /** @property {competencytree} The competency tree. */\n RuleConfig.prototype._tree = null;\n\n /**\n * After change.\n *\n * Triggered when a change occured.\n *\n * @method _afterChange\n * @protected\n */\n RuleConfig.prototype._afterChange = function() {\n if (!this._isValid()) {\n this._find('[data-action=\"save\"]').prop('disabled', true);\n } else {\n this._find('[data-action=\"save\"]').prop('disabled', false);\n }\n };\n\n /**\n * After change in rule's config.\n *\n * Triggered when a change occured in a specific rule config.\n *\n * @method _afterRuleConfigChange\n * @protected\n * @param {Event} e\n * @param {Rule} rule\n */\n RuleConfig.prototype._afterRuleConfigChange = function(e, rule) {\n if (rule != this._getRule()) {\n // This rule is not the current one any more, we can ignore.\n return;\n }\n this._afterChange();\n };\n\n /**\n * After render hook.\n *\n * @method _afterRender\n * @protected\n */\n RuleConfig.prototype._afterRender = function() {\n var self = this;\n\n self._find('[name=\"outcome\"]').on('change', function() {\n self._switchedOutcome();\n }).trigger('change');\n\n self._find('[name=\"rule\"]').on('change', function() {\n self._switchedRule();\n }).trigger('change');\n\n self._find('[data-action=\"save\"]').on('click', function() {\n self._trigger('save', self._getConfig());\n self.close();\n });\n\n self._find('[data-action=\"cancel\"]').on('click', function() {\n self.close();\n });\n };\n\n /**\n * Whether the current competency can be configured.\n *\n * @return {Boolean}\n * @method canBeConfigured\n */\n RuleConfig.prototype.canBeConfigured = function() {\n var can = false;\n $.each(this._rules, function(index, rule) {\n if (rule.canConfig()) {\n can = true;\n return;\n }\n });\n return can;\n };\n\n /**\n * Close the dialogue.\n *\n * @method close\n */\n RuleConfig.prototype.close = function() {\n this._popup.close();\n this._popup = null;\n };\n\n /**\n * Opens the picker.\n *\n * @param {Number} competencyId The competency ID of the competency to work on.\n * @method display\n * @return {Promise}\n */\n RuleConfig.prototype.display = function() {\n var self = this;\n if (!self._competency) {\n return false;\n }\n return $.when(Str.get_string('competencyrule', 'tool_lp'), self._render())\n .then(function(title, render) {\n self._popup = new Dialogue(\n title,\n render[0],\n self._afterRender.bind(self)\n );\n return;\n }).fail(Notification.exception);\n };\n\n /**\n * Find a node in the dialogue.\n *\n * @param {String} selector\n * @return {JQuery}\n * @method _find\n * @protected\n */\n RuleConfig.prototype._find = function(selector) {\n return $(this._popup.getContent()).find(selector);\n };\n\n /**\n * Get the applicable outcome options.\n *\n * @return {Array}\n * @method _getApplicableOutcomesOptions\n * @protected\n */\n RuleConfig.prototype._getApplicableOutcomesOptions = function() {\n var self = this,\n options = [];\n\n $.each(self._outcomesOption, function(index, outcome) {\n options.push({\n code: outcome.code,\n name: outcome.name,\n selected: (outcome.code == self._competency.ruleoutcome) ? true : false,\n });\n });\n\n return options;\n };\n\n /**\n * Get the applicable rules options.\n *\n * @return {Array}\n * @method _getApplicableRulesOptions\n * @protected\n */\n RuleConfig.prototype._getApplicableRulesOptions = function() {\n var self = this,\n options = [];\n\n $.each(self._rules, function(index, rule) {\n if (!rule.canConfig()) {\n return;\n }\n options.push({\n name: self._getRuleName(rule.getType()),\n type: rule.getType(),\n selected: (rule.getType() == self._competency.ruletype) ? true : false,\n });\n });\n\n return options;\n };\n\n /**\n * Get the full config for the competency.\n *\n * @return {Object} Contains rule, ruleoutcome and ruleconfig.\n * @method _getConfig\n * @protected\n */\n RuleConfig.prototype._getConfig = function() {\n var rule = this._getRule();\n return {\n ruletype: rule ? rule.getType() : null,\n ruleconfig: rule ? rule.getConfig() : null,\n ruleoutcome: this._getOutcome()\n };\n };\n\n /**\n * Get the selected outcome code.\n *\n * @return {String}\n * @method _getOutcome\n * @protected\n */\n RuleConfig.prototype._getOutcome = function() {\n return this._find('[name=\"outcome\"]').val();\n };\n\n /**\n * Get the selected rule.\n *\n * @return {null|Rule}\n * @method _getRule\n * @protected\n */\n RuleConfig.prototype._getRule = function() {\n var result,\n type = this._find('[name=\"rule\"]').val();\n\n $.each(this._rules, function(index, rule) {\n if (rule.getType() == type) {\n result = rule;\n return;\n }\n });\n\n return result;\n };\n\n /**\n * Return the name of a rule.\n *\n * @param {String} type The type of a rule.\n * @return {String}\n * @method _getRuleName\n * @protected\n */\n RuleConfig.prototype._getRuleName = function(type) {\n var self = this,\n name;\n $.each(self._rulesModules, function(index, modInfo) {\n if (modInfo.type == type) {\n name = modInfo.name;\n return;\n }\n });\n return name;\n };\n\n /**\n * Initialise the outcomes.\n *\n * @return {Promise}\n * @method _initOutcomes\n * @protected\n */\n RuleConfig.prototype._initOutcomes = function() {\n var self = this;\n return Outcomes.getAll().then(function(outcomes) {\n self._outcomesOption = outcomes;\n return;\n });\n };\n\n /**\n * Initialise the rules.\n *\n * @return {Promise}\n * @method _initRules\n * @protected\n */\n RuleConfig.prototype._initRules = function() {\n var self = this,\n promises = [];\n $.each(self._rules, function(index, rule) {\n var promise = rule.init().then(function() {\n rule.setTargetCompetency(self._competency);\n rule.on('change', self._afterRuleConfigChange.bind(self));\n return;\n }, function() {\n // Upon failure remove the rule, and resolve the promise.\n self._rules.splice(index, 1);\n return $.when();\n });\n promises.push(promise);\n });\n\n return $.when.apply($.when, promises);\n };\n\n /**\n * Whether or not the current config is valid.\n *\n * @return {Boolean}\n * @method _isValid\n * @protected\n */\n RuleConfig.prototype._isValid = function() {\n var outcome = this._getOutcome(),\n rule = this._getRule();\n\n if (outcome == Outcomes.NONE) {\n return true;\n } else if (!rule) {\n return false;\n }\n\n return rule.isValid();\n };\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 RuleConfig.prototype.on = function(type, handler) {\n this._eventNode.on(type, handler);\n };\n\n /**\n * Hook to executed before render.\n *\n * @method _preRender\n * @protected\n * @return {Promise}\n */\n RuleConfig.prototype._preRender = function() {\n // We need to have all the information about the rule plugins first.\n return this.ready();\n };\n\n /**\n * Returns a promise that is resolved when the module is ready.\n *\n * @return {Promise}\n * @method ready\n * @protected\n */\n RuleConfig.prototype.ready = function() {\n return this._ready.promise();\n };\n\n /**\n * Render the dialogue.\n *\n * @method _render\n * @protected\n * @return {Promise}\n */\n RuleConfig.prototype._render = function() {\n var self = this;\n return this._preRender().then(function() {\n var config;\n\n if (!self.canBeConfigured()) {\n config = false;\n } else {\n config = {};\n config.outcomes = self._getApplicableOutcomesOptions();\n config.rules = self._getApplicableRulesOptions();\n }\n\n var context = {\n competencyshortname: self._competency.shortname,\n config: config\n };\n\n return Templates.render('tool_lp/competency_rule_config', context);\n });\n };\n\n /**\n * Set the target competency.\n *\n * @param {Number} competencyId The target competency Id.\n * @method setTargetCompetencyId\n */\n RuleConfig.prototype.setTargetCompetencyId = function(competencyId) {\n var self = this;\n self._competency = self._tree.getCompetency(competencyId);\n $.each(self._rules, function(index, rule) {\n rule.setTargetCompetency(self._competency);\n });\n };\n\n /**\n * Set up the instance.\n *\n * @method _setUp\n * @protected\n */\n RuleConfig.prototype._setUp = function() {\n var self = this,\n promises = [],\n modules = [];\n\n self._ready = $.Deferred();\n self._rules = [];\n\n $.each(self._rulesModules, function(index, rule) {\n modules.push(rule.amd);\n });\n\n // Load all the modules.\n require(modules, function() {\n $.each(arguments, function(index, Module) {\n // Instantiate the rule and listen to it.\n var rule = new Module(self._tree);\n self._rules.push(rule);\n });\n\n // Load all the option values.\n promises.push(self._initRules());\n promises.push(self._initOutcomes());\n\n // Ready when everything is done.\n $.when.apply($.when, promises).always(function() {\n self._ready.resolve();\n });\n });\n };\n\n /**\n * Called when the user switches outcome.\n *\n * @method _switchedOutcome\n * @protected\n */\n RuleConfig.prototype._switchedOutcome = function() {\n var self = this,\n type = self._getOutcome();\n\n if (type == Outcomes.NONE) {\n // Reset to defaults.\n self._find('[data-region=\"rule-type\"]').hide()\n .find('[name=\"rule\"]').val(-1);\n self._find('[data-region=\"rule-config\"]').empty().hide();\n self._afterChange();\n return;\n }\n\n self._find('[data-region=\"rule-type\"]').show();\n self._find('[data-region=\"rule-config\"]').show();\n self._afterChange();\n };\n\n /**\n * Called when the user switches rule.\n *\n * @method _switchedRule\n * @protected\n */\n RuleConfig.prototype._switchedRule = function() {\n var self = this,\n container = self._find('[data-region=\"rule-config\"]'),\n rule = self._getRule();\n\n if (!rule) {\n container.empty().hide();\n self._afterChange();\n return;\n }\n rule.injectTemplate(container).then(function() {\n container.show();\n return;\n }).always(function() {\n self._afterChange();\n }).catch(function() {\n container.empty().hide();\n });\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 * @protected\n */\n RuleConfig.prototype._trigger = function(type, data) {\n this._eventNode.trigger(type, [data]);\n };\n\n return /** @alias module:tool_lp/competencyruleconfig */ RuleConfig;\n\n});\n"],"file":"competencyruleconfig.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/competencyruleconfig.js"],"names":["define","$","Notification","Templates","Dialogue","Outcomes","Str","RuleConfig","tree","rulesModules","_eventNode","_tree","_rulesModules","_setUp","prototype","_competency","_outcomesOption","_popup","_ready","_rules","_afterChange","_isValid","_find","prop","_afterRuleConfigChange","e","rule","_getRule","_afterRender","self","on","_switchedOutcome","trigger","_switchedRule","_trigger","_getConfig","close","canBeConfigured","can","each","index","canConfig","display","when","get_string","_render","then","title","render","bind","fail","exception","selector","getContent","find","_getApplicableOutcomesOptions","options","outcome","push","code","name","selected","ruleoutcome","_getApplicableRulesOptions","_getRuleName","getType","type","ruletype","ruleconfig","getConfig","_getOutcome","val","result","modInfo","_initOutcomes","getAll","outcomes","_initRules","promises","promise","init","setTargetCompetency","splice","apply","NONE","isValid","handler","_preRender","ready","config","rules","context","competencyshortname","shortname","setTargetCompetencyId","competencyId","getCompetency","modules","Deferred","amd","require","arguments","Module","always","resolve","hide","empty","show","container","injectTemplate","catch","data"],"mappings":"AAuBAA,OAAM,gCAAC,CAAC,QAAD,CACC,mBADD,CAEC,gBAFD,CAGC,kBAHD,CAIC,6BAJD,CAKC,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I,CAACT,YAAL,GACA,MACH,CACDM,CAAI,CAACmF,cAAL,CAAoBD,CAApB,EAA+B9D,IAA/B,CAAoC,UAAW,CAC3C8D,CAAS,CAACD,IAAV,EAEH,CAHD,EAGGJ,MAHH,CAGU,UAAW,CACjB1E,CAAI,CAACT,YAAL,EACH,CALD,EAKG0F,KALH,CAKS,UAAW,CAChBF,CAAS,CAACF,KAAV,GAAkBD,IAAlB,EACH,CAPD,CAQH,CAlBD,CA4BAlG,CAAU,CAACO,SAAX,CAAqBoB,QAArB,CAAgC,SAASgC,CAAT,CAAe6C,CAAf,CAAqB,CACjD,KAAKrG,UAAL,CAAgBsB,OAAhB,CAAwBkC,CAAxB,CAA8B,CAAC6C,CAAD,CAA9B,CACH,CAFD,CAIA,MAAyDxG,CAAAA,CAE5D,CAxgBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Competency rule config.\n *\n * @module tool_lp/competencyruleconfig\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/notification',\n 'core/templates',\n 'tool_lp/dialogue',\n 'tool_lp/competency_outcomes',\n 'core/str'],\n function($, Notification, Templates, Dialogue, Outcomes, Str) {\n\n /**\n * Competency rule class.\n *\n * When implementing this you should attach a listener to the event 'save'\n * on the instance. E.g.\n *\n * var config = new RuleConfig(tree, modules);\n * config.on('save', function(e, config) { ... });\n *\n * @param {competencytree} tree The competency tree.\n * @param {Array} rulesModules The modules containing the rules: [{ typeName: { amd: amdModule, name: ruleName }}].\n */\n var RuleConfig = function(tree, rulesModules) {\n this._eventNode = $('
');\n this._tree = tree;\n this._rulesModules = rulesModules;\n this._setUp();\n };\n\n /** @property {Object} The current competency. */\n RuleConfig.prototype._competency = null;\n /** @property {Node} The node we attach the events to. */\n RuleConfig.prototype._eventNode = null;\n /** @property {Array} Outcomes options. */\n RuleConfig.prototype._outcomesOption = null;\n /** @property {Dialogue} The dialogue. */\n RuleConfig.prototype._popup = null;\n /** @property {Promise} Resolved when the module is ready. */\n RuleConfig.prototype._ready = null;\n /** @property {Array} The rules. */\n RuleConfig.prototype._rules = null;\n /** @property {Array} The rules modules. */\n RuleConfig.prototype._rulesModules = null;\n /** @property {competencytree} The competency tree. */\n RuleConfig.prototype._tree = null;\n\n /**\n * After change.\n *\n * Triggered when a change occured.\n *\n * @method _afterChange\n * @protected\n */\n RuleConfig.prototype._afterChange = function() {\n if (!this._isValid()) {\n this._find('[data-action=\"save\"]').prop('disabled', true);\n } else {\n this._find('[data-action=\"save\"]').prop('disabled', false);\n }\n };\n\n /**\n * After change in rule's config.\n *\n * Triggered when a change occured in a specific rule config.\n *\n * @method _afterRuleConfigChange\n * @protected\n * @param {Event} e\n * @param {Rule} rule\n */\n RuleConfig.prototype._afterRuleConfigChange = function(e, rule) {\n if (rule != this._getRule()) {\n // This rule is not the current one any more, we can ignore.\n return;\n }\n this._afterChange();\n };\n\n /**\n * After render hook.\n *\n * @method _afterRender\n * @protected\n */\n RuleConfig.prototype._afterRender = function() {\n var self = this;\n\n self._find('[name=\"outcome\"]').on('change', function() {\n self._switchedOutcome();\n }).trigger('change');\n\n self._find('[name=\"rule\"]').on('change', function() {\n self._switchedRule();\n }).trigger('change');\n\n self._find('[data-action=\"save\"]').on('click', function() {\n self._trigger('save', self._getConfig());\n self.close();\n });\n\n self._find('[data-action=\"cancel\"]').on('click', function() {\n self.close();\n });\n };\n\n /**\n * Whether the current competency can be configured.\n *\n * @return {Boolean}\n * @method canBeConfigured\n */\n RuleConfig.prototype.canBeConfigured = function() {\n var can = false;\n $.each(this._rules, function(index, rule) {\n if (rule.canConfig()) {\n can = true;\n return;\n }\n });\n return can;\n };\n\n /**\n * Close the dialogue.\n *\n * @method close\n */\n RuleConfig.prototype.close = function() {\n this._popup.close();\n this._popup = null;\n };\n\n /**\n * Opens the picker.\n *\n * @method display\n * @returns {Promise}\n */\n RuleConfig.prototype.display = function() {\n var self = this;\n if (!self._competency) {\n return false;\n }\n return $.when(Str.get_string('competencyrule', 'tool_lp'), self._render())\n .then(function(title, render) {\n self._popup = new Dialogue(\n title,\n render[0],\n self._afterRender.bind(self)\n );\n return;\n }).fail(Notification.exception);\n };\n\n /**\n * Find a node in the dialogue.\n *\n * @param {String} selector\n * @return {JQuery}\n * @method _find\n * @protected\n */\n RuleConfig.prototype._find = function(selector) {\n return $(this._popup.getContent()).find(selector);\n };\n\n /**\n * Get the applicable outcome options.\n *\n * @return {Array}\n * @method _getApplicableOutcomesOptions\n * @protected\n */\n RuleConfig.prototype._getApplicableOutcomesOptions = function() {\n var self = this,\n options = [];\n\n $.each(self._outcomesOption, function(index, outcome) {\n options.push({\n code: outcome.code,\n name: outcome.name,\n selected: (outcome.code == self._competency.ruleoutcome) ? true : false,\n });\n });\n\n return options;\n };\n\n /**\n * Get the applicable rules options.\n *\n * @return {Array}\n * @method _getApplicableRulesOptions\n * @protected\n */\n RuleConfig.prototype._getApplicableRulesOptions = function() {\n var self = this,\n options = [];\n\n $.each(self._rules, function(index, rule) {\n if (!rule.canConfig()) {\n return;\n }\n options.push({\n name: self._getRuleName(rule.getType()),\n type: rule.getType(),\n selected: (rule.getType() == self._competency.ruletype) ? true : false,\n });\n });\n\n return options;\n };\n\n /**\n * Get the full config for the competency.\n *\n * @return {Object} Contains rule, ruleoutcome and ruleconfig.\n * @method _getConfig\n * @protected\n */\n RuleConfig.prototype._getConfig = function() {\n var rule = this._getRule();\n return {\n ruletype: rule ? rule.getType() : null,\n ruleconfig: rule ? rule.getConfig() : null,\n ruleoutcome: this._getOutcome()\n };\n };\n\n /**\n * Get the selected outcome code.\n *\n * @return {String}\n * @method _getOutcome\n * @protected\n */\n RuleConfig.prototype._getOutcome = function() {\n return this._find('[name=\"outcome\"]').val();\n };\n\n /**\n * Get the selected rule.\n *\n * @return {null|Rule}\n * @method _getRule\n * @protected\n */\n RuleConfig.prototype._getRule = function() {\n var result,\n type = this._find('[name=\"rule\"]').val();\n\n $.each(this._rules, function(index, rule) {\n if (rule.getType() == type) {\n result = rule;\n return;\n }\n });\n\n return result;\n };\n\n /**\n * Return the name of a rule.\n *\n * @param {String} type The type of a rule.\n * @return {String}\n * @method _getRuleName\n * @protected\n */\n RuleConfig.prototype._getRuleName = function(type) {\n var self = this,\n name;\n $.each(self._rulesModules, function(index, modInfo) {\n if (modInfo.type == type) {\n name = modInfo.name;\n return;\n }\n });\n return name;\n };\n\n /**\n * Initialise the outcomes.\n *\n * @return {Promise}\n * @method _initOutcomes\n * @protected\n */\n RuleConfig.prototype._initOutcomes = function() {\n var self = this;\n return Outcomes.getAll().then(function(outcomes) {\n self._outcomesOption = outcomes;\n return;\n });\n };\n\n /**\n * Initialise the rules.\n *\n * @return {Promise}\n * @method _initRules\n * @protected\n */\n RuleConfig.prototype._initRules = function() {\n var self = this,\n promises = [];\n $.each(self._rules, function(index, rule) {\n var promise = rule.init().then(function() {\n rule.setTargetCompetency(self._competency);\n rule.on('change', self._afterRuleConfigChange.bind(self));\n return;\n }, function() {\n // Upon failure remove the rule, and resolve the promise.\n self._rules.splice(index, 1);\n return $.when();\n });\n promises.push(promise);\n });\n\n return $.when.apply($.when, promises);\n };\n\n /**\n * Whether or not the current config is valid.\n *\n * @return {Boolean}\n * @method _isValid\n * @protected\n */\n RuleConfig.prototype._isValid = function() {\n var outcome = this._getOutcome(),\n rule = this._getRule();\n\n if (outcome == Outcomes.NONE) {\n return true;\n } else if (!rule) {\n return false;\n }\n\n return rule.isValid();\n };\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 RuleConfig.prototype.on = function(type, handler) {\n this._eventNode.on(type, handler);\n };\n\n /**\n * Hook to executed before render.\n *\n * @method _preRender\n * @protected\n * @return {Promise}\n */\n RuleConfig.prototype._preRender = function() {\n // We need to have all the information about the rule plugins first.\n return this.ready();\n };\n\n /**\n * Returns a promise that is resolved when the module is ready.\n *\n * @return {Promise}\n * @method ready\n * @protected\n */\n RuleConfig.prototype.ready = function() {\n return this._ready.promise();\n };\n\n /**\n * Render the dialogue.\n *\n * @method _render\n * @protected\n * @return {Promise}\n */\n RuleConfig.prototype._render = function() {\n var self = this;\n return this._preRender().then(function() {\n var config;\n\n if (!self.canBeConfigured()) {\n config = false;\n } else {\n config = {};\n config.outcomes = self._getApplicableOutcomesOptions();\n config.rules = self._getApplicableRulesOptions();\n }\n\n var context = {\n competencyshortname: self._competency.shortname,\n config: config\n };\n\n return Templates.render('tool_lp/competency_rule_config', context);\n });\n };\n\n /**\n * Set the target competency.\n *\n * @param {Number} competencyId The target competency Id.\n * @method setTargetCompetencyId\n */\n RuleConfig.prototype.setTargetCompetencyId = function(competencyId) {\n var self = this;\n self._competency = self._tree.getCompetency(competencyId);\n $.each(self._rules, function(index, rule) {\n rule.setTargetCompetency(self._competency);\n });\n };\n\n /**\n * Set up the instance.\n *\n * @method _setUp\n * @protected\n */\n RuleConfig.prototype._setUp = function() {\n var self = this,\n promises = [],\n modules = [];\n\n self._ready = $.Deferred();\n self._rules = [];\n\n $.each(self._rulesModules, function(index, rule) {\n modules.push(rule.amd);\n });\n\n // Load all the modules.\n require(modules, function() {\n $.each(arguments, function(index, Module) {\n // Instantiate the rule and listen to it.\n var rule = new Module(self._tree);\n self._rules.push(rule);\n });\n\n // Load all the option values.\n promises.push(self._initRules());\n promises.push(self._initOutcomes());\n\n // Ready when everything is done.\n $.when.apply($.when, promises).always(function() {\n self._ready.resolve();\n });\n });\n };\n\n /**\n * Called when the user switches outcome.\n *\n * @method _switchedOutcome\n * @protected\n */\n RuleConfig.prototype._switchedOutcome = function() {\n var self = this,\n type = self._getOutcome();\n\n if (type == Outcomes.NONE) {\n // Reset to defaults.\n self._find('[data-region=\"rule-type\"]').hide()\n .find('[name=\"rule\"]').val(-1);\n self._find('[data-region=\"rule-config\"]').empty().hide();\n self._afterChange();\n return;\n }\n\n self._find('[data-region=\"rule-type\"]').show();\n self._find('[data-region=\"rule-config\"]').show();\n self._afterChange();\n };\n\n /**\n * Called when the user switches rule.\n *\n * @method _switchedRule\n * @protected\n */\n RuleConfig.prototype._switchedRule = function() {\n var self = this,\n container = self._find('[data-region=\"rule-config\"]'),\n rule = self._getRule();\n\n if (!rule) {\n container.empty().hide();\n self._afterChange();\n return;\n }\n rule.injectTemplate(container).then(function() {\n container.show();\n return;\n }).always(function() {\n self._afterChange();\n }).catch(function() {\n container.empty().hide();\n });\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 * @protected\n */\n RuleConfig.prototype._trigger = function(type, data) {\n this._eventNode.trigger(type, [data]);\n };\n\n return /** @alias module:tool_lp/competencyruleconfig */ RuleConfig;\n\n});\n"],"file":"competencyruleconfig.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/course_competency_settings.min.js.map b/admin/tool/lp/amd/build/course_competency_settings.min.js.map index c28f3761c0d03..2011dcea9e3fc 100644 --- a/admin/tool/lp/amd/build/course_competency_settings.min.js.map +++ b/admin/tool/lp/amd/build/course_competency_settings.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/course_competency_settings.js"],"names":["define","$","notification","Dialogue","str","ajax","templates","Pending","settingsMod","selector","on","configureSettings","bind","prototype","_dialogue","e","pendingPromise","courseid","target","closest","data","currentValue","preventDefault","when","get_string","render","settings","pushratingstouserplans","then","title","templateResult","addListeners","resolve","catch","exception","save","_find","saveSettings","cancel","cancelChanges","close","find","newValue","val","courseId","call","methodname","args","refreshCourseCompetenciesPage","modu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AAAA,CACzE,CA9IK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Change the course competency settings in a popup.\n *\n * @module tool_lp/configurecoursecompetencysettings\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery',\n 'core/notification',\n 'tool_lp/dialogue',\n 'core/str',\n 'core/ajax',\n 'core/templates',\n 'core/pending'\n ],\n function($, notification, Dialogue, str, ajax, templates, Pending) {\n\n /**\n * Constructor\n *\n * @param {String} selector - selector for the links to open the dialogue.\n */\n var settingsMod = function(selector) {\n $(selector).on('click', this.configureSettings.bind(this));\n };\n\n /** @property {Dialogue} Reference to the dialogue that we opened. */\n settingsMod.prototype._dialogue = null;\n\n /**\n * Open the configure settings dialogue.\n *\n * @param {Event} e\n * @method configureSettings\n */\n settingsMod.prototype.configureSettings = function(e) {\n var pendingPromise = new Pending();\n var courseid = $(e.target).closest('a').data('courseid');\n var currentValue = $(e.target).closest('a').data('pushratingstouserplans');\n var context = {\n courseid: courseid,\n settings: {pushratingstouserplans: currentValue}\n };\n e.preventDefault();\n\n $.when(\n str.get_string('configurecoursecompetencysettings', 'tool_lp'),\n templates.render('tool_lp/course_competency_settings', context),\n )\n .then(function(title, templateResult) {\n this._dialogue = new Dialogue(\n title,\n templateResult[0],\n this.addListeners.bind(this)\n );\n\n return this._dialogue;\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n };\n\n /**\n * Add the save listener to the form.\n *\n * @method addSaveListener\n */\n settingsMod.prototype.addListeners = function() {\n var save = this._find('[data-action=\"save\"]');\n save.on('click', this.saveSettings.bind(this));\n var cancel = this._find('[data-action=\"cancel\"]');\n cancel.on('click', this.cancelChanges.bind(this));\n };\n\n /**\n * Cancel the changes.\n *\n * @param {Event} e\n * @method cancelChanges\n */\n settingsMod.prototype.cancelChanges = function(e) {\n e.preventDefault();\n this._dialogue.close();\n };\n\n /**\n * Cancel the changes.\n *\n * @param {String} selector\n * @return {JQuery}\n */\n settingsMod.prototype._find = function(selector) {\n return $('[data-region=\"coursecompetencysettings\"]').find(selector);\n };\n\n /**\n * Save the settings.\n *\n * @param {Event} e\n * @method saveSettings\n */\n settingsMod.prototype.saveSettings = function(e) {\n var pendingPromise = new Pending();\n e.preventDefault();\n\n var newValue = this._find('input[name=\"pushratingstouserplans\"]:checked').val();\n var courseId = this._find('input[name=\"courseid\"]').val();\n var settings = {pushratingstouserplans: newValue};\n\n ajax.call([\n {methodname: 'core_competency_update_course_competency_settings',\n args: {courseid: courseId, settings: settings}}\n ])[0]\n .then(function() {\n return this.refreshCourseCompetenciesPage();\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n\n };\n\n /**\n * Refresh the course competencies page.\n *\n * @param {Event} e\n * @method saveSettings\n */\n settingsMod.prototype.refreshCourseCompetenciesPage = function() {\n var courseId = this._find('input[name=\"courseid\"]').val();\n var pendingPromise = new Pending();\n\n ajax.call([\n {methodname: 'tool_lp_data_for_course_competencies_page',\n args: {courseid: courseId, moduleid: 0}}\n ])[0]\n .then(function(context) {\n return templates.render('tool_lp/course_competencies_page', context);\n })\n .then(function(html, js) {\n templates.replaceNode($('[data-region=\"coursecompetenciespage\"]'), html, js);\n this._dialogue.close();\n\n return;\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n };\n\n return /** @alias module:tool_lp/configurecoursecompetencysettings */ settingsMod;\n});\n"],"file":"course_competency_settings.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/course_competency_settings.js"],"names":["define","$","notification","Dialogue","str","ajax","templates","Pending","settingsMod","selector","on","configureSettings","bind","prototype","_dialogue","e","pendingPromise","courseid","target","closest","data","currentValue","preventDefault","when","get_string","render","settings","pushratingstouserplans","then","title","templateResult","addListeners","resolve","catch","exception","save","_find","saveSettings","cancel","cancelChanges","close","find","newValue","val","courseId","call","methodname","args","refreshCourseCompetenciesPage","moduleid","context","html","js","replaceNode"],"mappings":"AAsBAA,OAAM,sCAAC,CAAC,QAAD,CACC,mBADD,CAEC,kBAFD,CAGC,UAHD,CAIC,WAJD,CAKC,gBALD,CAMC,cAND,CAAD,CAQC,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAoCC,CAApC,CAAyCC,CAAzC,CAA+CC,CAA/C,CAA0DC,CAA1D,CAAmE,CAOtE,GAAIC,CAAAA,CAAW,CAAG,SAASC,CAAT,CAAmB,CACjCR,CAAC,CAACQ,CAAD,CAAD,CAAYC,EAAZ,CAAe,OAAf,CAAwB,KAAKC,iBAAL,CAAuBC,IAAvB,CAA4B,IAA5B,CAAxB,CACH,CAFD,CAKAJ,CAAW,CAACK,SAAZ,CAAsBC,SAAtB,CAAkC,IAAlC,CAQAN,CAAW,CAACK,SAAZ,CAAsBF,iBAAtB,CAA0C,SAASI,CAAT,CAAY,IAC9CC,CAAAA,CAAc,CAAG,GAAIT,CAAAA,CADyB,CAE9CU,CAAQ,CAAGhB,CAAC,CAACc,CAAC,CAACG,MAAH,CAAD,CAAYC,OAAZ,CAAoB,GAApB,EAAyBC,IAAzB,CAA8B,UAA9B,CAFmC,CAG9CC,CAAY,CAAGpB,CAAC,CAACc,CAAC,CAACG,MAAH,CAAD,CAAYC,OAAZ,CAAoB,GAApB,EAAyBC,IAAzB,CAA8B,wBAA9B,CAH+B,CAQlDL,CAAC,CAACO,cAAF,GAEArB,CAAC,CAACsB,IAAF,CACInB,CAAG,CAACoB,UAAJ,CAAe,mCAAf,CAAoD,SAApD,CADJ,CAEIlB,CAAS,CAACmB,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CAAD,CAAvB,CAAmEkD,CAAnE,CAAyEC,CAAzE,EACA,KAAKtC,SAAL,CAAe0B,KAAf,EAGH,CALK,CAKJ5B,IALI,CAKC,IALD,CAPN,EAaCgB,IAbD,CAaMZ,CAAc,CAACgB,OAbrB,EAcCC,KAdD,CAcO/B,CAAY,CAACgC,SAdpB,CAeH,CAnBD,CAqBA,MAAsE1B,CAAAA,CACzE,CA7IK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Change the course competency settings in a popup.\n *\n * @module tool_lp/configurecoursecompetencysettings\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery',\n 'core/notification',\n 'tool_lp/dialogue',\n 'core/str',\n 'core/ajax',\n 'core/templates',\n 'core/pending'\n ],\n function($, notification, Dialogue, str, ajax, templates, Pending) {\n\n /**\n * Constructor\n *\n * @param {String} selector - selector for the links to open the dialogue.\n */\n var settingsMod = function(selector) {\n $(selector).on('click', this.configureSettings.bind(this));\n };\n\n /** @property {Dialogue} Reference to the dialogue that we opened. */\n settingsMod.prototype._dialogue = null;\n\n /**\n * Open the configure settings dialogue.\n *\n * @param {Event} e\n * @method configureSettings\n */\n settingsMod.prototype.configureSettings = function(e) {\n var pendingPromise = new Pending();\n var courseid = $(e.target).closest('a').data('courseid');\n var currentValue = $(e.target).closest('a').data('pushratingstouserplans');\n var context = {\n courseid: courseid,\n settings: {pushratingstouserplans: currentValue}\n };\n e.preventDefault();\n\n $.when(\n str.get_string('configurecoursecompetencysettings', 'tool_lp'),\n templates.render('tool_lp/course_competency_settings', context),\n )\n .then(function(title, templateResult) {\n this._dialogue = new Dialogue(\n title,\n templateResult[0],\n this.addListeners.bind(this)\n );\n\n return this._dialogue;\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n };\n\n /**\n * Add the save listener to the form.\n *\n * @method addSaveListener\n */\n settingsMod.prototype.addListeners = function() {\n var save = this._find('[data-action=\"save\"]');\n save.on('click', this.saveSettings.bind(this));\n var cancel = this._find('[data-action=\"cancel\"]');\n cancel.on('click', this.cancelChanges.bind(this));\n };\n\n /**\n * Cancel the changes.\n *\n * @param {Event} e\n * @method cancelChanges\n */\n settingsMod.prototype.cancelChanges = function(e) {\n e.preventDefault();\n this._dialogue.close();\n };\n\n /**\n * Cancel the changes.\n *\n * @param {String} selector\n * @return {JQuery}\n */\n settingsMod.prototype._find = function(selector) {\n return $('[data-region=\"coursecompetencysettings\"]').find(selector);\n };\n\n /**\n * Save the settings.\n *\n * @param {Event} e\n * @method saveSettings\n */\n settingsMod.prototype.saveSettings = function(e) {\n var pendingPromise = new Pending();\n e.preventDefault();\n\n var newValue = this._find('input[name=\"pushratingstouserplans\"]:checked').val();\n var courseId = this._find('input[name=\"courseid\"]').val();\n var settings = {pushratingstouserplans: newValue};\n\n ajax.call([\n {methodname: 'core_competency_update_course_competency_settings',\n args: {courseid: courseId, settings: settings}}\n ])[0]\n .then(function() {\n return this.refreshCourseCompetenciesPage();\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n\n };\n\n /**\n * Refresh the course competencies page.\n *\n * @method saveSettings\n */\n settingsMod.prototype.refreshCourseCompetenciesPage = function() {\n var courseId = this._find('input[name=\"courseid\"]').val();\n var pendingPromise = new Pending();\n\n ajax.call([\n {methodname: 'tool_lp_data_for_course_competencies_page',\n args: {courseid: courseId, moduleid: 0}}\n ])[0]\n .then(function(context) {\n return templates.render('tool_lp/course_competencies_page', context);\n })\n .then(function(html, js) {\n templates.replaceNode($('[data-region=\"coursecompetenciespage\"]'), html, js);\n this._dialogue.close();\n\n return;\n }.bind(this))\n .then(pendingPromise.resolve)\n .catch(notification.exception);\n };\n\n return /** @alias module:tool_lp/configurecoursecompetencysettings */ settingsMod;\n});\n"],"file":"course_competency_settings.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/dragdrop-reorder.min.js.map b/admin/tool/lp/amd/build/dragdrop-reorder.min.js.map index ebcf3d87791b5..fb8b59038a342 100644 --- a/admin/tool/lp/amd/build/dragdrop-reorder.min.js.map +++ b/admin/tool/lp/amd/build/dragdrop-reorder.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/dragdrop-reorder.js"],"names":["define","str","Y","dragDropInstance","proxyCallback","e","dragNode","drag","get","dropNode","drop","callback","getDOMNode","dragdrop","group","dragHandleText","sameNodeText","parentNodeText","sameNodeClass","parentNodeClass","dragHandleInsertClass","get_strings","key","component","done","use","destroy","M","tool_lp","dragdrop_reorder","bind"],"mappings":"AAsBAA,OAAM,4BAAC,CAAC,UAAD,CAAa,UAAb,CAAD,CAA2B,SAASC,CAAT,CAAcC,CAAd,CAAiB,IAQ1CC,CAAAA,CAAgB,CAAG,IARuB,CAe1CC,CAAa,CAAG,SAASC,CAAT,CAAY,IACxBC,CAAAA,CAAQ,CAAGD,CAAC,CAACE,IAAF,CAAOC,GAAP,CAAW,MAAX,CADa,CAExBC,CAAQ,CAAGJ,CAAC,CAACK,IAAF,CAAOF,GAAP,CAAW,MAAX,CAFa,CAG5B,KAAKG,QAAL,CAAcL,CAAQ,CAACM,UAAT,EAAd,CAAqCH,CAAQ,CAACG,UAAT,EAArC,CACH,CAnB6C,CAqB9C,MAAqD,CAcjDC,QAAQ,CAAE,kBAASC,CAAT,CACSC,CADT,CAESC,CAFT,CAGSC,CAHT,CAISC,CAJT,CAKSC,CALT,CAMSC,CANT,CAOST,CAPT,CAOmB,CAGzBV,CAAG,CAACoB,WAAJ,CAAgB,CACZ,CAACC,GAAG,CAAE,qBAAN,CAA6BC,SAAS,CAAE,QAAxC,CADY,CAEZ,CAACD,GAAG,CAAE,aAAN,CAAqBC,SAAS,CAAE,QAAhC,CAFY,CAGZ,CAACD,GAAG,CAAE,WAAN,CAAmBC,SAAS,CAAE,QAA9B,CAHY,CAAhB,EAIGC,IAJH,CAIQ,UAAW,CACftB,CAAC,CAACuB,GAAF,CAAM,iCAAN,CAAyC,UAAW,CAKhD,GAAItB,CAAJ,CAAsB,CAClBA,CAAgB,CAACuB,OAAjB,EACH,CACDvB,CAAgB,CAAGwB,CAAC,CAACC,OAAF,CAAUC,gBAAV,CAA2B,CAC1Cf,KAAK,CAAEA,CADmC,CAE1CC,cAAc,CAAEA,CAF0B,CAG1CC,YAAY,CAAEA,CAH4B,CAI1CC,cAAc,CAAEA,CAJ0B,CAK1CC,aAAa,CAAEA,CAL2B,CAM1CC,eAAe,CAAEA,CANyB,CAO1CC,qBAAqB,CAAEA,CAPmB,CAQ1CT,QAAQ,CAAET,CAAC,CAAC4B,IAAF,CAAO1B,CAAP,CAdA,CACVO,QAAQ,CAAEA,CADA,CAcA,CARgC,CAA3B,CAUtB,CAlBD,CAmBH,CAxBD,CAyBH,CAjDgD,CAoDxD,CAzEK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Drag and drop reorder via HTML5.\n *\n * @module tool_lp/dragdrop-reorder\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['core/str', 'core/yui'], function(str, Y) {\n // Private variables and functions.\n\n /**\n * Store the current instance of the core drag drop.\n *\n * @property dragDropInstance M.tool_lp.dragdrop_reorder\n */\n var dragDropInstance = null;\n\n /**\n * Translate the drophit event from YUI\n * into simple drag and drop nodes.\n * @param {Y.Event} e The yui drop event.\n */\n var proxyCallback = function(e) {\n var dragNode = e.drag.get('node');\n var dropNode = e.drop.get('node');\n this.callback(dragNode.getDOMNode(), dropNode.getDOMNode());\n };\n\n return /** @alias module:tool_lp/dragdrop-reorder */ {\n // Public variables and functions.\n /**\n * Create an instance of M.tool_lp.dragdrop\n *\n * @param {String} group Unique string to identify this interaction.\n * @param {String} dragHandleText Alt text for the drag handle.\n * @param {String} sameNodeText Used in keyboard drag drop for the list of items target.\n * @param {String} parentNodeText Used in keyboard drag drop for the parent target.\n * @param {String} sameNodeClass class used to find the each of the list of items.\n * @param {String} parentNodeClass class used to find the container for the list of items.\n * @param {String} dragHandleInsertClass class used to find the location to insert the drag handles.\n * @param {function} callback Drop hit handler.\n */\n dragdrop: function(group,\n dragHandleText,\n sameNodeText,\n parentNodeText,\n sameNodeClass,\n parentNodeClass,\n dragHandleInsertClass,\n callback) {\n // Here we are wrapping YUI. This allows us to start transitioning, but\n // wait for a good alternative without having inconsistent UIs.\n str.get_strings([\n {key: 'emptydragdropregion', component: 'moodle'},\n {key: 'movecontent', component: 'moodle'},\n {key: 'tocontent', component: 'moodle'},\n ]).done(function() {\n Y.use('moodle-tool_lp-dragdrop-reorder', function() {\n\n var context = {\n callback: callback\n };\n if (dragDropInstance) {\n dragDropInstance.destroy();\n }\n dragDropInstance = M.tool_lp.dragdrop_reorder({\n group: group,\n dragHandleText: dragHandleText,\n sameNodeText: sameNodeText,\n parentNodeText: parentNodeText,\n sameNodeClass: sameNodeClass,\n parentNodeClass: parentNodeClass,\n dragHandleInsertClass: dragHandleInsertClass,\n callback: Y.bind(proxyCallback, context)\n });\n });\n });\n }\n\n };\n});\n"],"file":"dragdrop-reorder.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/dragdrop-reorder.js"],"names":["define","str","Y","dragDropInstance","proxyCallback","e","dragNode","drag","get","dropNode","drop","callback","getDOMNode","dragdrop","group","dragHandleText","sameNodeText","parentNodeText","sameNodeClass","parentNodeClass","dragHandleInsertClass","get_strings","key","component","done","use","destroy","M","tool_lp","dragdrop_reorder","bind"],"mappings":"AAsBAA,OAAM,4BAAC,CAAC,UAAD,CAAa,UAAb,CAAD,CAA2B,SAASC,CAAT,CAAcC,CAAd,CAAiB,IAQ1CC,CAAAA,CAAgB,CAAG,IARuB,CAe1CC,CAAa,CAAG,SAASC,CAAT,CAAY,IACxBC,CAAAA,CAAQ,CAAGD,CAAC,CAACE,IAAF,CAAOC,GAAP,CAAW,MAAX,CADa,CAExBC,CAAQ,CAAGJ,CAAC,CAACK,IAAF,CAAOF,GAAP,CAAW,MAAX,CAFa,CAG5B,KAAKG,QAAL,CAAcL,CAAQ,CAACM,UAAT,EAAd,CAAqCH,CAAQ,CAACG,UAAT,EAArC,CACH,CAnB6C,CAqB9C,MAAqD,CAcjDC,QAAQ,CAAE,kBAASC,CAAT,CACSC,CADT,CAESC,CAFT,CAGSC,CAHT,CAISC,CAJT,CAKSC,CALT,CAMSC,CANT,CAOST,CAPT,CAOmB,CAGzBV,CAAG,CAACoB,WAAJ,CAAgB,CACZ,CAACC,GAAG,CAAE,qBAAN,CAA6BC,SAAS,CAAE,QAAxC,CADY,CAEZ,CAACD,GAAG,CAAE,aAAN,CAAqBC,SAAS,CAAE,QAAhC,CAFY,CAGZ,CAACD,GAAG,CAAE,WAAN,CAAmBC,SAAS,CAAE,QAA9B,CAHY,CAAhB,EAIGC,IAJH,CAIQ,UAAW,CACftB,CAAC,CAACuB,GAAF,CAAM,iCAAN,CAAyC,UAAW,CAKhD,GAAItB,CAAJ,CAAsB,CAClBA,CAAgB,CAACuB,OAAjB,EACH,CACDvB,CAAgB,CAAGwB,CAAC,CAACC,OAAF,CAAUC,gBAAV,CAA2B,CAC1Cf,KAAK,CAAEA,CADmC,CAE1CC,cAAc,CAAEA,CAF0B,CAG1CC,YAAY,CAAEA,CAH4B,CAI1CC,cAAc,CAAEA,CAJ0B,CAK1CC,aAAa,CAAEA,CAL2B,CAM1CC,eAAe,CAAEA,CANyB,CAO1CC,qBAAqB,CAAEA,CAPmB,CAQ1CT,QAAQ,CAAET,CAAC,CAAC4B,IAAF,CAAO1B,CAAP,CAdA,CACVO,QAAQ,CAAEA,CADA,CAcA,CARgC,CAA3B,CAUtB,CAlBD,CAmBH,CAxBD,CAyBH,CAjDgD,CAoDxD,CAzEK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Drag and drop reorder via HTML5.\n *\n * @module tool_lp/dragdrop-reorder\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['core/str', 'core/yui'], function(str, Y) {\n // Private variables and functions.\n\n /**\n * Store the current instance of the core drag drop.\n *\n * @property {object} dragDropInstance M.tool_lp.dragdrop_reorder\n */\n var dragDropInstance = null;\n\n /**\n * Translate the drophit event from YUI\n * into simple drag and drop nodes.\n * @param {Y.Event} e The yui drop event.\n */\n var proxyCallback = function(e) {\n var dragNode = e.drag.get('node');\n var dropNode = e.drop.get('node');\n this.callback(dragNode.getDOMNode(), dropNode.getDOMNode());\n };\n\n return /** @alias module:tool_lp/dragdrop-reorder */ {\n // Public variables and functions.\n /**\n * Create an instance of M.tool_lp.dragdrop\n *\n * @param {String} group Unique string to identify this interaction.\n * @param {String} dragHandleText Alt text for the drag handle.\n * @param {String} sameNodeText Used in keyboard drag drop for the list of items target.\n * @param {String} parentNodeText Used in keyboard drag drop for the parent target.\n * @param {String} sameNodeClass class used to find the each of the list of items.\n * @param {String} parentNodeClass class used to find the container for the list of items.\n * @param {String} dragHandleInsertClass class used to find the location to insert the drag handles.\n * @param {function} callback Drop hit handler.\n */\n dragdrop: function(group,\n dragHandleText,\n sameNodeText,\n parentNodeText,\n sameNodeClass,\n parentNodeClass,\n dragHandleInsertClass,\n callback) {\n // Here we are wrapping YUI. This allows us to start transitioning, but\n // wait for a good alternative without having inconsistent UIs.\n str.get_strings([\n {key: 'emptydragdropregion', component: 'moodle'},\n {key: 'movecontent', component: 'moodle'},\n {key: 'tocontent', component: 'moodle'},\n ]).done(function() {\n Y.use('moodle-tool_lp-dragdrop-reorder', function() {\n\n var context = {\n callback: callback\n };\n if (dragDropInstance) {\n dragDropInstance.destroy();\n }\n dragDropInstance = M.tool_lp.dragdrop_reorder({\n group: group,\n dragHandleText: dragHandleText,\n sameNodeText: sameNodeText,\n parentNodeText: parentNodeText,\n sameNodeClass: sameNodeClass,\n parentNodeClass: parentNodeClass,\n dragHandleInsertClass: dragHandleInsertClass,\n callback: Y.bind(proxyCallback, context)\n });\n });\n });\n }\n\n };\n});\n"],"file":"dragdrop-reorder.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/grade_dialogue.min.js.map b/admin/tool/lp/amd/build/grade_dialogue.min.js.map index e8fb63a2ee1be..333e741fe4ef7 100644 --- a/admin/tool/lp/amd/build/grade_dialogue.min.js.map +++ b/admin/tool/lp/amd/build/grade_dialogue.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/grade_dialogue.js"],"names":["define","$","Notification","Templates","Dialogue","EventBase","Str","Grade","ratingOptions","prototype","constructor","apply","_ratingOptions","Object","create","_popup","_afterRender","btnRate","_find","lstRating","txtComment","click","e","preventDefault","_trigger","close","bind","change","node","val","prop","display","M","util","js_pending","when","get_string","_render","then","title","templateResult","js_complete","catch","ex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B,SAAS0B,CAAT,CAAmB,CACvC,MAAO3C,CAAAA,CAAC,CAAC,KAAKc,MAAL,CAAY8B,UAAZ,EAAD,CAAD,CAA4BC,IAA5B,CAAiCF,CAAjC,CACV,CAFD,CAWArC,CAAK,CAACE,SAAN,CAAgB4B,OAAhB,CAA0B,UAAW,CACjC,GAAIU,CAAAA,CAAO,CAAG,CACVC,QAAQ,CAAE,KAAKC,SADL,CAEVC,OAAO,CAAE,KAAKtC,cAFJ,CAAd,CAIA,MAAOT,CAAAA,CAAS,CAACgD,MAAV,CAAiB,2BAAjB,CAA8CJ,CAA9C,CACV,CAND,CAQA,MAAOxC,CAAAA,CACV,CAnIK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Grade dialogue.\n *\n * @module tool_lp/grade_dialogue\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/templates',\n 'tool_lp/dialogue',\n 'tool_lp/event_base',\n 'core/str'],\n function($, Notification, Templates, Dialogue, EventBase, Str) {\n\n /**\n * Grade dialogue class.\n *\n * @class tool_lp/grade_dialogue\n * @param {Array} ratingOptions\n */\n var Grade = function(ratingOptions) {\n EventBase.prototype.constructor.apply(this, []);\n this._ratingOptions = ratingOptions;\n };\n Grade.prototype = Object.create(EventBase.prototype);\n\n /** @property {Dialogue} The dialogue. */\n Grade.prototype._popup = null;\n /** @property {Array} Array of objects containing, 'value', 'name' and optionally 'selected'. */\n Grade.prototype._ratingOptions = null;\n\n /**\n * After render hook.\n *\n * @method _afterRender\n * @protected\n */\n Grade.prototype._afterRender = function() {\n var btnRate = this._find('[data-action=\"rate\"]'),\n lstRating = this._find('[name=\"rating\"]'),\n txtComment = this._find('[name=\"comment\"]');\n\n this._find('[data-action=\"cancel\"]').click(function(e) {\n e.preventDefault();\n this._trigger('cancelled');\n this.close();\n }.bind(this));\n\n lstRating.change(function() {\n var node = $(this);\n if (!node.val()) {\n btnRate.prop('disabled', true);\n } else {\n btnRate.prop('disabled', false);\n }\n }).change();\n\n btnRate.click(function(e) {\n e.preventDefault();\n var val = lstRating.val();\n if (!val) {\n return;\n }\n this._trigger('rated', {\n 'rating': val,\n 'note': txtComment.val()\n });\n this.close();\n }.bind(this));\n };\n\n /**\n * Close the dialogue.\n *\n * @method close\n */\n Grade.prototype.close = function() {\n this._popup.close();\n this._popup = null;\n };\n\n /**\n * Opens the picker.\n *\n * @param {Number} competencyId The competency ID of the competency to work on.\n * @method display\n * @return {Promise}\n */\n Grade.prototype.display = function() {\n M.util.js_pending('tool_lp/grade_dialogue:display');\n return $.when(\n Str.get_string('rate', 'tool_lp'),\n this._render()\n )\n .then(function(title, templateResult) {\n this._popup = new Dialogue(\n title,\n templateResult[0],\n function() {\n this._afterRender();\n M.util.js_complete('tool_lp/grade_dialogue:display');\n }.bind(this)\n );\n\n return this._popup;\n }.bind(this))\n .catch(Notification.exception);\n };\n\n /**\n * Find a node in the dialogue.\n *\n * @param {String} selector\n * @method _find\n * @returns {node} The node\n * @protected\n */\n Grade.prototype._find = function(selector) {\n return $(this._popup.getContent()).find(selector);\n };\n\n /**\n * Render the dialogue.\n *\n * @method _render\n * @protected\n * @return {Promise}\n */\n Grade.prototype._render = function() {\n var context = {\n cangrade: this._canGrade,\n ratings: this._ratingOptions\n };\n return Templates.render('tool_lp/competency_grader', context);\n };\n\n return Grade;\n});\n"],"file":"grade_dialogue.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/grade_dialogue.js"],"names":["define","$","Notification","Templates","Dialogue","EventBase","Str","Grade","ratingOptions","prototype","constructor","apply","_ratingOptions","Object","create","_popup","_afterRender","btnRate","_find","lstRating","txtComment","click","e","preventDefault","_trigger","close","bind","change","node","val","prop","display","M","util","js_pending","when","get_string","_render","then","title","templateResult","js_complete","catch","exception","selector","getContent","find","context","cangrade","_canGrade","ratings","render"],"mappings":"AAuBAA,OAAM,0BAAC,CAAC,QAAD,CACC,mBADD,CAEC,gBAFD,CAGC,kBAHD,CAIC,oBAJD,CAKC,UALD,CAAD,CAME,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAqCC,CAArC,CAA+CC,CAA/C,CAA0DC,CAA1D,CAA+D,CAQnE,GAAIC,CAAAA,CAAK,CAAG,SAASC,CAAT,CAAwB,CAChCH,CAAS,CAACI,SAAV,CAAoBC,WAApB,CAAgCC,KAAhC,CAAsC,IAAtC,CAA4C,EAA5C,EACA,KAAKC,cAAL,CAAsBJ,CACzB,CAHD,CAIAD,CAAK,CAACE,SAAN,CAAkBI,MAAM,CAACC,MAAP,CAAcT,CAAS,CAACI,SAAxB,CAAlB,CAGAF,CAAK,CAACE,SAAN,CAAgBM,MAAhB,CAAyB,IAAzB,CAEAR,CAAK,CAACE,SAAN,CAAgBG,cAAhB,CAAiC,IAAjC,CAQAL,CAAK,CAACE,SAAN,CAAgBO,YAAhB,CAA+B,UAAW,CACtC,GAAIC,CAAAA,CAAO,CAAG,KAAKC,KAAL,CAAW,wBAAX,CAAd,CACIC,CAAS,CAAG,KAAKD,KAAL,CAAW,mBAAX,CADhB,CAEIE,CAAU,CAAG,KAAKF,KAAL,CAAW,oBAAX,CAFjB,CAIA,KAAKA,KAAL,CAAW,0BAAX,EAAqCG,KAArC,CAA2C,SAASC,CAAT,CAAY,CACnDA,CAAC,CAACC,cAAF,GACA,KAAKC,QAAL,CAAc,WAAd,EACA,KAAKC,KAAL,EACH,CAJ0C,CAIzCC,IAJyC,CAIpC,IAJoC,CAA3C,E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,CAGO,IAHP,CAHU,CAAd,CASA,MAAO,MAAKX,MACf,CAXK,CAWJW,IAXI,CAWC,IAXD,CAJC,EAgBNgB,KAhBM,CAgBAxC,CAAY,CAACyC,SAhBb,CAiBV,CAnBD,CA6BApC,CAAK,CAACE,SAAN,CAAgBS,KAAhB,CAAwB,SAAS0B,CAAT,CAAmB,CACvC,MAAO3C,CAAAA,CAAC,CAAC,KAAKc,MAAL,CAAY8B,UAAZ,EAAD,CAAD,CAA4BC,IAA5B,CAAiCF,CAAjC,CACV,CAFD,CAWArC,CAAK,CAACE,SAAN,CAAgB4B,OAAhB,CAA0B,UAAW,CACjC,GAAIU,CAAAA,CAAO,CAAG,CACVC,QAAQ,CAAE,KAAKC,SADL,CAEVC,OAAO,CAAE,KAAKtC,cAFJ,CAAd,CAIA,MAAOT,CAAAA,CAAS,CAACgD,MAAV,CAAiB,2BAAjB,CAA8CJ,CAA9C,CACV,CAND,CAQA,MAAOxC,CAAAA,CACV,CAlIK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Grade dialogue.\n *\n * @module tool_lp/grade_dialogue\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/templates',\n 'tool_lp/dialogue',\n 'tool_lp/event_base',\n 'core/str'],\n function($, Notification, Templates, Dialogue, EventBase, Str) {\n\n /**\n * Grade dialogue class.\n *\n * @class tool_lp/grade_dialogue\n * @param {Array} ratingOptions\n */\n var Grade = function(ratingOptions) {\n EventBase.prototype.constructor.apply(this, []);\n this._ratingOptions = ratingOptions;\n };\n Grade.prototype = Object.create(EventBase.prototype);\n\n /** @property {Dialogue} The dialogue. */\n Grade.prototype._popup = null;\n /** @property {Array} Array of objects containing, 'value', 'name' and optionally 'selected'. */\n Grade.prototype._ratingOptions = null;\n\n /**\n * After render hook.\n *\n * @method _afterRender\n * @protected\n */\n Grade.prototype._afterRender = function() {\n var btnRate = this._find('[data-action=\"rate\"]'),\n lstRating = this._find('[name=\"rating\"]'),\n txtComment = this._find('[name=\"comment\"]');\n\n this._find('[data-action=\"cancel\"]').click(function(e) {\n e.preventDefault();\n this._trigger('cancelled');\n this.close();\n }.bind(this));\n\n lstRating.change(function() {\n var node = $(this);\n if (!node.val()) {\n btnRate.prop('disabled', true);\n } else {\n btnRate.prop('disabled', false);\n }\n }).change();\n\n btnRate.click(function(e) {\n e.preventDefault();\n var val = lstRating.val();\n if (!val) {\n return;\n }\n this._trigger('rated', {\n 'rating': val,\n 'note': txtComment.val()\n });\n this.close();\n }.bind(this));\n };\n\n /**\n * Close the dialogue.\n *\n * @method close\n */\n Grade.prototype.close = function() {\n this._popup.close();\n this._popup = null;\n };\n\n /**\n * Opens the picker.\n *\n * @method display\n * @return {Promise}\n */\n Grade.prototype.display = function() {\n M.util.js_pending('tool_lp/grade_dialogue:display');\n return $.when(\n Str.get_string('rate', 'tool_lp'),\n this._render()\n )\n .then(function(title, templateResult) {\n this._popup = new Dialogue(\n title,\n templateResult[0],\n function() {\n this._afterRender();\n M.util.js_complete('tool_lp/grade_dialogue:display');\n }.bind(this)\n );\n\n return this._popup;\n }.bind(this))\n .catch(Notification.exception);\n };\n\n /**\n * Find a node in the dialogue.\n *\n * @param {String} selector\n * @method _find\n * @returns {node} The node\n * @protected\n */\n Grade.prototype._find = function(selector) {\n return $(this._popup.getContent()).find(selector);\n };\n\n /**\n * Render the dialogue.\n *\n * @method _render\n * @protected\n * @return {Promise}\n */\n Grade.prototype._render = function() {\n var context = {\n cangrade: this._canGrade,\n ratings: this._ratingOptions\n };\n return Templates.render('tool_lp/competency_grader', context);\n };\n\n return Grade;\n});\n"],"file":"grade_dialogue.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/menubar.min.js.map b/admin/tool/lp/amd/build/menubar.min.js.map index a04852bcc1c5a..8da85b4154347 100644 --- a/admin/tool/lp/amd/build/menubar.min.js.map +++ b/admin/tool/lp/amd/build/menubar.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/menubar.js"],"names":["define","$","documentClickHandlerRegistered","menuActive","closeAllSubMenus","attr","Menubar","menuRoot","handlers","rootMenus","children","subMenus","subMenuItems","allItems","add","activeItem","isChildOpen","keys","tab","enter","esc","space","left","up","right","down","addAriaAttributes","addEventListeners","prototype","openSubMenu","menu","setOpenDirection","currentThis","document","click","mouseenter","addClass","mouseout","removeClass","e","handleClick","keydown","handleKeyDown","focus","handleFocus","blur","handleBlur","item","stopPropagation","parentUL","parent","is","first","find","not","anchor","clickEvent","Event","target","eventHandled","each","selector","handler","length","callable","proxy","isDefaultPrevented","window","location","href","parentItems","parentsUntil","filter","itemUL","pos","offset","isRTL","body","hasClass","heightmenuRoot","outerHeight","widthmenuRoot","outerWidth","subMenuContainer","css","menuRealWidth","menuRealHeight","margintop","marginright","marginleft","top","scrollTop","height","width","altKey","ctrlKey","keyCode","moveToPrevious","moveToNext","moveUp","moveDown","menuItems","menuNum","menuIndex","index","newItem","childMenu","next","parentMenus","rootItem","last","prev","parentLI","startChr","newItemUL","match","curNdx","titleChr","eq","html","charAt","toLowerCase","enhance","element","data","closeAll"],"mappings":"AAuBAA,OAAM,mBAAC,CAAC,QAAD,CAAD,CAAa,SAASC,CAAT,CAAY,IAGvBC,CAAAA,CAA8B,GAHP,CAMvBC,CAAU,GANa,CAavBC,CAAgB,CAAG,UAAW,CAC9BH,CAAC,CAAC,iCAAD,CAAD,CAAqCI,IAArC,CAA0C,aAA1C,CAAyD,MAAzD,EAEAF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vB,CAAmC,IAAnC,EAGA,KAAKE,QAAL,CAAc6B,QAAd,CAAuB,cAAvB,EACA,KAAKvB,QAAL,CAAcuB,QAAd,CAAuB,mBAAvB,EACA,KAAK3B,SAAL,CAAe2B,QAAf,CAAwB,mBAAxB,EACA,KAAKzB,QAAL,CAAcyB,QAAd,CAAuB,kBAAvB,EACA,KAAKxB,YAAL,CAAkBwB,QAAlB,CAA2B,eAA3B,CACH,CAhBD,CAkBA,MAA4C,CA0BxCsF,OAAO,CAAE,iBAAS7D,CAAT,CAAmBC,CAAnB,CAA4B,CACjC7D,CAAC,CAAC4D,CAAD,CAAD,CAAYD,IAAZ,CAAiB,SAAS4C,CAAT,CAAgBmB,CAAhB,CAAyB,CACtC,GAAIpH,CAAAA,CAAQ,CAAGN,CAAC,CAAC0H,CAAD,CAAhB,CAEA,GAAI,KAAApH,CAAQ,CAACqH,IAAT,CAAc,iBAAd,CAAJ,CAA+C,CAC1C,GAAItH,CAAAA,CAAJ,CAAYC,CAAZ,CAAsBuD,CAAtB,CAAD,CACAvD,CAAQ,CAACqH,IAAT,CAAc,iBAAd,IACH,CACJ,CAPD,CAQH,CAnCuC,CAyCxCC,QAAQ,CAAEzH,CAzC8B,CA2C/C,CAlzBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Aria menubar functionality. Enhances a simple nested list structure into a full aria widget.\n * Based on the open ajax example: http://oaa-accessibility.org/example/26/\n *\n * @module tool_lp/menubar\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery'], function($) {\n\n /** @property {boolean} Flag to indicate if we have already registered a click event handler for the document. */\n var documentClickHandlerRegistered = false;\n\n /** @property {boolean} Flag to indicate whether there's an active, open menu. */\n var menuActive = false;\n\n /**\n * Close all open submenus anywhere in the page (there should only ever be one open at a time).\n *\n * @method closeAllSubMenus\n */\n var closeAllSubMenus = function() {\n $('.tool-lp-menu .tool-lp-sub-menu').attr('aria-hidden', 'true');\n // Every menu's closed at this point, so set the menu active flag to false.\n menuActive = false;\n };\n\n /**\n * Constructor\n *\n * @param {$} menuRoot Jquery collection matching the root of the menu.\n * @param {Function[]} handlers, called when a menu item is chosen.\n */\n var Menubar = function(menuRoot, handlers) {\n // Setup private class variables.\n this.menuRoot = menuRoot;\n this.handlers = handlers;\n this.rootMenus = this.menuRoot.children('li');\n this.subMenus = this.rootMenus.children('ul');\n this.subMenuItems = this.subMenus.children('li');\n this.allItems = this.rootMenus.add(this.subMenuItems);\n this.activeItem = null;\n this.isChildOpen = false;\n\n this.keys = {\n tab: 9,\n enter: 13,\n esc: 27,\n space: 32,\n left: 37,\n up: 38,\n right: 39,\n down: 40\n };\n\n this.addAriaAttributes();\n // Add the event listeners.\n this.addEventListeners();\n };\n\n /**\n * Open a submenu, first it closes all other sub-menus and sets the open direction.\n * @method openSubMenu\n * @param {Node} menu\n */\n Menubar.prototype.openSubMenu = function(menu) {\n this.setOpenDirection();\n closeAllSubMenus();\n menu.attr('aria-hidden', 'false');\n // Set menu active flag to true when a menu is opened.\n menuActive = true;\n };\n\n\n /**\n * Bind the event listeners to the DOM\n * @method addEventListeners\n */\n Menubar.prototype.addEventListeners = function() {\n var currentThis = this;\n\n // When clicking outside the menubar.\n if (documentClickHandlerRegistered === false) {\n $(document).click(function() {\n // Check if a menu is opened.\n if (menuActive) {\n // Close menu.\n closeAllSubMenus();\n }\n });\n // Set this flag to true so that we won't need to add a document click handler for the other Menubar instances.\n documentClickHandlerRegistered = true;\n }\n\n // Hovers.\n this.subMenuItems.mouseenter(function() {\n $(this).addClass('menu-hover');\n return true;\n });\n\n this.subMenuItems.mouseout(function() {\n $(this).removeClass('menu-hover');\n return true;\n });\n\n // Mouse listeners.\n this.allItems.click(function(e) {\n return currentThis.handleClick($(this), e);\n });\n\n // Key listeners.\n this.allItems.keydown(function(e) {\n return currentThis.handleKeyDown($(this), e);\n });\n\n this.allItems.focus(function() {\n return currentThis.handleFocus($(this));\n });\n\n this.allItems.blur(function() {\n return currentThis.handleBlur($(this));\n });\n };\n\n /**\n * Process click events for the top menus.\n *\n * @method handleClick\n * @param {Object} item is the jquery object of the item firing the event\n * @param {Event} e is the associated event object\n * @return {boolean} Returns false\n */\n Menubar.prototype.handleClick = function(item, e) {\n e.stopPropagation();\n\n var parentUL = item.parent();\n\n if (parentUL.is('.tool-lp-menu')) {\n // Toggle the child menu open/closed.\n if (item.children('ul').first().attr('aria-hidden') == 'true') {\n this.openSubMenu(item.children('ul').first());\n } else {\n item.children('ul').first().attr('aria-hidden', 'true');\n }\n } else {\n // Remove hover and focus styling.\n this.allItems.removeClass('menu-hover menu-focus');\n\n // Clear the active item.\n this.activeItem = null;\n\n // Close the menu.\n this.menuRoot.find('ul').not('.root-level').attr('aria-hidden', 'true');\n // Follow any link, or call the click handlers.\n var anchor = item.find('a').first();\n var clickEvent = new $.Event('click');\n clickEvent.target = anchor;\n var eventHandled = false;\n if (this.handlers) {\n $.each(this.handlers, function(selector, handler) {\n if (eventHandled) {\n return;\n }\n if (item.find(selector).length > 0) {\n var callable = $.proxy(handler, anchor);\n // False means stop propogatting events.\n eventHandled = (callable(clickEvent) === false) || clickEvent.isDefaultPrevented();\n }\n });\n }\n // If we didn't find a handler, and the HREF is # that probably means that\n // we are handling it from somewhere else. Let's just do nothing in that case.\n if (!eventHandled && anchor.attr('href') !== '#') {\n window.location.href = anchor.attr('href');\n }\n }\n return false;\n };\n\n /*\n * Process focus events for the menu.\n *\n * @method handleFocus\n * @param {Object} item is the jquery object of the item firing the event\n * @return boolean Returns false\n */\n Menubar.prototype.handleFocus = function(item) {\n\n // If activeItem is null, we are getting focus from outside the menu. Store\n // the item that triggered the event.\n if (this.activeItem === null) {\n this.activeItem = item;\n } else if (item[0] != this.activeItem[0]) {\n return true;\n }\n\n // Get the set of jquery objects for all the parent items of the active item.\n var parentItems = this.activeItem.parentsUntil('ul.tool-lp-menu').filter('li');\n\n // Remove focus styling from all other menu items.\n this.allItems.removeClass('menu-focus');\n\n // Add focus styling to the active item.\n this.activeItem.addClass('menu-focus');\n\n // Add focus styling to all parent items.\n parentItems.addClass('menu-focus');\n\n // If the bChildOpen flag has been set, open the active item's child menu (if applicable).\n if (this.isChildOpen === true) {\n\n var itemUL = item.parent();\n\n // If the itemUL is a root-level menu and item is a parent item,\n // show the child menu.\n if (itemUL.is('.tool-lp-menu') && (item.attr('aria-haspopup') == 'true')) {\n this.openSubMenu(item.children('ul').first());\n }\n }\n\n return true;\n };\n\n /*\n * Process blur events for the menu.\n *\n * @method handleBlur\n * @param {Object} item is the jquery object of the item firing the event\n * @return boolean Returns false\n */\n Menubar.prototype.handleBlur = function(item) {\n item.removeClass('menu-focus');\n\n return true;\n };\n\n /*\n * Determine if the menu should open to the left, or the right,\n * based on the screen size and menu position.\n * @method setOpenDirection\n */\n Menubar.prototype.setOpenDirection = function() {\n var pos = this.menuRoot.offset();\n var isRTL = $(document.body).hasClass('dir-rtl');\n var openLeft = true;\n var heightmenuRoot = this.rootMenus.outerHeight();\n var widthmenuRoot = this.rootMenus.outerWidth();\n // Sometimes the menuMinWidth is not enough to figure out if menu exceeds the window width.\n // So we have to calculate the real menu width.\n var subMenuContainer = this.rootMenus.find('ul.tool-lp-sub-menu');\n\n // Reset margins.\n subMenuContainer.css('margin-right', '');\n subMenuContainer.css('margin-left', '');\n subMenuContainer.css('margin-top', '');\n\n subMenuContainer.attr('aria-hidden', false);\n var menuRealWidth = subMenuContainer.outerWidth(),\n menuRealHeight = subMenuContainer.outerHeight();\n\n var margintop = null,\n marginright = null,\n marginleft = null;\n var top = pos.top - $(window).scrollTop();\n // Top is the same for RTL and LTR.\n if (top + menuRealHeight > $(window).height()) {\n margintop = menuRealHeight + heightmenuRoot;\n subMenuContainer.css('margin-top', '-' + margintop + 'px');\n }\n\n if (isRTL) {\n if (pos.left - menuRealWidth < 0) {\n marginright = menuRealWidth - widthmenuRoot;\n subMenuContainer.css('margin-right', '-' + marginright + 'px');\n }\n } else {\n if (pos.left + menuRealWidth > $(window).width()) {\n marginleft = menuRealWidth - widthmenuRoot;\n subMenuContainer.css('margin-left', '-' + marginleft + 'px');\n }\n }\n\n if (openLeft) {\n this.menuRoot.addClass('tool-lp-menu-open-left');\n } else {\n this.menuRoot.removeClass('tool-lp-menu-open-left');\n }\n\n };\n\n /*\n * Process keyDown events for the menu.\n *\n * @method handleKeyDown\n * @param {Object} item is the jquery object of the item firing the event\n * @param {Event} e is the associated event object\n * @return boolean Returns false if consuming the event\n */\n Menubar.prototype.handleKeyDown = function(item, e) {\n\n if (e.altKey || e.ctrlKey) {\n // Modifier key pressed: Do not process.\n return true;\n }\n\n switch (e.keyCode) {\n case this.keys.tab: {\n\n // Hide all menu items and update their aria attributes.\n this.menuRoot.find('ul').attr('aria-hidden', 'true');\n\n // Remove focus styling from all menu items.\n this.allItems.removeClass('menu-focus');\n\n this.activeItem = null;\n\n this.isChildOpen = false;\n\n break;\n }\n case this.keys.esc: {\n var itemUL = item.parent();\n\n if (itemUL.is('.tool-lp-menu')) {\n // Hide the child menu and update the aria attributes.\n item.children('ul').first().attr('aria-hidden', 'true');\n } else {\n\n // Move up one level.\n this.activeItem = itemUL.parent();\n\n // Reset the isChildOpen flag.\n this.isChildOpen = false;\n\n // Set focus on the new item.\n this.activeItem.focus();\n\n // Hide the active menu and update the aria attributes.\n itemUL.attr('aria-hidden', 'true');\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.enter:\n case this.keys.space: {\n // Trigger click handler.\n return this.handleClick(item, e);\n }\n\n case this.keys.left: {\n\n this.activeItem = this.moveToPrevious(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.right: {\n\n this.activeItem = this.moveToNext(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.up: {\n\n this.activeItem = this.moveUp(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.down: {\n\n this.activeItem = this.moveDown(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n }\n\n return true;\n\n };\n\n\n /**\n * Move to the next menu level.\n * This will be either the next root-level menu or the child of a menu parent. If\n * at the root level and the active item is the last in the menu, this function will loop\n * to the first menu item.\n *\n * If the menu is a horizontal menu, the first child element of the newly selected menu will\n * be selected\n *\n * @method moveToNext\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveToNext = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n\n // The items in the currently active menu.\n var menuItems = itemUL.children('li');\n\n // The number of items in the active menu.\n var menuNum = menuItems.length;\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var childMenu = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level move to next sibling. This will require closing\n // the current child menu and opening the new one.\n\n if (menuIndex < menuNum - 1) {\n // Not the last root menu.\n newItem = item.next();\n } else { // Wrap to first item.\n newItem = menuItems.first();\n }\n\n // Close the current child menu (if applicable).\n if (item.attr('aria-haspopup') == 'true') {\n\n childMenu = item.children('ul').first();\n\n if (childMenu.attr('aria-hidden') == 'false') {\n // Update the child menu's aria-hidden attribute.\n childMenu.attr('aria-hidden', 'true');\n this.isChildOpen = true;\n }\n }\n\n // Remove the focus styling from the current menu.\n item.removeClass('menu-focus');\n\n // Open the new child menu (if applicable).\n if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {\n\n childMenu = newItem.children('ul').first();\n\n // Update the child's aria-hidden attribute.\n this.openSubMenu(childMenu);\n }\n } else {\n // This is not the root level. If there is a child menu to be moved into, do that;\n // otherwise, move to the next root-level menu if there is one.\n if (item.attr('aria-haspopup') == 'true') {\n\n childMenu = item.children('ul').first();\n\n newItem = childMenu.children('li').first();\n\n // Show the child menu and update its aria attributes.\n this.openSubMenu(childMenu);\n } else {\n // At deepest level, move to the next root-level menu.\n\n var parentMenus = null;\n var rootItem = null;\n\n // Get list of all parent menus for item, up to the root level.\n parentMenus = item.parentsUntil('ul.tool-lp-menu').filter('ul').not('.tool-lp-menu');\n\n // Hide the current menu and update its aria attributes accordingly.\n parentMenus.attr('aria-hidden', 'true');\n\n // Remove the focus styling from the active menu.\n parentMenus.find('li').removeClass('menu-focus');\n parentMenus.last().parent().removeClass('menu-focus');\n\n // The containing root for the menu.\n rootItem = parentMenus.last().parent();\n\n menuIndex = this.rootMenus.index(rootItem);\n\n // If this is not the last root menu item, move to the next one.\n if (menuIndex < this.rootMenus.length - 1) {\n newItem = rootItem.next();\n } else {\n // Loop.\n newItem = this.rootMenus.first();\n }\n\n // Add the focus styling to the new menu.\n newItem.addClass('menu-focus');\n\n if (newItem.attr('aria-haspopup') == 'true') {\n childMenu = newItem.children('ul').first();\n\n newItem = childMenu.children('li').first();\n\n // Show the child menu and update it's aria attributes.\n this.openSubMenu(childMenu);\n this.isChildOpen = true;\n }\n }\n }\n\n return newItem;\n };\n\n /**\n * Member function to move to the previous menu level.\n * This will be either the previous root-level menu or the child of a menu parent. If\n * at the root level and the active item is the first in the menu, this function will loop\n * to the last menu item.\n *\n * If the menu is a horizontal menu, the first child element of the newly selected menu will\n * be selected\n *\n * @method moveToPrevious\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveToPrevious = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li');\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var childMenu = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level move to previous sibling. This will require closing\n // the current child menu and opening the new one.\n\n if (menuIndex > 0) {\n // Not the first root menu.\n newItem = item.prev();\n } else {\n // Wrap to last item.\n newItem = menuItems.last();\n }\n\n // Close the current child menu (if applicable).\n if (item.attr('aria-haspopup') == 'true') {\n childMenu = item.children('ul').first();\n\n if (childMenu.attr('aria-hidden') == 'false') {\n // Update the child menu's aria-hidden attribute.\n childMenu.attr('aria-hidden', 'true');\n this.isChildOpen = true;\n }\n }\n\n // Remove the focus styling from the current menu.\n item.removeClass('menu-focus');\n\n // Open the new child menu (if applicable).\n if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {\n\n childMenu = newItem.children('ul').first();\n\n // Update the child's aria-hidden attribute.\n this.openSubMenu(childMenu);\n\n }\n } else {\n // This is not the root level. If there is a parent menu that is not the\n // root menu, move up one level; otherwise, move to first item of the previous\n // root menu.\n\n var parentLI = itemUL.parent();\n var parentUL = parentLI.parent();\n\n // If this is a vertical menu or is not the first child menu\n // of the root-level menu, move up one level.\n if (!parentUL.is('.tool-lp-menu')) {\n\n newItem = itemUL.parent();\n\n // Hide the active menu and update aria-hidden.\n itemUL.attr('aria-hidden', 'true');\n\n // Remove the focus highlight from the item.\n item.removeClass('menu-focus');\n\n } else {\n // Move to previous root-level menu.\n\n // Hide the current menu and update the aria attributes accordingly.\n itemUL.attr('aria-hidden', 'true');\n\n // Remove the focus styling from the active menu.\n item.removeClass('menu-focus');\n parentLI.removeClass('menu-focus');\n\n menuIndex = this.rootMenus.index(parentLI);\n\n if (menuIndex > 0) {\n // Move to the previous root-level menu.\n newItem = parentLI.prev();\n } else {\n // Loop to last root-level menu.\n newItem = this.rootMenus.last();\n }\n\n // Add the focus styling to the new menu.\n newItem.addClass('menu-focus');\n\n if (newItem.attr('aria-haspopup') == 'true') {\n childMenu = newItem.children('ul').first();\n\n // Show the child menu and update it's aria attributes.\n this.openSubMenu(childMenu);\n this.isChildOpen = true;\n\n newItem = childMenu.children('li').first();\n }\n }\n }\n\n return newItem;\n };\n\n /**\n * Member function to select the next item in a menu.\n * If the active item is the last in the menu, this function will loop to the\n * first menu item.\n *\n * @method moveDown\n * @param {Object} item is the active menu item\n * @param {String} startChr is the character to attempt to match against the beginning of the\n * menu item titles. If found, focus moves to the next menu item beginning with that character.\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveDown = function(item, startChr) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li').not('.separator');\n // The number of items in the active menu.\n var menuNum = menuItems.length;\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var newItemUL = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level menu.\n\n if (item.attr('aria-haspopup') != 'true') {\n // No child menu to move to.\n return item;\n }\n\n // Move to the first item in the child menu.\n newItemUL = item.children('ul').first();\n newItem = newItemUL.children('li').first();\n\n // Make sure the child menu is visible.\n this.openSubMenu(newItemUL);\n\n return newItem;\n }\n\n // If $item is not the last item in its menu, move to the next item. If startChr is specified, move\n // to the next item with a title that begins with that character.\n if (startChr) {\n var match = false;\n var curNdx = menuIndex + 1;\n\n // Check if the active item was the last one on the list.\n if (curNdx == menuNum) {\n curNdx = 0;\n }\n\n // Iterate through the menu items (starting from the current item and wrapping) until a match is found\n // or the loop returns to the current menu item.\n while (curNdx != menuIndex) {\n\n var titleChr = menuItems.eq(curNdx).html().charAt(0);\n\n if (titleChr.toLowerCase() == startChr) {\n match = true;\n break;\n }\n\n curNdx = curNdx + 1;\n\n if (curNdx == menuNum) {\n // Reached the end of the list, start again at the beginning.\n curNdx = 0;\n }\n }\n\n if (match === true) {\n newItem = menuItems.eq(curNdx);\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n } else {\n return item;\n }\n } else {\n if (menuIndex < menuNum - 1) {\n newItem = menuItems.eq(menuIndex + 1);\n } else {\n newItem = menuItems.first();\n }\n }\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n };\n\n /**\n * Function moveUp() is a member function to select the previous item in a menu.\n * If the active item is the first in the menu, this function will loop to the\n * last menu item.\n *\n * @method moveUp\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveUp = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li').not('.separator');\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level menu.\n // Nothing to do.\n return item;\n }\n\n // If item is not the first item in its menu, move to the previous item.\n if (menuIndex > 0) {\n newItem = menuItems.eq(menuIndex - 1);\n } else {\n // Loop to top of menu.\n newItem = menuItems.last();\n }\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n };\n\n /**\n * Enhance the dom with aria attributes.\n * @method addAriaAttributes\n */\n Menubar.prototype.addAriaAttributes = function() {\n this.menuRoot.attr('role', 'menubar');\n this.rootMenus.attr('role', 'menuitem');\n this.rootMenus.attr('tabindex', '0');\n this.rootMenus.attr('aria-haspopup', 'true');\n this.subMenus.attr('role', 'menu');\n this.subMenus.attr('aria-hidden', 'true');\n this.subMenuItems.attr('role', 'menuitem');\n this.subMenuItems.attr('tabindex', '-1');\n\n // For CSS styling and effects.\n this.menuRoot.addClass('tool-lp-menu');\n this.allItems.addClass('tool-lp-menu-item');\n this.rootMenus.addClass('tool-lp-root-menu');\n this.subMenus.addClass('tool-lp-sub-menu');\n this.subMenuItems.addClass('dropdown-item');\n };\n\n return /** @alias module:tool_lp/menubar */ {\n /**\n * Create a menu bar object for every node matching the selector.\n *\n * The expected DOM structure is shown below.\n *
    <- This is the target of the selector parameter.\n *
  • <- This is repeated for each top level menu.\n * Text <- This is the text for the top level menu.\n *
      <- This is a list of the entries in this top level menu.\n *
    • <- This is repeated for each menu entry.\n * Choice 1 <- The anchor for the menu.\n *
    • \n *
    \n *
  • \n *
\n *\n * @method enhance\n * @param {String} selector - The selector for the outer most menu node.\n * @param {Function} handler - Javascript handler for when a menu item was chosen. If the\n * handler returns true (or does not exist), the\n * menu will look for an anchor with a link to follow.\n * For example, if the menu entry has a \"data-action\" attribute\n * and we want to call a javascript function when that entry is chosen,\n * we could pass a list of handlers like this:\n * { \"[data-action='add']\" : callAddFunction }\n */\n enhance: function(selector, handler) {\n $(selector).each(function(index, element) {\n var menuRoot = $(element);\n // Don't enhance the same menu twice.\n if (menuRoot.data(\"menubarEnhanced\") !== true) {\n (new Menubar(menuRoot, handler));\n menuRoot.data(\"menubarEnhanced\", true);\n }\n });\n },\n\n /**\n * Handy function to close all open menus anywhere on the page.\n * @method closeAll\n */\n closeAll: closeAllSubMenus\n };\n});\n"],"file":"menubar.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/menubar.js"],"names":["define","$","documentClickHandlerRegistered","menuActive","closeAllSubMenus","attr","Menubar","menuRoot","handlers","rootMenus","children","subMenus","subMenuItems","allItems","add","activeItem","isChildOpen","keys","tab","enter","esc","space","left","up","right","down","addAriaAttributes","addEventListeners","prototype","openSubMenu","menu","setOpenDirection","currentThis","document","click","mouseenter","addClass","mouseout","removeClass","e","handleClick","keydown","handleKeyDown","focus","handleFocus","blur","handleBlur","item","stopPropagation","parentUL","parent","is","first","find","not","anchor","clickEvent","Event","target","eventHandled","each","selector","handler","length","callable","proxy","isDefaultPrevented","window","location","href","parentItems","parentsUntil","filter","itemUL","pos","offset","isRTL","body","hasClass","heightmenuRoot","outerHeight","widthmenuRoot","outerWidth","subMenuContainer","css","menuRealWidth","menuRealHeight","margintop","marginright","marginleft","top","scrollTop","height","width","altKey","ctrlKey","keyCode","moveToPrevious","moveToNext","moveUp","moveDown","menuItems","menuNum","menuIndex","index","newItem","childMenu","next","parentMenus","rootItem","last","prev","parentLI","startChr","newItemUL","match","curNdx","titleChr","eq","html","charAt","toLowerCase","enhance","element","data","clos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,MAArC,EACA,KAAKM,QAAL,CAAcN,IAAd,CAAmB,MAAnB,CAA2B,MAA3B,EACA,KAAKM,QAAL,CAAcN,IAAd,CAAmB,aAAnB,CAAkC,MAAlC,EACA,KAAKO,YAAL,CAAkBP,IAAlB,CAAuB,MAAvB,CAA+B,UAA/B,EACA,KAAKO,YAAL,CAAkBP,IAAlB,CAAuB,UAAvB,CAAmC,IAAnC,EAGA,KAAKE,QAAL,CAAc6B,QAAd,CAAuB,cAAvB,EACA,KAAKvB,QAAL,CAAcuB,QAAd,CAAuB,mBAAvB,EACA,KAAK3B,SAAL,CAAe2B,QAAf,CAAwB,mBAAxB,EACA,KAAKzB,QAAL,CAAcyB,QAAd,CAAuB,kBAAvB,EACA,KAAKxB,YAAL,CAAkBwB,QAAlB,CAA2B,eAA3B,CACH,CAhBD,CAkBA,MAA4C,CA0BxCsF,OAAO,CAAE,iBAAS7D,CAAT,CAAmBC,CAAnB,CAA4B,CACjC7D,CAAC,CAAC4D,CAAD,CAAD,CAAYD,IAAZ,CAAiB,SAAS4C,CAAT,CAAgBmB,CAAhB,CAAyB,CACtC,GAAIpH,CAAAA,CAAQ,CAAGN,CAAC,CAAC0H,CAAD,CAAhB,CAEA,GAAI,KAAApH,CAAQ,CAACqH,IAAT,CAAc,iBAAd,CAAJ,CAA+C,CAC1C,GAAItH,CAAAA,CAAJ,CAAYC,CAAZ,CAAsBuD,CAAtB,CAAD,CACAvD,CAAQ,CAACqH,IAAT,CAAc,iBAAd,IACH,CACJ,CAPD,CAQH,CAnCuC,CAyCxCC,QAAQ,CAAEzH,CAzC8B,CA2C/C,CAlzBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Aria menubar functionality. Enhances a simple nested list structure into a full aria widget.\n * Based on the open ajax example: http://oaa-accessibility.org/example/26/\n *\n * @module tool_lp/menubar\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery'], function($) {\n\n /** @property {boolean} Flag to indicate if we have already registered a click event handler for the document. */\n var documentClickHandlerRegistered = false;\n\n /** @property {boolean} Flag to indicate whether there's an active, open menu. */\n var menuActive = false;\n\n /**\n * Close all open submenus anywhere in the page (there should only ever be one open at a time).\n *\n * @method closeAllSubMenus\n */\n var closeAllSubMenus = function() {\n $('.tool-lp-menu .tool-lp-sub-menu').attr('aria-hidden', 'true');\n // Every menu's closed at this point, so set the menu active flag to false.\n menuActive = false;\n };\n\n /**\n * Constructor\n *\n * @param {jQuery} menuRoot Jquery collection matching the root of the menu.\n * @param {Function[]} handlers called when a menu item is chosen.\n */\n var Menubar = function(menuRoot, handlers) {\n // Setup private class variables.\n this.menuRoot = menuRoot;\n this.handlers = handlers;\n this.rootMenus = this.menuRoot.children('li');\n this.subMenus = this.rootMenus.children('ul');\n this.subMenuItems = this.subMenus.children('li');\n this.allItems = this.rootMenus.add(this.subMenuItems);\n this.activeItem = null;\n this.isChildOpen = false;\n\n this.keys = {\n tab: 9,\n enter: 13,\n esc: 27,\n space: 32,\n left: 37,\n up: 38,\n right: 39,\n down: 40\n };\n\n this.addAriaAttributes();\n // Add the event listeners.\n this.addEventListeners();\n };\n\n /**\n * Open a submenu, first it closes all other sub-menus and sets the open direction.\n * @method openSubMenu\n * @param {Node} menu\n */\n Menubar.prototype.openSubMenu = function(menu) {\n this.setOpenDirection();\n closeAllSubMenus();\n menu.attr('aria-hidden', 'false');\n // Set menu active flag to true when a menu is opened.\n menuActive = true;\n };\n\n\n /**\n * Bind the event listeners to the DOM\n * @method addEventListeners\n */\n Menubar.prototype.addEventListeners = function() {\n var currentThis = this;\n\n // When clicking outside the menubar.\n if (documentClickHandlerRegistered === false) {\n $(document).click(function() {\n // Check if a menu is opened.\n if (menuActive) {\n // Close menu.\n closeAllSubMenus();\n }\n });\n // Set this flag to true so that we won't need to add a document click handler for the other Menubar instances.\n documentClickHandlerRegistered = true;\n }\n\n // Hovers.\n this.subMenuItems.mouseenter(function() {\n $(this).addClass('menu-hover');\n return true;\n });\n\n this.subMenuItems.mouseout(function() {\n $(this).removeClass('menu-hover');\n return true;\n });\n\n // Mouse listeners.\n this.allItems.click(function(e) {\n return currentThis.handleClick($(this), e);\n });\n\n // Key listeners.\n this.allItems.keydown(function(e) {\n return currentThis.handleKeyDown($(this), e);\n });\n\n this.allItems.focus(function() {\n return currentThis.handleFocus($(this));\n });\n\n this.allItems.blur(function() {\n return currentThis.handleBlur($(this));\n });\n };\n\n /**\n * Process click events for the top menus.\n *\n * @method handleClick\n * @param {Object} item is the jquery object of the item firing the event\n * @param {Event} e is the associated event object\n * @return {boolean} Returns false\n */\n Menubar.prototype.handleClick = function(item, e) {\n e.stopPropagation();\n\n var parentUL = item.parent();\n\n if (parentUL.is('.tool-lp-menu')) {\n // Toggle the child menu open/closed.\n if (item.children('ul').first().attr('aria-hidden') == 'true') {\n this.openSubMenu(item.children('ul').first());\n } else {\n item.children('ul').first().attr('aria-hidden', 'true');\n }\n } else {\n // Remove hover and focus styling.\n this.allItems.removeClass('menu-hover menu-focus');\n\n // Clear the active item.\n this.activeItem = null;\n\n // Close the menu.\n this.menuRoot.find('ul').not('.root-level').attr('aria-hidden', 'true');\n // Follow any link, or call the click handlers.\n var anchor = item.find('a').first();\n var clickEvent = new $.Event('click');\n clickEvent.target = anchor;\n var eventHandled = false;\n if (this.handlers) {\n $.each(this.handlers, function(selector, handler) {\n if (eventHandled) {\n return;\n }\n if (item.find(selector).length > 0) {\n var callable = $.proxy(handler, anchor);\n // False means stop propogatting events.\n eventHandled = (callable(clickEvent) === false) || clickEvent.isDefaultPrevented();\n }\n });\n }\n // If we didn't find a handler, and the HREF is # that probably means that\n // we are handling it from somewhere else. Let's just do nothing in that case.\n if (!eventHandled && anchor.attr('href') !== '#') {\n window.location.href = anchor.attr('href');\n }\n }\n return false;\n };\n\n /*\n * Process focus events for the menu.\n *\n * @method handleFocus\n * @param {Object} item is the jquery object of the item firing the event\n * @return boolean Returns false\n */\n Menubar.prototype.handleFocus = function(item) {\n\n // If activeItem is null, we are getting focus from outside the menu. Store\n // the item that triggered the event.\n if (this.activeItem === null) {\n this.activeItem = item;\n } else if (item[0] != this.activeItem[0]) {\n return true;\n }\n\n // Get the set of jquery objects for all the parent items of the active item.\n var parentItems = this.activeItem.parentsUntil('ul.tool-lp-menu').filter('li');\n\n // Remove focus styling from all other menu items.\n this.allItems.removeClass('menu-focus');\n\n // Add focus styling to the active item.\n this.activeItem.addClass('menu-focus');\n\n // Add focus styling to all parent items.\n parentItems.addClass('menu-focus');\n\n // If the bChildOpen flag has been set, open the active item's child menu (if applicable).\n if (this.isChildOpen === true) {\n\n var itemUL = item.parent();\n\n // If the itemUL is a root-level menu and item is a parent item,\n // show the child menu.\n if (itemUL.is('.tool-lp-menu') && (item.attr('aria-haspopup') == 'true')) {\n this.openSubMenu(item.children('ul').first());\n }\n }\n\n return true;\n };\n\n /*\n * Process blur events for the menu.\n *\n * @method handleBlur\n * @param {Object} item is the jquery object of the item firing the event\n * @return boolean Returns false\n */\n Menubar.prototype.handleBlur = function(item) {\n item.removeClass('menu-focus');\n\n return true;\n };\n\n /*\n * Determine if the menu should open to the left, or the right,\n * based on the screen size and menu position.\n * @method setOpenDirection\n */\n Menubar.prototype.setOpenDirection = function() {\n var pos = this.menuRoot.offset();\n var isRTL = $(document.body).hasClass('dir-rtl');\n var openLeft = true;\n var heightmenuRoot = this.rootMenus.outerHeight();\n var widthmenuRoot = this.rootMenus.outerWidth();\n // Sometimes the menuMinWidth is not enough to figure out if menu exceeds the window width.\n // So we have to calculate the real menu width.\n var subMenuContainer = this.rootMenus.find('ul.tool-lp-sub-menu');\n\n // Reset margins.\n subMenuContainer.css('margin-right', '');\n subMenuContainer.css('margin-left', '');\n subMenuContainer.css('margin-top', '');\n\n subMenuContainer.attr('aria-hidden', false);\n var menuRealWidth = subMenuContainer.outerWidth(),\n menuRealHeight = subMenuContainer.outerHeight();\n\n var margintop = null,\n marginright = null,\n marginleft = null;\n var top = pos.top - $(window).scrollTop();\n // Top is the same for RTL and LTR.\n if (top + menuRealHeight > $(window).height()) {\n margintop = menuRealHeight + heightmenuRoot;\n subMenuContainer.css('margin-top', '-' + margintop + 'px');\n }\n\n if (isRTL) {\n if (pos.left - menuRealWidth < 0) {\n marginright = menuRealWidth - widthmenuRoot;\n subMenuContainer.css('margin-right', '-' + marginright + 'px');\n }\n } else {\n if (pos.left + menuRealWidth > $(window).width()) {\n marginleft = menuRealWidth - widthmenuRoot;\n subMenuContainer.css('margin-left', '-' + marginleft + 'px');\n }\n }\n\n if (openLeft) {\n this.menuRoot.addClass('tool-lp-menu-open-left');\n } else {\n this.menuRoot.removeClass('tool-lp-menu-open-left');\n }\n\n };\n\n /*\n * Process keyDown events for the menu.\n *\n * @method handleKeyDown\n * @param {Object} item is the jquery object of the item firing the event\n * @param {Event} e is the associated event object\n * @return boolean Returns false if consuming the event\n */\n Menubar.prototype.handleKeyDown = function(item, e) {\n\n if (e.altKey || e.ctrlKey) {\n // Modifier key pressed: Do not process.\n return true;\n }\n\n switch (e.keyCode) {\n case this.keys.tab: {\n\n // Hide all menu items and update their aria attributes.\n this.menuRoot.find('ul').attr('aria-hidden', 'true');\n\n // Remove focus styling from all menu items.\n this.allItems.removeClass('menu-focus');\n\n this.activeItem = null;\n\n this.isChildOpen = false;\n\n break;\n }\n case this.keys.esc: {\n var itemUL = item.parent();\n\n if (itemUL.is('.tool-lp-menu')) {\n // Hide the child menu and update the aria attributes.\n item.children('ul').first().attr('aria-hidden', 'true');\n } else {\n\n // Move up one level.\n this.activeItem = itemUL.parent();\n\n // Reset the isChildOpen flag.\n this.isChildOpen = false;\n\n // Set focus on the new item.\n this.activeItem.focus();\n\n // Hide the active menu and update the aria attributes.\n itemUL.attr('aria-hidden', 'true');\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.enter:\n case this.keys.space: {\n // Trigger click handler.\n return this.handleClick(item, e);\n }\n\n case this.keys.left: {\n\n this.activeItem = this.moveToPrevious(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.right: {\n\n this.activeItem = this.moveToNext(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.up: {\n\n this.activeItem = this.moveUp(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n case this.keys.down: {\n\n this.activeItem = this.moveDown(item);\n\n this.activeItem.focus();\n\n e.stopPropagation();\n return false;\n }\n }\n\n return true;\n\n };\n\n\n /**\n * Move to the next menu level.\n * This will be either the next root-level menu or the child of a menu parent. If\n * at the root level and the active item is the last in the menu, this function will loop\n * to the first menu item.\n *\n * If the menu is a horizontal menu, the first child element of the newly selected menu will\n * be selected\n *\n * @method moveToNext\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveToNext = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n\n // The items in the currently active menu.\n var menuItems = itemUL.children('li');\n\n // The number of items in the active menu.\n var menuNum = menuItems.length;\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var childMenu = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level move to next sibling. This will require closing\n // the current child menu and opening the new one.\n\n if (menuIndex < menuNum - 1) {\n // Not the last root menu.\n newItem = item.next();\n } else { // Wrap to first item.\n newItem = menuItems.first();\n }\n\n // Close the current child menu (if applicable).\n if (item.attr('aria-haspopup') == 'true') {\n\n childMenu = item.children('ul').first();\n\n if (childMenu.attr('aria-hidden') == 'false') {\n // Update the child menu's aria-hidden attribute.\n childMenu.attr('aria-hidden', 'true');\n this.isChildOpen = true;\n }\n }\n\n // Remove the focus styling from the current menu.\n item.removeClass('menu-focus');\n\n // Open the new child menu (if applicable).\n if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {\n\n childMenu = newItem.children('ul').first();\n\n // Update the child's aria-hidden attribute.\n this.openSubMenu(childMenu);\n }\n } else {\n // This is not the root level. If there is a child menu to be moved into, do that;\n // otherwise, move to the next root-level menu if there is one.\n if (item.attr('aria-haspopup') == 'true') {\n\n childMenu = item.children('ul').first();\n\n newItem = childMenu.children('li').first();\n\n // Show the child menu and update its aria attributes.\n this.openSubMenu(childMenu);\n } else {\n // At deepest level, move to the next root-level menu.\n\n var parentMenus = null;\n var rootItem = null;\n\n // Get list of all parent menus for item, up to the root level.\n parentMenus = item.parentsUntil('ul.tool-lp-menu').filter('ul').not('.tool-lp-menu');\n\n // Hide the current menu and update its aria attributes accordingly.\n parentMenus.attr('aria-hidden', 'true');\n\n // Remove the focus styling from the active menu.\n parentMenus.find('li').removeClass('menu-focus');\n parentMenus.last().parent().removeClass('menu-focus');\n\n // The containing root for the menu.\n rootItem = parentMenus.last().parent();\n\n menuIndex = this.rootMenus.index(rootItem);\n\n // If this is not the last root menu item, move to the next one.\n if (menuIndex < this.rootMenus.length - 1) {\n newItem = rootItem.next();\n } else {\n // Loop.\n newItem = this.rootMenus.first();\n }\n\n // Add the focus styling to the new menu.\n newItem.addClass('menu-focus');\n\n if (newItem.attr('aria-haspopup') == 'true') {\n childMenu = newItem.children('ul').first();\n\n newItem = childMenu.children('li').first();\n\n // Show the child menu and update it's aria attributes.\n this.openSubMenu(childMenu);\n this.isChildOpen = true;\n }\n }\n }\n\n return newItem;\n };\n\n /**\n * Member function to move to the previous menu level.\n * This will be either the previous root-level menu or the child of a menu parent. If\n * at the root level and the active item is the first in the menu, this function will loop\n * to the last menu item.\n *\n * If the menu is a horizontal menu, the first child element of the newly selected menu will\n * be selected\n *\n * @method moveToPrevious\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveToPrevious = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li');\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var childMenu = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level move to previous sibling. This will require closing\n // the current child menu and opening the new one.\n\n if (menuIndex > 0) {\n // Not the first root menu.\n newItem = item.prev();\n } else {\n // Wrap to last item.\n newItem = menuItems.last();\n }\n\n // Close the current child menu (if applicable).\n if (item.attr('aria-haspopup') == 'true') {\n childMenu = item.children('ul').first();\n\n if (childMenu.attr('aria-hidden') == 'false') {\n // Update the child menu's aria-hidden attribute.\n childMenu.attr('aria-hidden', 'true');\n this.isChildOpen = true;\n }\n }\n\n // Remove the focus styling from the current menu.\n item.removeClass('menu-focus');\n\n // Open the new child menu (if applicable).\n if ((newItem.attr('aria-haspopup') === 'true') && (this.isChildOpen === true)) {\n\n childMenu = newItem.children('ul').first();\n\n // Update the child's aria-hidden attribute.\n this.openSubMenu(childMenu);\n\n }\n } else {\n // This is not the root level. If there is a parent menu that is not the\n // root menu, move up one level; otherwise, move to first item of the previous\n // root menu.\n\n var parentLI = itemUL.parent();\n var parentUL = parentLI.parent();\n\n // If this is a vertical menu or is not the first child menu\n // of the root-level menu, move up one level.\n if (!parentUL.is('.tool-lp-menu')) {\n\n newItem = itemUL.parent();\n\n // Hide the active menu and update aria-hidden.\n itemUL.attr('aria-hidden', 'true');\n\n // Remove the focus highlight from the item.\n item.removeClass('menu-focus');\n\n } else {\n // Move to previous root-level menu.\n\n // Hide the current menu and update the aria attributes accordingly.\n itemUL.attr('aria-hidden', 'true');\n\n // Remove the focus styling from the active menu.\n item.removeClass('menu-focus');\n parentLI.removeClass('menu-focus');\n\n menuIndex = this.rootMenus.index(parentLI);\n\n if (menuIndex > 0) {\n // Move to the previous root-level menu.\n newItem = parentLI.prev();\n } else {\n // Loop to last root-level menu.\n newItem = this.rootMenus.last();\n }\n\n // Add the focus styling to the new menu.\n newItem.addClass('menu-focus');\n\n if (newItem.attr('aria-haspopup') == 'true') {\n childMenu = newItem.children('ul').first();\n\n // Show the child menu and update it's aria attributes.\n this.openSubMenu(childMenu);\n this.isChildOpen = true;\n\n newItem = childMenu.children('li').first();\n }\n }\n }\n\n return newItem;\n };\n\n /**\n * Member function to select the next item in a menu.\n * If the active item is the last in the menu, this function will loop to the\n * first menu item.\n *\n * @method moveDown\n * @param {Object} item is the active menu item\n * @param {String} startChr is the character to attempt to match against the beginning of the\n * menu item titles. If found, focus moves to the next menu item beginning with that character.\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveDown = function(item, startChr) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li').not('.separator');\n // The number of items in the active menu.\n var menuNum = menuItems.length;\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n var newItemUL = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level menu.\n\n if (item.attr('aria-haspopup') != 'true') {\n // No child menu to move to.\n return item;\n }\n\n // Move to the first item in the child menu.\n newItemUL = item.children('ul').first();\n newItem = newItemUL.children('li').first();\n\n // Make sure the child menu is visible.\n this.openSubMenu(newItemUL);\n\n return newItem;\n }\n\n // If $item is not the last item in its menu, move to the next item. If startChr is specified, move\n // to the next item with a title that begins with that character.\n if (startChr) {\n var match = false;\n var curNdx = menuIndex + 1;\n\n // Check if the active item was the last one on the list.\n if (curNdx == menuNum) {\n curNdx = 0;\n }\n\n // Iterate through the menu items (starting from the current item and wrapping) until a match is found\n // or the loop returns to the current menu item.\n while (curNdx != menuIndex) {\n\n var titleChr = menuItems.eq(curNdx).html().charAt(0);\n\n if (titleChr.toLowerCase() == startChr) {\n match = true;\n break;\n }\n\n curNdx = curNdx + 1;\n\n if (curNdx == menuNum) {\n // Reached the end of the list, start again at the beginning.\n curNdx = 0;\n }\n }\n\n if (match === true) {\n newItem = menuItems.eq(curNdx);\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n } else {\n return item;\n }\n } else {\n if (menuIndex < menuNum - 1) {\n newItem = menuItems.eq(menuIndex + 1);\n } else {\n newItem = menuItems.first();\n }\n }\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n };\n\n /**\n * Function moveUp() is a member function to select the previous item in a menu.\n * If the active item is the first in the menu, this function will loop to the\n * last menu item.\n *\n * @method moveUp\n * @param {Object} item is the active menu item\n * @return {Object} Returns the item to move to. Returns item is no move is possible\n */\n Menubar.prototype.moveUp = function(item) {\n // Item's containing menu.\n var itemUL = item.parent();\n // The items in the currently active menu.\n var menuItems = itemUL.children('li').not('.separator');\n // The items index in its menu.\n var menuIndex = menuItems.index(item);\n var newItem = null;\n\n if (itemUL.is('.tool-lp-menu')) {\n // This is the root level menu.\n // Nothing to do.\n return item;\n }\n\n // If item is not the first item in its menu, move to the previous item.\n if (menuIndex > 0) {\n newItem = menuItems.eq(menuIndex - 1);\n } else {\n // Loop to top of menu.\n newItem = menuItems.last();\n }\n\n // Remove the focus styling from the current item.\n item.removeClass('menu-focus');\n\n return newItem;\n };\n\n /**\n * Enhance the dom with aria attributes.\n * @method addAriaAttributes\n */\n Menubar.prototype.addAriaAttributes = function() {\n this.menuRoot.attr('role', 'menubar');\n this.rootMenus.attr('role', 'menuitem');\n this.rootMenus.attr('tabindex', '0');\n this.rootMenus.attr('aria-haspopup', 'true');\n this.subMenus.attr('role', 'menu');\n this.subMenus.attr('aria-hidden', 'true');\n this.subMenuItems.attr('role', 'menuitem');\n this.subMenuItems.attr('tabindex', '-1');\n\n // For CSS styling and effects.\n this.menuRoot.addClass('tool-lp-menu');\n this.allItems.addClass('tool-lp-menu-item');\n this.rootMenus.addClass('tool-lp-root-menu');\n this.subMenus.addClass('tool-lp-sub-menu');\n this.subMenuItems.addClass('dropdown-item');\n };\n\n return /** @alias module:tool_lp/menubar */ {\n /**\n * Create a menu bar object for every node matching the selector.\n *\n * The expected DOM structure is shown below.\n *
    <- This is the target of the selector parameter.\n *
  • <- This is repeated for each top level menu.\n * Text <- This is the text for the top level menu.\n *
      <- This is a list of the entries in this top level menu.\n *
    • <- This is repeated for each menu entry.\n * Choice 1 <- The anchor for the menu.\n *
    • \n *
    \n *
  • \n *
\n *\n * @method enhance\n * @param {String} selector - The selector for the outer most menu node.\n * @param {Function} handler - Javascript handler for when a menu item was chosen. If the\n * handler returns true (or does not exist), the\n * menu will look for an anchor with a link to follow.\n * For example, if the menu entry has a \"data-action\" attribute\n * and we want to call a javascript function when that entry is chosen,\n * we could pass a list of handlers like this:\n * { \"[data-action='add']\" : callAddFunction }\n */\n enhance: function(selector, handler) {\n $(selector).each(function(index, element) {\n var menuRoot = $(element);\n // Don't enhance the same menu twice.\n if (menuRoot.data(\"menubarEnhanced\") !== true) {\n (new Menubar(menuRoot, handler));\n menuRoot.data(\"menubarEnhanced\", true);\n }\n });\n },\n\n /**\n * Handy function to close all open menus anywhere on the page.\n * @method closeAll\n */\n closeAll: closeAllSubMenus\n };\n});\n"],"file":"menubar.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/tree.min.js.map b/admin/tool/lp/amd/build/tree.min.js.map index 70eeb50519dfa..257bfb049a5f6 100644 --- a/admin/tool/lp/amd/build/tree.min.js.map +++ b/admin/tool/lp/amd/build/tree.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/tree.js"],"names":["define","$","url","log","expandedImage","imageUrl","collapsedImage","Tree","selector","multiSelect","treeRoot","items","find","expandAll","length","parents","attr","visibleItems","activeItem","lastActiveItem","keys","tab","enter","space","pageup","pagedown","end","home","left","up","right","down","eight","asterisk","init","bindEventHandlers","prototype","prepend","clone","thisObj","each","collapseGroup","expandGroup","first","item","group","children","show","hide","toggleGroup","triggerChange","allSelected","filter","trigger","selected","multiSelectItem","lastIndex","index","currentIndex","oneItem","get","selectItem","walk","parent","toggleItem","current","updateFocus","handleKeyDown","e","newItem","hasKeyModifier","shiftKey","ctrlKey","metaKey","altKey","keyCode","focus","stopPropagation","last","has","itemUL","itemParent","is","prev","eq","next","handleKeyPress","chr","String","fromCharCode","which","match","itemIndex","itemCount","currentItem","titleChr","text","charAt","toLowerCase","on","eventname","handler","warning","handleDblClick","handleExpandCollapseClick","handleClick","handleBlur","handleFocus","dblclick","click","keydown","keypress","blur"],"mappings":"AA2BAA,OAAM,gBAAC,CAAC,QAAD,CAAW,UAAX,CAAuB,UAAvB,CAAD,CAAqC,SAASC,CAAT,CAAYC,CAAZ,CAAiBC,CAAjB,CAAsB,IAGzDC,CAAAA,CAAa,CAAGH,CAAC,CAAC,uBAAsBC,CAAG,CAACG,QAAJ,CAAa,YAAb,CAAtB,CAAmD,MAApD,CAHwC,CAKzDC,CAAc,CAAGL,CAAC,CAAC,uBAAsBC,CAAG,CAACG,QAAJ,CAAa,aAAb,CAAtB,CAAoD,MAArD,CALuC,CAazDE,CAAI,CAAG,SAASC,CAAT,CAAmBC,CAAnB,CAAgC,CACvC,KAAKC,QAAL,CAAgBT,CAAC,CAACO,CAAD,CAAjB,CACA,KAAKC,WAAL,CAA2C,WAAvB,QAAOA,CAAAA,CAAP,EAAsC,KAAAA,CAA1D,CAEA,KAAKE,KAAL,CAAa,KAAKD,QAAL,CAAcE,IAAd,CAAmB,IAAnB,CAAb,CACA,KAAKC,SAAL,CAAqC,EAApB,MAAKF,KAAL,CAAWG,MAA5B,CACA,KAAKC,OAAL,CAAe,KAAKL,QAAL,CAAcE,IAAd,CAAmB,YAAnB,CAAf,CAEA,GAAIH,CAAJ,CAAiB,CACb,KAAKC,QAAL,CAAcM,IAAd,CAAmB,sBAAnB,CAA2C,MAA3C,CACH,CAED,KAAKL,KAAL,CAAWK,IAAX,CAAgB,eAAhB,CAAiC,OAAjC,EAEA,KAAKC,YAAL,CAAoB,IAApB,CACA,KAAKC,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C7D,CAAAA,CAC5C,CA1mBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Implement an accessible aria tree widget, from a nested unordered list.\n * Based on http://oaa-accessibility.org/example/41/\n *\n * To respond to selection changed events - use tree.on(\"selectionchanged\", handler).\n * The handler will receive an array of nodes, which are the list items that are currently\n * selected. (Or a single node if multiselect is disabled).\n *\n * @module tool_lp/tree\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/url', 'core/log'], function($, url, log) {\n // Private variables and functions.\n /** @var {String} expandedImage The html for an expanded tree node twistie. */\n var expandedImage = $('\"\"');\n /** @var {String} collapsedImage The html for a collapsed tree node twistie. */\n var collapsedImage = $('\"\"');\n\n /**\n * Constructor\n *\n * @param {String} selector\n * @param {Boolean} multiSelect\n */\n var Tree = function(selector, multiSelect) {\n this.treeRoot = $(selector);\n this.multiSelect = (typeof multiSelect === 'undefined' || multiSelect === true);\n\n this.items = this.treeRoot.find('li');\n this.expandAll = this.items.length < 20;\n this.parents = this.treeRoot.find('li:has(ul)');\n\n if (multiSelect) {\n this.treeRoot.attr('aria-multiselectable', 'true');\n }\n\n this.items.attr('aria-selected', 'false');\n\n this.visibleItems = null;\n this.activeItem = null;\n this.lastActiveItem = null;\n\n this.keys = {\n tab: 9,\n enter: 13,\n space: 32,\n pageup: 33,\n pagedown: 34,\n end: 35,\n home: 36,\n left: 37,\n up: 38,\n right: 39,\n down: 40,\n eight: 56,\n asterisk: 106\n };\n\n this.init();\n\n this.bindEventHandlers();\n };\n // Public variables and functions.\n\n /**\n * Init this tree\n * @method init\n */\n Tree.prototype.init = function() {\n this.parents.attr('aria-expanded', 'true');\n this.parents.prepend(expandedImage.clone());\n\n this.items.attr('role', 'tree-item');\n this.items.attr('tabindex', '-1');\n this.parents.attr('role', 'group');\n this.treeRoot.attr('role', 'tree');\n\n this.visibleItems = this.treeRoot.find('li');\n\n var thisObj = this;\n if (!this.expandAll) {\n this.parents.each(function() {\n thisObj.collapseGroup($(this));\n });\n this.expandGroup(this.parents.first());\n }\n };\n\n /**\n * Expand a collapsed group.\n *\n * @method expandGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.expandGroup = function(item) {\n // Find the first child ul node.\n var group = item.children('ul');\n\n // Expand the group.\n group.show().attr('aria-hidden', 'false');\n\n item.attr('aria-expanded', 'true');\n\n item.children('img').attr('src', expandedImage.attr('src'));\n\n // Update the list of visible items.\n this.visibleItems = this.treeRoot.find('li:visible');\n };\n\n /**\n * Collapse an expanded group.\n *\n * @method collapseGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.collapseGroup = function(item) {\n var group = item.children('ul');\n\n // Collapse the group.\n group.hide().attr('aria-hidden', 'true');\n\n item.attr('aria-expanded', 'false');\n\n item.children('img').attr('src', collapsedImage.attr('src'));\n\n // Update the list of visible items.\n this.visibleItems = this.treeRoot.find('li:visible');\n };\n\n /**\n * Expand or collapse a group.\n *\n * @method toggleGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.toggleGroup = function(item) {\n if (item.attr('aria-expanded') == 'true') {\n this.collapseGroup(item);\n } else {\n this.expandGroup(item);\n }\n };\n\n /**\n * Whenever the currently selected node has changed, trigger an event using this function.\n *\n * @method triggerChange\n */\n Tree.prototype.triggerChange = function() {\n var allSelected = this.items.filter('[aria-selected=true]');\n if (!this.multiSelect) {\n allSelected = allSelected.first();\n }\n this.treeRoot.trigger('selectionchanged', {selected: allSelected});\n };\n\n /**\n * Select all the items between the last focused item and this currently focused item.\n *\n * @method multiSelectItem\n * @param {Object} item is the jquery id of the newly selected item.\n */\n Tree.prototype.multiSelectItem = function(item) {\n if (!this.multiSelect) {\n this.items.attr('aria-selected', 'false');\n } else if (this.lastActiveItem !== null) {\n var lastIndex = this.visibleItems.index(this.lastActiveItem);\n var currentIndex = this.visibleItems.index(this.activeItem);\n var oneItem = null;\n\n while (lastIndex < currentIndex) {\n oneItem = $(this.visibleItems.get(lastIndex));\n oneItem.attr('aria-selected', 'true');\n lastIndex++;\n }\n while (lastIndex > currentIndex) {\n oneItem = $(this.visibleItems.get(lastIndex));\n oneItem.attr('aria-selected', 'true');\n lastIndex--;\n }\n }\n\n item.attr('aria-selected', 'true');\n this.triggerChange();\n };\n\n /**\n * Select a single item. Make sure all the parents are expanded. De-select all other items.\n *\n * @method selectItem\n * @param {Object} item is the jquery id of the newly selected item.\n */\n Tree.prototype.selectItem = function(item) {\n // Expand all nodes up the tree.\n var walk = item.parent();\n while (walk.attr('role') != 'tree') {\n walk = walk.parent();\n if (walk.attr('aria-expanded') == 'false') {\n this.expandGroup(walk);\n }\n walk = walk.parent();\n }\n this.items.attr('aria-selected', 'false');\n item.attr('aria-selected', 'true');\n this.triggerChange();\n };\n\n /**\n * Toggle the selected state for an item back and forth.\n *\n * @method toggleItem\n * @param {Object} item is the jquery id of the item to toggle.\n */\n Tree.prototype.toggleItem = function(item) {\n if (!this.multiSelect) {\n this.selectItem(item);\n return;\n }\n\n var current = item.attr('aria-selected');\n if (current === 'true') {\n current = 'false';\n } else {\n current = 'true';\n }\n item.attr('aria-selected', current);\n this.triggerChange();\n };\n\n /**\n * Set the focus to this item.\n *\n * @method updateFocus\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.updateFocus = function(item) {\n this.lastActiveItem = this.activeItem;\n this.activeItem = item;\n // Expand all nodes up the tree.\n var walk = item.parent();\n while (walk.attr('role') != 'tree') {\n walk = walk.parent();\n if (walk.attr('aria-expanded') == 'false') {\n this.expandGroup(walk);\n }\n walk = walk.parent();\n }\n this.items.attr('tabindex', '-1');\n item.attr('tabindex', 0);\n };\n\n /**\n * Handle a key down event - ie navigate the tree.\n *\n * @method handleKeyDown\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n // This function should be simplified. In the meantime..\n // eslint-disable-next-line complexity\n Tree.prototype.handleKeyDown = function(item, e) {\n var currentIndex = this.visibleItems.index(item);\n var newItem = null;\n var hasKeyModifier = e.shiftKey || e.ctrlKey || e.metaKey || e.altKey;\n var thisObj = this;\n\n switch (e.keyCode) {\n case this.keys.home: {\n // Jump to first item in tree.\n newItem = this.parents.first();\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.end: {\n // Jump to last visible item.\n newItem = this.visibleItems.last();\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.enter:\n case this.keys.space: {\n\n if (e.shiftKey) {\n this.multiSelectItem(item);\n } else if (e.metaKey || e.ctrlKey) {\n this.toggleItem(item);\n } else {\n this.selectItem(item);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.left: {\n if (item.has('ul') && item.attr('aria-expanded') == 'true') {\n this.collapseGroup(item);\n } else {\n // Move up to the parent.\n var itemUL = item.parent();\n var itemParent = itemUL.parent();\n if (itemParent.is('li')) {\n itemParent.focus();\n if (e.shiftKey) {\n this.multiSelectItem(itemParent);\n } else if (!hasKeyModifier) {\n this.selectItem(itemParent);\n }\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.right: {\n if (item.has('ul') && item.attr('aria-expanded') == 'false') {\n this.expandGroup(item);\n } else {\n // Move to the first item in the child group.\n newItem = item.children('ul').children('li').first();\n if (newItem.length > 0) {\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.up: {\n\n if (currentIndex > 0) {\n var prev = this.visibleItems.eq(currentIndex - 1);\n prev.focus();\n if (e.shiftKey) {\n this.multiSelectItem(prev);\n } else if (!hasKeyModifier) {\n this.selectItem(prev);\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.down: {\n\n if (currentIndex < this.visibleItems.length - 1) {\n var next = this.visibleItems.eq(currentIndex + 1);\n next.focus();\n if (e.shiftKey) {\n this.multiSelectItem(next);\n } else if (!hasKeyModifier) {\n this.selectItem(next);\n }\n }\n e.stopPropagation();\n return false;\n }\n case this.keys.asterisk: {\n // Expand all groups.\n this.parents.each(function() {\n thisObj.expandGroup($(this));\n });\n\n e.stopPropagation();\n return false;\n }\n case this.keys.eight: {\n if (e.shiftKey) {\n // Expand all groups.\n this.parents.each(function() {\n thisObj.expandGroup($(this));\n });\n\n e.stopPropagation();\n }\n\n return false;\n }\n }\n\n return true;\n };\n\n /**\n * Handle a key press event - ie navigate the tree.\n *\n * @method handleKeyPress\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleKeyPress = function(item, e) {\n if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {\n // Do nothing.\n return true;\n }\n\n switch (e.keyCode) {\n case this.keys.tab: {\n return true;\n }\n case this.keys.enter:\n case this.keys.home:\n case this.keys.end:\n case this.keys.left:\n case this.keys.right:\n case this.keys.up:\n case this.keys.down: {\n e.stopPropagation();\n return false;\n }\n default : {\n var chr = String.fromCharCode(e.which);\n var match = false;\n var itemIndex = this.visibleItems.index(item);\n var itemCount = this.visibleItems.length;\n var currentIndex = itemIndex + 1;\n\n // Check if the active item was the last one on the list.\n if (currentIndex == itemCount) {\n currentIndex = 0;\n }\n\n // Iterate through the menu items (starting from the current item and wrapping) until a match is found\n // or the loop returns to the current menu item.\n while (currentIndex != itemIndex) {\n\n var currentItem = this.visibleItems.eq(currentIndex);\n var titleChr = currentItem.text().charAt(0);\n\n if (currentItem.has('ul')) {\n titleChr = currentItem.find('span').text().charAt(0);\n }\n\n if (titleChr.toLowerCase() == chr) {\n match = true;\n break;\n }\n\n currentIndex = currentIndex + 1;\n if (currentIndex == itemCount) {\n // Reached the end of the list, start again at the beginning.\n currentIndex = 0;\n }\n }\n\n if (match === true) {\n this.updateFocus(this.visibleItems.eq(currentIndex));\n }\n e.stopPropagation();\n return false;\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return true;\n };\n\n /**\n * Attach an event listener to the tree.\n *\n * @method on\n * @param {String} eventname This is the name of the event to listen for. Only 'selectionchanged' is supported for now.\n * @param {Function} handler The function to call when the event is triggered.\n */\n Tree.prototype.on = function(eventname, handler) {\n if (eventname !== 'selectionchanged') {\n log.warning('Invalid custom event name for tree. Only \"selectionchanged\" is supported.');\n } else {\n this.treeRoot.on(eventname, handler);\n }\n };\n\n /**\n * Handle a double click (expand/collapse).\n *\n * @method handleDblClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleDblClick = function(item, e) {\n\n if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {\n // Do nothing.\n return true;\n }\n\n // Apply the focus markup.\n this.updateFocus(item);\n\n // Expand or collapse the group.\n this.toggleGroup(item);\n\n e.stopPropagation();\n return false;\n };\n\n /**\n * Handle a click (select).\n *\n * @method handleExpandCollapseClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleExpandCollapseClick = function(item, e) {\n\n // Do not shift the focus.\n this.toggleGroup(item);\n e.stopPropagation();\n return false;\n };\n\n\n /**\n * Handle a click (select).\n *\n * @method handleClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleClick = function(item, e) {\n\n if (e.shiftKey) {\n this.multiSelectItem(item);\n } else if (e.metaKey || e.ctrlKey) {\n this.toggleItem(item);\n } else {\n this.selectItem(item);\n }\n this.updateFocus(item);\n e.stopPropagation();\n return false;\n };\n\n /**\n * Handle a blur event\n *\n * @method handleBlur\n * @param {Object} item item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleBlur = function() {\n return true;\n };\n\n /**\n * Handle a focus event\n *\n * @method handleFocus\n * @param {Object} item item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleFocus = function(item) {\n\n this.updateFocus(item);\n\n return true;\n };\n\n /**\n * Bind the event listeners we require.\n *\n * @method bindEventHandlers\n */\n Tree.prototype.bindEventHandlers = function() {\n var thisObj = this;\n\n // Bind a dblclick handler to the parent items.\n this.parents.dblclick(function(e) {\n return thisObj.handleDblClick($(this), e);\n });\n\n // Bind a click handler.\n this.items.click(function(e) {\n return thisObj.handleClick($(this), e);\n });\n\n // Bind a toggle handler to the expand/collapse icons.\n this.items.children('img').click(function(e) {\n return thisObj.handleExpandCollapseClick($(this).parent(), e);\n });\n\n // Bind a keydown handler.\n this.items.keydown(function(e) {\n return thisObj.handleKeyDown($(this), e);\n });\n\n // Bind a keypress handler.\n this.items.keypress(function(e) {\n return thisObj.handleKeyPress($(this), e);\n });\n\n // Bind a focus handler.\n this.items.focus(function(e) {\n return thisObj.handleFocus($(this), e);\n });\n\n // Bind a blur handler.\n this.items.blur(function(e) {\n return thisObj.handleBlur($(this), e);\n });\n\n };\n\n return /** @alias module:tool_lp/tree */ Tree;\n});\n"],"file":"tree.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/tree.js"],"names":["define","$","url","log","expandedImage","imageUrl","collapsedImage","Tree","selector","multiSelect","treeRoot","items","find","expandAll","length","parents","attr","visibleItems","activeItem","lastActiveItem","keys","tab","enter","space","pageup","pagedown","end","home","left","up","right","down","eight","asterisk","init","bindEventHandlers","prototype","prepend","clone","thisObj","each","collapseGroup","expandGroup","first","item","group","children","show","hide","toggleGroup","triggerChange","allSelected","filter","trigger","selected","multiSelectItem","lastIndex","index","currentIndex","oneItem","get","selectItem","walk","parent","toggleItem","current","updateFocus","handleKeyDown","e","newItem","hasKeyModifier","shiftKey","ctrlKey","metaKey","altKey","keyCode","focus","stopPropagation","last","has","itemUL","itemParent","is","prev","eq","next","handleKeyPress","chr","String","fromCharCode","which","match","itemIndex","itemCount","currentItem","titleChr","text","charAt","toLowerCase","on","eventname","handler","warning","handleDblClick","handleExpandCollapseClick","handleClick","handleBlur","handleFocus","dblclick","click","keydown","keypress","blur"],"mappings":"AA2BAA,OAAM,gBAAC,CAAC,QAAD,CAAW,UAAX,CAAuB,UAAvB,CAAD,CAAqC,SAASC,CAAT,CAAYC,CAAZ,CAAiBC,CAAjB,CAAsB,IAGzDC,CAAAA,CAAa,CAAGH,CAAC,CAAC,uBAAsBC,CAAG,CAACG,QAAJ,CAAa,YAAb,CAAtB,CAAmD,MAApD,CAHwC,CAKzDC,CAAc,CAAGL,CAAC,CAAC,uBAAsBC,CAAG,CAACG,QAAJ,CAAa,aAAb,CAAtB,CAAoD,MAArD,CALuC,CAazDE,CAAI,CAAG,SAASC,CAAT,CAAmBC,CAAnB,CAAgC,CACvC,KAAKC,QAAL,CAAgBT,CAAC,CAACO,CAAD,CAAjB,CACA,KAAKC,WAAL,CAA2C,WAAvB,QAAOA,CAAAA,CAAP,EAAsC,KAAAA,CAA1D,CAEA,KAAKE,KAAL,CAAa,KAAKD,QAAL,CAAcE,IAAd,CAAmB,IAAnB,CAAb,CACA,KAAKC,SAAL,CAAqC,EAApB,MAAKF,KAAL,CAAWG,MAA5B,CACA,KAAKC,OAAL,CAAe,KAAKL,QAAL,CAAcE,IAAd,CAAmB,YAAnB,CAAf,CAEA,GAAIH,CAAJ,CAAiB,CACb,KAAKC,QAAL,CAAcM,IAAd,CA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AT,CAAY,CACxB,MAAO7B,CAAAA,CAAO,CAACmE,UAAR,CAAmBzG,CAAC,CAAC,IAAD,CAApB,CAA4BmE,CAA5B,CACV,CAFD,CAIH,CAtCD,CAwCA,MAAyC7D,CAAAA,CAC5C,CAvmBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Implement an accessible aria tree widget, from a nested unordered list.\n * Based on http://oaa-accessibility.org/example/41/\n *\n * To respond to selection changed events - use tree.on(\"selectionchanged\", handler).\n * The handler will receive an array of nodes, which are the list items that are currently\n * selected. (Or a single node if multiselect is disabled).\n *\n * @module tool_lp/tree\n * @copyright 2015 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/url', 'core/log'], function($, url, log) {\n // Private variables and functions.\n /** @var {String} expandedImage The html for an expanded tree node twistie. */\n var expandedImage = $('\"\"');\n /** @var {String} collapsedImage The html for a collapsed tree node twistie. */\n var collapsedImage = $('\"\"');\n\n /**\n * Constructor\n *\n * @param {String} selector\n * @param {Boolean} multiSelect\n */\n var Tree = function(selector, multiSelect) {\n this.treeRoot = $(selector);\n this.multiSelect = (typeof multiSelect === 'undefined' || multiSelect === true);\n\n this.items = this.treeRoot.find('li');\n this.expandAll = this.items.length < 20;\n this.parents = this.treeRoot.find('li:has(ul)');\n\n if (multiSelect) {\n this.treeRoot.attr('aria-multiselectable', 'true');\n }\n\n this.items.attr('aria-selected', 'false');\n\n this.visibleItems = null;\n this.activeItem = null;\n this.lastActiveItem = null;\n\n this.keys = {\n tab: 9,\n enter: 13,\n space: 32,\n pageup: 33,\n pagedown: 34,\n end: 35,\n home: 36,\n left: 37,\n up: 38,\n right: 39,\n down: 40,\n eight: 56,\n asterisk: 106\n };\n\n this.init();\n\n this.bindEventHandlers();\n };\n // Public variables and functions.\n\n /**\n * Init this tree\n * @method init\n */\n Tree.prototype.init = function() {\n this.parents.attr('aria-expanded', 'true');\n this.parents.prepend(expandedImage.clone());\n\n this.items.attr('role', 'tree-item');\n this.items.attr('tabindex', '-1');\n this.parents.attr('role', 'group');\n this.treeRoot.attr('role', 'tree');\n\n this.visibleItems = this.treeRoot.find('li');\n\n var thisObj = this;\n if (!this.expandAll) {\n this.parents.each(function() {\n thisObj.collapseGroup($(this));\n });\n this.expandGroup(this.parents.first());\n }\n };\n\n /**\n * Expand a collapsed group.\n *\n * @method expandGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.expandGroup = function(item) {\n // Find the first child ul node.\n var group = item.children('ul');\n\n // Expand the group.\n group.show().attr('aria-hidden', 'false');\n\n item.attr('aria-expanded', 'true');\n\n item.children('img').attr('src', expandedImage.attr('src'));\n\n // Update the list of visible items.\n this.visibleItems = this.treeRoot.find('li:visible');\n };\n\n /**\n * Collapse an expanded group.\n *\n * @method collapseGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.collapseGroup = function(item) {\n var group = item.children('ul');\n\n // Collapse the group.\n group.hide().attr('aria-hidden', 'true');\n\n item.attr('aria-expanded', 'false');\n\n item.children('img').attr('src', collapsedImage.attr('src'));\n\n // Update the list of visible items.\n this.visibleItems = this.treeRoot.find('li:visible');\n };\n\n /**\n * Expand or collapse a group.\n *\n * @method toggleGroup\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.toggleGroup = function(item) {\n if (item.attr('aria-expanded') == 'true') {\n this.collapseGroup(item);\n } else {\n this.expandGroup(item);\n }\n };\n\n /**\n * Whenever the currently selected node has changed, trigger an event using this function.\n *\n * @method triggerChange\n */\n Tree.prototype.triggerChange = function() {\n var allSelected = this.items.filter('[aria-selected=true]');\n if (!this.multiSelect) {\n allSelected = allSelected.first();\n }\n this.treeRoot.trigger('selectionchanged', {selected: allSelected});\n };\n\n /**\n * Select all the items between the last focused item and this currently focused item.\n *\n * @method multiSelectItem\n * @param {Object} item is the jquery id of the newly selected item.\n */\n Tree.prototype.multiSelectItem = function(item) {\n if (!this.multiSelect) {\n this.items.attr('aria-selected', 'false');\n } else if (this.lastActiveItem !== null) {\n var lastIndex = this.visibleItems.index(this.lastActiveItem);\n var currentIndex = this.visibleItems.index(this.activeItem);\n var oneItem = null;\n\n while (lastIndex < currentIndex) {\n oneItem = $(this.visibleItems.get(lastIndex));\n oneItem.attr('aria-selected', 'true');\n lastIndex++;\n }\n while (lastIndex > currentIndex) {\n oneItem = $(this.visibleItems.get(lastIndex));\n oneItem.attr('aria-selected', 'true');\n lastIndex--;\n }\n }\n\n item.attr('aria-selected', 'true');\n this.triggerChange();\n };\n\n /**\n * Select a single item. Make sure all the parents are expanded. De-select all other items.\n *\n * @method selectItem\n * @param {Object} item is the jquery id of the newly selected item.\n */\n Tree.prototype.selectItem = function(item) {\n // Expand all nodes up the tree.\n var walk = item.parent();\n while (walk.attr('role') != 'tree') {\n walk = walk.parent();\n if (walk.attr('aria-expanded') == 'false') {\n this.expandGroup(walk);\n }\n walk = walk.parent();\n }\n this.items.attr('aria-selected', 'false');\n item.attr('aria-selected', 'true');\n this.triggerChange();\n };\n\n /**\n * Toggle the selected state for an item back and forth.\n *\n * @method toggleItem\n * @param {Object} item is the jquery id of the item to toggle.\n */\n Tree.prototype.toggleItem = function(item) {\n if (!this.multiSelect) {\n this.selectItem(item);\n return;\n }\n\n var current = item.attr('aria-selected');\n if (current === 'true') {\n current = 'false';\n } else {\n current = 'true';\n }\n item.attr('aria-selected', current);\n this.triggerChange();\n };\n\n /**\n * Set the focus to this item.\n *\n * @method updateFocus\n * @param {Object} item is the jquery id of the parent item of the group\n */\n Tree.prototype.updateFocus = function(item) {\n this.lastActiveItem = this.activeItem;\n this.activeItem = item;\n // Expand all nodes up the tree.\n var walk = item.parent();\n while (walk.attr('role') != 'tree') {\n walk = walk.parent();\n if (walk.attr('aria-expanded') == 'false') {\n this.expandGroup(walk);\n }\n walk = walk.parent();\n }\n this.items.attr('tabindex', '-1');\n item.attr('tabindex', 0);\n };\n\n /**\n * Handle a key down event - ie navigate the tree.\n *\n * @method handleKeyDown\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n // This function should be simplified. In the meantime..\n // eslint-disable-next-line complexity\n Tree.prototype.handleKeyDown = function(item, e) {\n var currentIndex = this.visibleItems.index(item);\n var newItem = null;\n var hasKeyModifier = e.shiftKey || e.ctrlKey || e.metaKey || e.altKey;\n var thisObj = this;\n\n switch (e.keyCode) {\n case this.keys.home: {\n // Jump to first item in tree.\n newItem = this.parents.first();\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.end: {\n // Jump to last visible item.\n newItem = this.visibleItems.last();\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.enter:\n case this.keys.space: {\n\n if (e.shiftKey) {\n this.multiSelectItem(item);\n } else if (e.metaKey || e.ctrlKey) {\n this.toggleItem(item);\n } else {\n this.selectItem(item);\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.left: {\n if (item.has('ul') && item.attr('aria-expanded') == 'true') {\n this.collapseGroup(item);\n } else {\n // Move up to the parent.\n var itemUL = item.parent();\n var itemParent = itemUL.parent();\n if (itemParent.is('li')) {\n itemParent.focus();\n if (e.shiftKey) {\n this.multiSelectItem(itemParent);\n } else if (!hasKeyModifier) {\n this.selectItem(itemParent);\n }\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.right: {\n if (item.has('ul') && item.attr('aria-expanded') == 'false') {\n this.expandGroup(item);\n } else {\n // Move to the first item in the child group.\n newItem = item.children('ul').children('li').first();\n if (newItem.length > 0) {\n newItem.focus();\n if (e.shiftKey) {\n this.multiSelectItem(newItem);\n } else if (!hasKeyModifier) {\n this.selectItem(newItem);\n }\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.up: {\n\n if (currentIndex > 0) {\n var prev = this.visibleItems.eq(currentIndex - 1);\n prev.focus();\n if (e.shiftKey) {\n this.multiSelectItem(prev);\n } else if (!hasKeyModifier) {\n this.selectItem(prev);\n }\n }\n\n e.stopPropagation();\n return false;\n }\n case this.keys.down: {\n\n if (currentIndex < this.visibleItems.length - 1) {\n var next = this.visibleItems.eq(currentIndex + 1);\n next.focus();\n if (e.shiftKey) {\n this.multiSelectItem(next);\n } else if (!hasKeyModifier) {\n this.selectItem(next);\n }\n }\n e.stopPropagation();\n return false;\n }\n case this.keys.asterisk: {\n // Expand all groups.\n this.parents.each(function() {\n thisObj.expandGroup($(this));\n });\n\n e.stopPropagation();\n return false;\n }\n case this.keys.eight: {\n if (e.shiftKey) {\n // Expand all groups.\n this.parents.each(function() {\n thisObj.expandGroup($(this));\n });\n\n e.stopPropagation();\n }\n\n return false;\n }\n }\n\n return true;\n };\n\n /**\n * Handle a key press event - ie navigate the tree.\n *\n * @method handleKeyPress\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleKeyPress = function(item, e) {\n if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {\n // Do nothing.\n return true;\n }\n\n switch (e.keyCode) {\n case this.keys.tab: {\n return true;\n }\n case this.keys.enter:\n case this.keys.home:\n case this.keys.end:\n case this.keys.left:\n case this.keys.right:\n case this.keys.up:\n case this.keys.down: {\n e.stopPropagation();\n return false;\n }\n default : {\n var chr = String.fromCharCode(e.which);\n var match = false;\n var itemIndex = this.visibleItems.index(item);\n var itemCount = this.visibleItems.length;\n var currentIndex = itemIndex + 1;\n\n // Check if the active item was the last one on the list.\n if (currentIndex == itemCount) {\n currentIndex = 0;\n }\n\n // Iterate through the menu items (starting from the current item and wrapping) until a match is found\n // or the loop returns to the current menu item.\n while (currentIndex != itemIndex) {\n\n var currentItem = this.visibleItems.eq(currentIndex);\n var titleChr = currentItem.text().charAt(0);\n\n if (currentItem.has('ul')) {\n titleChr = currentItem.find('span').text().charAt(0);\n }\n\n if (titleChr.toLowerCase() == chr) {\n match = true;\n break;\n }\n\n currentIndex = currentIndex + 1;\n if (currentIndex == itemCount) {\n // Reached the end of the list, start again at the beginning.\n currentIndex = 0;\n }\n }\n\n if (match === true) {\n this.updateFocus(this.visibleItems.eq(currentIndex));\n }\n e.stopPropagation();\n return false;\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return true;\n };\n\n /**\n * Attach an event listener to the tree.\n *\n * @method on\n * @param {String} eventname This is the name of the event to listen for. Only 'selectionchanged' is supported for now.\n * @param {Function} handler The function to call when the event is triggered.\n */\n Tree.prototype.on = function(eventname, handler) {\n if (eventname !== 'selectionchanged') {\n log.warning('Invalid custom event name for tree. Only \"selectionchanged\" is supported.');\n } else {\n this.treeRoot.on(eventname, handler);\n }\n };\n\n /**\n * Handle a double click (expand/collapse).\n *\n * @method handleDblClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleDblClick = function(item, e) {\n\n if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {\n // Do nothing.\n return true;\n }\n\n // Apply the focus markup.\n this.updateFocus(item);\n\n // Expand or collapse the group.\n this.toggleGroup(item);\n\n e.stopPropagation();\n return false;\n };\n\n /**\n * Handle a click (select).\n *\n * @method handleExpandCollapseClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleExpandCollapseClick = function(item, e) {\n\n // Do not shift the focus.\n this.toggleGroup(item);\n e.stopPropagation();\n return false;\n };\n\n\n /**\n * Handle a click (select).\n *\n * @method handleClick\n * @param {Object} item is the jquery id of the parent item of the group\n * @param {Event} e The event.\n * @return {Boolean}\n */\n Tree.prototype.handleClick = function(item, e) {\n\n if (e.shiftKey) {\n this.multiSelectItem(item);\n } else if (e.metaKey || e.ctrlKey) {\n this.toggleItem(item);\n } else {\n this.selectItem(item);\n }\n this.updateFocus(item);\n e.stopPropagation();\n return false;\n };\n\n /**\n * Handle a blur event\n *\n * @method handleBlur\n * @return {Boolean}\n */\n Tree.prototype.handleBlur = function() {\n return true;\n };\n\n /**\n * Handle a focus event\n *\n * @method handleFocus\n * @param {Object} item item is the jquery id of the parent item of the group\n * @return {Boolean}\n */\n Tree.prototype.handleFocus = function(item) {\n\n this.updateFocus(item);\n\n return true;\n };\n\n /**\n * Bind the event listeners we require.\n *\n * @method bindEventHandlers\n */\n Tree.prototype.bindEventHandlers = function() {\n var thisObj = this;\n\n // Bind a dblclick handler to the parent items.\n this.parents.dblclick(function(e) {\n return thisObj.handleDblClick($(this), e);\n });\n\n // Bind a click handler.\n this.items.click(function(e) {\n return thisObj.handleClick($(this), e);\n });\n\n // Bind a toggle handler to the expand/collapse icons.\n this.items.children('img').click(function(e) {\n return thisObj.handleExpandCollapseClick($(this).parent(), e);\n });\n\n // Bind a keydown handler.\n this.items.keydown(function(e) {\n return thisObj.handleKeyDown($(this), e);\n });\n\n // Bind a keypress handler.\n this.items.keypress(function(e) {\n return thisObj.handleKeyPress($(this), e);\n });\n\n // Bind a focus handler.\n this.items.focus(function(e) {\n return thisObj.handleFocus($(this), e);\n });\n\n // Bind a blur handler.\n this.items.blur(function(e) {\n return thisObj.handleBlur($(this), e);\n });\n\n };\n\n return /** @alias module:tool_lp/tree */ Tree;\n});\n"],"file":"tree.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/user_competency_workflow.min.js.map b/admin/tool/lp/amd/build/user_competency_workflow.min.js.map index 52dfc5dc575b1..f843d5ce9e68b 100644 --- a/admin/tool/lp/amd/build/user_competency_workflow.min.js.map +++ b/admin/tool/lp/amd/build/user_competency_workflow.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/user_competency_workflow.js"],"names":["define","$","Templates","Ajax","Notification","Str","Menubar","EventBase","UserCompetencyWorkflow","prototype","constructor","apply","Object","create","_nodeSelector","_cancelReviewRequest","data","call","methodname","args","userid","competencyid","then","_trigger","bind","catch","cancelReviewRequest","_cancelReviewRequestHandler","e","preventDefault","_findUserCompetencyData","target","_requestReview","requestReview","_requestReviewHandler","_startReview","startReview","_startReviewHandler","_stopReview","stopReview","_stopReviewHandler","enhanceMenubar","selector","enhance","node","parent","parents","length","Error","registerEvents","wrapper","find","click"],"mappings":"AAsBAA,OAAM,oCAAC,CAAC,QAAD,CACC,gBADD,CAEC,WAFD,CAGC,mBAHD,CAIC,UAJD,CAKC,iBALD,CAMC,oBAND,CAAD,CAOE,SAASC,CAAT,CAAYC,CAAZ,CAAuBC,CAAvB,CAA6BC,CAA7B,CAA2CC,CAA3C,CAAgDC,CAAhD,CAAyDC,CAAzD,CAAoE,CAOxE,GAAIC,CAAAA,CAAsB,CAAG,UAAW,CACpCD,CAAS,CAACE,SAAV,CAAoBC,WAApB,CAAgCC,KAAhC,CAAsC,IAAtC,CAA4C,EAA5C,CACH,CAFD,CAGAH,CAAsB,CAACC,SAAvB,CAAmCG,MAAM,CAACC,MAAP,CAAcN,CAAS,CAACE,SAAxB,CAAnC,CAGAD,CAAsB,CAACC,SAAvB,CAAiCK,aAAjC,CAAiD,iCAAjD,CAQAN,CAAsB,CAACC,SAAvB,CAAiCM,oBAAjC,CAAwD,SAASC,CAAT,CAAe,CACnE,GAAIC,CAAAA,CAAI,CAAG,CACPC,UAAU,CAAE,uDADL,CAEPC,IAAI,CAAE,CACFC,MAAM,CAAEJ,CAAI,CAACI,MADX,CAEFC,YAAY,CAAEL,CAAI,CAACK,YAFjB,CAFC,CAA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,cAAjC,CAAkD,SAASP,CAAT,CAAmB,CACjE,GAAIQ,CAAAA,CAAO,CAAGjD,CAAC,CAACyC,CAAD,CAAf,CAEAQ,CAAO,CAACC,IAAR,CAAa,kCAAb,EAA+CC,KAA/C,CAAqD,KAAKlB,qBAAL,CAA2BV,IAA3B,CAAgC,IAAhC,CAArD,EACA0B,CAAO,CAACC,IAAR,CAAa,yCAAb,EAAsDC,KAAtD,CAA4D,KAAKzB,2BAAL,CAAiCH,IAAjC,CAAsC,IAAtC,CAA5D,EACA0B,CAAO,CAACC,IAAR,CAAa,gCAAb,EAA6CC,KAA7C,CAAmD,KAAKf,mBAAL,CAAyBb,IAAzB,CAA8B,IAA9B,CAAnD,EACA0B,CAAO,CAACC,IAAR,CAAa,+BAAb,EAA4CC,KAA5C,CAAkD,KAAKZ,kBAAL,CAAwBhB,IAAxB,CAA6B,IAA7B,CAAlD,CACH,CAPD,CASA,MAA4DhB,CAAAA,CAC/D,CAxQK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * User competency workflow.\n *\n * @module tool_lp/user_competency_workflow\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',\n 'core/templates',\n 'core/ajax',\n 'core/notification',\n 'core/str',\n 'tool_lp/menubar',\n 'tool_lp/event_base'],\n function($, Templates, Ajax, Notification, Str, Menubar, EventBase) {\n\n /**\n * UserCompetencyWorkflow class.\n *\n * @param {String} selector The node containing the buttons to switch mode.\n */\n var UserCompetencyWorkflow = function() {\n EventBase.prototype.constructor.apply(this, []);\n };\n UserCompetencyWorkflow.prototype = Object.create(EventBase.prototype);\n\n /** @property {String} The selector to find the user competency data. */\n UserCompetencyWorkflow.prototype._nodeSelector = '[data-node=\"user-competency\"]';\n\n /**\n * Cancel a review request and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _cancelReviewRequest\n */\n UserCompetencyWorkflow.prototype._cancelReviewRequest = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_cancel_review_request',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-request-cancelled', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Cancel a review request an refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method cancelReviewRequest\n */\n UserCompetencyWorkflow.prototype.cancelReviewRequest = function(data) {\n this._cancelReviewRequest(data);\n };\n\n /**\n * Cancel a review request handler.\n *\n * @param {Event} e The event.\n * @method _cancelReviewRequestHandler\n */\n UserCompetencyWorkflow.prototype._cancelReviewRequestHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.cancelReviewRequest(data);\n };\n\n /**\n * Request a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _requestReview\n */\n UserCompetencyWorkflow.prototype._requestReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_request_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-requested', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Request a review.\n *\n * @param {Object} data The user competency data.\n * @method requestReview\n */\n UserCompetencyWorkflow.prototype.requestReview = function(data) {\n this._requestReview(data);\n };\n\n /**\n * Request a review handler.\n *\n * @param {Event} e The event.\n * @method _requestReviewHandler\n */\n UserCompetencyWorkflow.prototype._requestReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.requestReview(data);\n };\n\n /**\n * Start a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _startReview\n */\n UserCompetencyWorkflow.prototype._startReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_start_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n Ajax.call([call])[0].then(function() {\n this._trigger('review-started', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Start a review.\n *\n * @param {Object} data The user competency data.\n * @method startReview\n */\n UserCompetencyWorkflow.prototype.startReview = function(data) {\n this._startReview(data);\n };\n\n /**\n * Start a review handler.\n *\n * @param {Event} e The event.\n * @method _startReviewHandler\n */\n UserCompetencyWorkflow.prototype._startReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.startReview(data);\n };\n\n /**\n * Stop a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _stopReview\n */\n UserCompetencyWorkflow.prototype._stopReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_stop_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-stopped', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Stop a review.\n *\n * @param {Object} data The user competency data.\n * @method stopReview\n */\n UserCompetencyWorkflow.prototype.stopReview = function(data) {\n this._stopReview(data);\n };\n\n /**\n * Stop a review handler.\n *\n * @param {Event} e The event.\n * @method _stopReviewHandler\n */\n UserCompetencyWorkflow.prototype._stopReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.stopReview(data);\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserCompetencyWorkflow.prototype.enhanceMenubar = function(selector) {\n Menubar.enhance(selector, {\n '[data-action=\"request-review\"]': this._requestReviewHandler.bind(this),\n '[data-action=\"cancel-review-request\"]': this._cancelReviewRequestHandler.bind(this),\n });\n };\n\n /**\n * Find the user competency data from a node.\n *\n * @param {Node} node The node to search from.\n * @return {Object} User competency data.\n */\n UserCompetencyWorkflow.prototype._findUserCompetencyData = function(node) {\n var parent = node.parents(this._nodeSelector),\n data;\n\n if (parent.length != 1) {\n throw new Error('The evidence node was not located.');\n }\n\n data = parent.data();\n if (typeof data === 'undefined' || typeof data.userid === 'undefined' || typeof data.competencyid === 'undefined') {\n throw new Error('User competency data could not be found.');\n }\n\n return data;\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserCompetencyWorkflow.prototype.enhanceMenubar = function(selector) {\n Menubar.enhance(selector, {\n '[data-action=\"request-review\"]': this._requestReviewHandler.bind(this),\n '[data-action=\"cancel-review-request\"]': this._cancelReviewRequestHandler.bind(this),\n '[data-action=\"start-review\"]': this._startReviewHandler.bind(this),\n '[data-action=\"stop-review\"]': this._stopReviewHandler.bind(this),\n });\n };\n\n /**\n * Register the events in the region.\n *\n * @param {String} selector The base selector to search nodes in and attach events.\n */\n UserCompetencyWorkflow.prototype.registerEvents = function(selector) {\n var wrapper = $(selector);\n\n wrapper.find('[data-action=\"request-review\"]').click(this._requestReviewHandler.bind(this));\n wrapper.find('[data-action=\"cancel-review-request\"]').click(this._cancelReviewRequestHandler.bind(this));\n wrapper.find('[data-action=\"start-review\"]').click(this._startReviewHandler.bind(this));\n wrapper.find('[data-action=\"stop-review\"]').click(this._stopReviewHandler.bind(this));\n };\n\n return /** @alias module:tool_lp/user_competency_actions */ UserCompetencyWorkflow;\n});\n"],"file":"user_competency_workflow.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/user_competency_workflow.js"],"names":["define","$","Templates","Ajax","Notification","Str","Menubar","EventBase","UserCompetencyWorkflow","prototype","constructor","apply","Object","create","_nodeSelector","_cancelReviewRequest","data","call","methodname","args","userid","competencyid","then","_trigger","bind","catch","cancelReviewRequest","_cancelReviewRequestHandler","e","preventDefault","_findUserCompetencyData","target","_requestReview","requestReview","_requestReviewHandler","_startReview","startReview","_startReviewHandler","_stopReview","stopReview","_stopReviewHandler","enhanceMenubar","selector","enhance","node","parent","parents","length","Error","registerEvents","wrapper","find","click"],"mappings":"AAsBAA,OAAM,oCAAC,CAAC,QAAD,CACC,gBADD,CAEC,WAFD,CAGC,mBAHD,CAIC,UAJD,CAKC,iBALD,CAMC,oBAND,CAAD,CAOE,SAASC,CAAT,CAAYC,CAAZ,CAAuBC,CAAvB,CAA6BC,CAA7B,CAA2CC,CAA3C,CAAgDC,CAAhD,CAAyDC,CAAzD,CAAoE,CAKxE,GAAIC,CAAAA,CAAsB,CAAG,UAAW,CACpCD,CAAS,CAACE,SAAV,CAAoBC,WAApB,CAAgCC,KAAhC,CAAsC,IAAtC,CAA4C,EAA5C,CACH,CAFD,CAGAH,CAAsB,CAACC,SAAvB,CAAmCG,MAAM,CAACC,MAAP,CAAcN,CAAS,CAACE,SAAxB,CAAnC,CAGAD,CAAsB,CAACC,SAAvB,CAAiCK,aAAjC,CAAiD,iCAAjD,CAQAN,CAAsB,CAACC,SAAvB,CAAiCM,oBAAjC,CAAwD,SAASC,CAAT,CAAe,CACnE,GAAIC,CAAAA,CAAI,CAAG,CACPC,UAAU,CAAE,uDADL,CAEPC,IAAI,CAAE,CACFC,MAAM,CAAEJ,CAAI,CAACI,MADX,CAEFC,YAAY,CAAEL,CAAI,CAACK,YAFjB,CAFC,CAAX,CAQAlB,CAAI,CAACc,IAAL,CAAU,CAACA,CAAD,CAAV,EAAkB,CAAlB,EAAqBK,IAArB,CAA0B,UAAW,CACjC,KAAKC,QAAL,CAAc,0BAAd,CAA0CP,CAA1C,EACA,KAAKO,QAAL,CAAc,gBAAd,CAAgCP,CAAhC,CACH,CAHyB,CAGxBQ,IAHwB,CA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O,CAACC,IAAR,CAAa,yCAAb,EAAsDC,KAAtD,CAA4D,KAAKzB,2BAAL,CAAiCH,IAAjC,CAAsC,IAAtC,CAA5D,EACA0B,CAAO,CAACC,IAAR,CAAa,gCAAb,EAA6CC,KAA7C,CAAmD,KAAKf,mBAAL,CAAyBb,IAAzB,CAA8B,IAA9B,CAAnD,EACA0B,CAAO,CAACC,IAAR,CAAa,+BAAb,EAA4CC,KAA5C,CAAkD,KAAKZ,kBAAL,CAAwBhB,IAAxB,CAA6B,IAA7B,CAAlD,CACH,CAPD,CASA,MAA4DhB,CAAAA,CAC/D,CAtQK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * User competency workflow.\n *\n * @module tool_lp/user_competency_workflow\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',\n 'core/templates',\n 'core/ajax',\n 'core/notification',\n 'core/str',\n 'tool_lp/menubar',\n 'tool_lp/event_base'],\n function($, Templates, Ajax, Notification, Str, Menubar, EventBase) {\n\n /**\n * UserCompetencyWorkflow class.\n */\n var UserCompetencyWorkflow = function() {\n EventBase.prototype.constructor.apply(this, []);\n };\n UserCompetencyWorkflow.prototype = Object.create(EventBase.prototype);\n\n /** @property {String} The selector to find the user competency data. */\n UserCompetencyWorkflow.prototype._nodeSelector = '[data-node=\"user-competency\"]';\n\n /**\n * Cancel a review request and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _cancelReviewRequest\n */\n UserCompetencyWorkflow.prototype._cancelReviewRequest = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_cancel_review_request',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-request-cancelled', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Cancel a review request an refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method cancelReviewRequest\n */\n UserCompetencyWorkflow.prototype.cancelReviewRequest = function(data) {\n this._cancelReviewRequest(data);\n };\n\n /**\n * Cancel a review request handler.\n *\n * @param {Event} e The event.\n * @method _cancelReviewRequestHandler\n */\n UserCompetencyWorkflow.prototype._cancelReviewRequestHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.cancelReviewRequest(data);\n };\n\n /**\n * Request a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _requestReview\n */\n UserCompetencyWorkflow.prototype._requestReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_request_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-requested', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Request a review.\n *\n * @param {Object} data The user competency data.\n * @method requestReview\n */\n UserCompetencyWorkflow.prototype.requestReview = function(data) {\n this._requestReview(data);\n };\n\n /**\n * Request a review handler.\n *\n * @param {Event} e The event.\n * @method _requestReviewHandler\n */\n UserCompetencyWorkflow.prototype._requestReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.requestReview(data);\n };\n\n /**\n * Start a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _startReview\n */\n UserCompetencyWorkflow.prototype._startReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_start_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n Ajax.call([call])[0].then(function() {\n this._trigger('review-started', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Start a review.\n *\n * @param {Object} data The user competency data.\n * @method startReview\n */\n UserCompetencyWorkflow.prototype.startReview = function(data) {\n this._startReview(data);\n };\n\n /**\n * Start a review handler.\n *\n * @param {Event} e The event.\n * @method _startReviewHandler\n */\n UserCompetencyWorkflow.prototype._startReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.startReview(data);\n };\n\n /**\n * Stop a review and refresh the view.\n *\n * @param {Object} data The user competency data.\n * @method _stopReview\n */\n UserCompetencyWorkflow.prototype._stopReview = function(data) {\n var call = {\n methodname: 'core_competency_user_competency_stop_review',\n args: {\n userid: data.userid,\n competencyid: data.competencyid\n }\n };\n\n Ajax.call([call])[0].then(function() {\n this._trigger('review-stopped', data);\n this._trigger('status-changed', data);\n }.bind(this)).catch(function() {\n this._trigger('error-occured', data);\n }.bind(this));\n };\n\n /**\n * Stop a review.\n *\n * @param {Object} data The user competency data.\n * @method stopReview\n */\n UserCompetencyWorkflow.prototype.stopReview = function(data) {\n this._stopReview(data);\n };\n\n /**\n * Stop a review handler.\n *\n * @param {Event} e The event.\n * @method _stopReviewHandler\n */\n UserCompetencyWorkflow.prototype._stopReviewHandler = function(e) {\n e.preventDefault();\n var data = this._findUserCompetencyData($(e.target));\n this.stopReview(data);\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserCompetencyWorkflow.prototype.enhanceMenubar = function(selector) {\n Menubar.enhance(selector, {\n '[data-action=\"request-review\"]': this._requestReviewHandler.bind(this),\n '[data-action=\"cancel-review-request\"]': this._cancelReviewRequestHandler.bind(this),\n });\n };\n\n /**\n * Find the user competency data from a node.\n *\n * @param {Node} node The node to search from.\n * @return {Object} User competency data.\n */\n UserCompetencyWorkflow.prototype._findUserCompetencyData = function(node) {\n var parent = node.parents(this._nodeSelector),\n data;\n\n if (parent.length != 1) {\n throw new Error('The evidence node was not located.');\n }\n\n data = parent.data();\n if (typeof data === 'undefined' || typeof data.userid === 'undefined' || typeof data.competencyid === 'undefined') {\n throw new Error('User competency data could not be found.');\n }\n\n return data;\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserCompetencyWorkflow.prototype.enhanceMenubar = function(selector) {\n Menubar.enhance(selector, {\n '[data-action=\"request-review\"]': this._requestReviewHandler.bind(this),\n '[data-action=\"cancel-review-request\"]': this._cancelReviewRequestHandler.bind(this),\n '[data-action=\"start-review\"]': this._startReviewHandler.bind(this),\n '[data-action=\"stop-review\"]': this._stopReviewHandler.bind(this),\n });\n };\n\n /**\n * Register the events in the region.\n *\n * @param {String} selector The base selector to search nodes in and attach events.\n */\n UserCompetencyWorkflow.prototype.registerEvents = function(selector) {\n var wrapper = $(selector);\n\n wrapper.find('[data-action=\"request-review\"]').click(this._requestReviewHandler.bind(this));\n wrapper.find('[data-action=\"cancel-review-request\"]').click(this._cancelReviewRequestHandler.bind(this));\n wrapper.find('[data-action=\"start-review\"]').click(this._startReviewHandler.bind(this));\n wrapper.find('[data-action=\"stop-review\"]').click(this._stopReviewHandler.bind(this));\n };\n\n return /** @alias module:tool_lp/user_competency_actions */ UserCompetencyWorkflow;\n});\n"],"file":"user_competency_workflow.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/build/user_evidence_actions.min.js.map b/admin/tool/lp/amd/build/user_evidence_actions.min.js.map index 7a2d437981cc3..e4ce2adbb683b 100644 --- a/admin/tool/lp/amd/build/user_evidence_actions.min.js.map +++ b/admin/tool/lp/amd/build/user_evidence_actions.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/user_evidence_actions.js"],"names":["define","$","templates","ajax","notification","str","Menubar","PickerUserPlans","UserEvidenceActions","type","_type","_region","_evidenceNode","_template","_contextMethod","TypeError","prototype","_getContextArgs","evidenceData","self","args","id","userid","_renderView","context","render","then","newhtml","newjs","replaceNode","_callAndRefresh","calls","push","methodname","when","apply","call","arguments","length","fail","exception","_doDelete","deleteEvidence","requests","done","evidence","get_strings","key","component","param","name","strings","confirm","_deleteEvidenceHandler","e","preventDefault","data","_findEvidenceData","target","_doCreateUserEvidenceCompetency","competencyIds","each","index","competencyId","userevidenceid","competencyid","createUserEvidenceCompetency","picker","on","requestReview","display","_createUserEvidenceCompetencyHandler","_doDeleteUserEvidenceCompetency","deleteUserEvidenceCompetency","_deleteUserEvidenceCompetencyHandler","currentTarget","_doReviewUserEvidenceCompetencies","reviewUserEvidenceCompetencies","_reviewUserEvidenceCompetenciesHandler","node","parent","parentsUntil","Error","enhanceMenubar","selector","enhance","bind","registerEvents","wrapper","find","click"],"mappings":"AAsBAA,OAAM,iCAAC,CAAC,QAAD,CACC,gBADD,CAEC,WAFD,CAGC,mBAHD,CAIC,UAJD,CAKC,iBALD,CAMC,qCAND,CAAD,CAOE,SAASC,CAAT,CAAYC,CAAZ,CAAuBC,CAAvB,CAA6BC,CAA7B,CAA2CC,CAA3C,CAAgDC,CAAhD,CAAyDC,CAAzD,CAA0E,CAS9E,GAAIC,CAAAA,CAAmB,CAAG,SAASC,CAAT,CAAe,CACrC,KAAKC,KAAL,CAAaD,CAAb,CAEA,GAAa,UAAT,GAAAA,CAAJ,CAAyB,CAErB,KAAKE,OAAL,CAAe,sCAAf,CACA,KAAKC,aAAL,CAAqB,sCAArB,CACA,KAAKC,SAAL,CAAiB,4BAAjB,CACA,KAAKC,cAAL,CAAsB,qCAEzB,CAPD,IAOO,IAAa,MAAT,GAAAL,CAAJ,CAAqB,CAExB,KAAKE,OAAL,CAAe,sCAAf,CACA,KAAKC,aAAL,CAAqB,sCAArB,CACA,KAAKC,SAAL,CAAiB,iCAAjB,CACA,KAAKC,cAAL,CAAsB,0CAEzB,CAPM,IAOA,CACH,KAAM,IAAIC,CAAAA,SAAJ,CAAc,kBAAd,CACT,CACJ,CApBD,CA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,CAA/D,CACH,CARD,CAUA,MAA0DX,CAAAA,CAC7D,CA1XK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * User evidence actions.\n *\n * @module tool_lp/user_evidence_actions\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',\n 'core/templates',\n 'core/ajax',\n 'core/notification',\n 'core/str',\n 'tool_lp/menubar',\n 'tool_lp/competencypicker_user_plans'],\n function($, templates, ajax, notification, str, Menubar, PickerUserPlans) {\n\n /**\n * UserEvidenceActions class.\n *\n * Note that presently this cannot be instantiated more than once per page.\n *\n * @param {String} type The type of page we're in.\n */\n var UserEvidenceActions = function(type) {\n this._type = type;\n\n if (type === 'evidence') {\n // This is the page to view one evidence.\n this._region = '[data-region=\"user-evidence-page\"]';\n this._evidenceNode = '[data-region=\"user-evidence-page\"]';\n this._template = 'tool_lp/user_evidence_page';\n this._contextMethod = 'tool_lp_data_for_user_evidence_page';\n\n } else if (type === 'list') {\n // This is the page to view a list of evidence.\n this._region = '[data-region=\"user-evidence-list\"]';\n this._evidenceNode = '[data-region=\"user-evidence-node\"]';\n this._template = 'tool_lp/user_evidence_list_page';\n this._contextMethod = 'tool_lp_data_for_user_evidence_list_page';\n\n } else {\n throw new TypeError('Unexpected type.');\n }\n };\n\n /** @property {String} Ajax method to fetch the page data from. */\n UserEvidenceActions.prototype._contextMethod = null;\n /** @property {String} Selector to find the node describing the evidence. */\n UserEvidenceActions.prototype._evidenceNode = null;\n /** @property {String} Selector mapping to the region to update. Usually similar to wrapper. */\n UserEvidenceActions.prototype._region = null;\n /** @property {String} Name of the template used to render the region. */\n UserEvidenceActions.prototype._template = null;\n /** @property {String} Type of page/region we're in. */\n UserEvidenceActions.prototype._type = null;\n\n /**\n * Resolve the arguments to refresh the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @return {Object} List of arguments.\n */\n UserEvidenceActions.prototype._getContextArgs = function(evidenceData) {\n var self = this,\n args = {};\n\n if (self._type === 'evidence') {\n args = {\n id: evidenceData.id\n };\n\n } else if (self._type === 'list') {\n args = {\n userid: evidenceData.userid\n };\n }\n\n return args;\n };\n\n /**\n * Callback to render the region template.\n *\n * @param {Object} context The context for the template.\n * @return {Promise}\n */\n UserEvidenceActions.prototype._renderView = function(context) {\n var self = this;\n return templates.render(self._template, context)\n .then(function(newhtml, newjs) {\n templates.replaceNode($(self._region), newhtml, newjs);\n return;\n });\n };\n\n /**\n * Call multiple ajax methods, and refresh.\n *\n * @param {Array} calls List of Ajax calls.\n * @param {Object} evidenceData Evidence data from evidence node.\n * @return {Promise}\n */\n UserEvidenceActions.prototype._callAndRefresh = function(calls, evidenceData) {\n var self = this;\n calls.push({\n methodname: self._contextMethod,\n args: self._getContextArgs(evidenceData)\n });\n\n // Apply all the promises, and refresh when the last one is resolved.\n return $.when.apply($.when, ajax.call(calls))\n .then(function() {\n return self._renderView(arguments[arguments.length - 1]);\n })\n .fail(notification.exception);\n };\n\n /**\n * Delete a plan and reload the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype._doDelete = function(evidenceData) {\n var self = this,\n calls = [{\n methodname: 'core_competency_delete_user_evidence',\n args: {id: evidenceData.id}\n }];\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Delete a plan.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.deleteEvidence = function(evidenceData) {\n var self = this,\n requests;\n\n requests = ajax.call([{\n methodname: 'core_competency_read_user_evidence',\n args: {id: evidenceData.id}\n }]);\n\n requests[0].done(function(evidence) {\n str.get_strings([\n {key: 'confirm', component: 'moodle'},\n {key: 'deleteuserevidence', component: 'tool_lp', param: evidence.name},\n {key: 'delete', component: 'moodle'},\n {key: 'cancel', component: 'moodle'}\n ]).done(function(strings) {\n notification.confirm(\n strings[0], // Confirm.\n strings[1], // Delete evidence X?\n strings[2], // Delete.\n strings[3], // Cancel.\n function() {\n self._doDelete(evidenceData);\n }\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n\n };\n\n /**\n * Delete evidence handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._deleteEvidenceHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.deleteEvidence(data);\n };\n\n /**\n * Link a competency and reload.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyIds The competency IDs.\n * @param {Boolean} requestReview Send competencies to review.\n */\n UserEvidenceActions.prototype._doCreateUserEvidenceCompetency = function(evidenceData, competencyIds) {\n var self = this,\n calls = [];\n\n $.each(competencyIds, function(index, competencyId) {\n calls.push({\n methodname: 'core_competency_create_user_evidence_competency',\n args: {\n userevidenceid: evidenceData.id,\n competencyid: competencyId,\n }\n });\n });\n\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Create a user evidence competency.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.createUserEvidenceCompetency = function(evidenceData) {\n var self = this,\n picker = new PickerUserPlans(evidenceData.userid);\n\n picker.on('save', function(e, data) {\n var competencyIds = data.competencyIds;\n self._doCreateUserEvidenceCompetency(evidenceData, competencyIds, data.requestReview);\n });\n\n picker.display();\n };\n\n /**\n * Create user evidence competency handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._createUserEvidenceCompetencyHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.createUserEvidenceCompetency(data);\n };\n\n /**\n * Remove a linked competency and reload.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyId The competency ID.\n */\n UserEvidenceActions.prototype._doDeleteUserEvidenceCompetency = function(evidenceData, competencyId) {\n var self = this,\n calls = [];\n\n calls.push({\n methodname: 'core_competency_delete_user_evidence_competency',\n args: {\n userevidenceid: evidenceData.id,\n competencyid: competencyId,\n }\n });\n\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Delete a user evidence competency.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyId The competency ID.\n */\n UserEvidenceActions.prototype.deleteUserEvidenceCompetency = function(evidenceData, competencyId) {\n this._doDeleteUserEvidenceCompetency(evidenceData, competencyId);\n };\n\n /**\n * Delete user evidence competency handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._deleteUserEvidenceCompetencyHandler = function(e) {\n var data = this._findEvidenceData($(e.currentTarget)),\n competencyId = $(e.currentTarget).data('id');\n e.preventDefault();\n this.deleteUserEvidenceCompetency(data, competencyId);\n };\n\n /**\n * Send request review for user evidence competencies and reload the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype._doReviewUserEvidenceCompetencies = function(evidenceData) {\n var self = this,\n calls = [{\n methodname: 'core_competency_request_review_of_user_evidence_linked_competencies',\n args: {id: evidenceData.id}\n }];\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Send request review for user evidence competencies.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.reviewUserEvidenceCompetencies = function(evidenceData) {\n var self = this,\n requests;\n\n requests = ajax.call([{\n methodname: 'core_competency_read_user_evidence',\n args: {id: evidenceData.id}\n }]);\n\n requests[0].done(function(evidence) {\n str.get_strings([\n {key: 'confirm', component: 'moodle'},\n {key: 'sendallcompetenciestoreview', component: 'tool_lp', param: evidence.name},\n {key: 'confirm', component: 'moodle'},\n {key: 'cancel', component: 'moodle'}\n ]).done(function(strings) {\n notification.confirm(\n strings[0], // Confirm.\n strings[1], // Send all competencies in review for X?\n strings[2], // Confirm.\n strings[3], // Cancel.\n function() {\n self._doReviewUserEvidenceCompetencies(evidenceData);\n }\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n\n };\n\n /**\n * Send request review for user evidence competencies handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._reviewUserEvidenceCompetenciesHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.reviewUserEvidenceCompetencies(data);\n };\n\n /**\n * Find the evidence data from the evidence node.\n *\n * @param {Node} node The node to search from.\n * @return {Object} Evidence data.\n */\n UserEvidenceActions.prototype._findEvidenceData = function(node) {\n var parent = node.parentsUntil($(this._region).parent(), this._evidenceNode),\n data;\n\n if (parent.length != 1) {\n throw new Error('The evidence node was not located.');\n }\n\n data = parent.data();\n if (typeof data === 'undefined' || typeof data.id === 'undefined') {\n throw new Error('Evidence data could not be found.');\n }\n\n return data;\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserEvidenceActions.prototype.enhanceMenubar = function(selector) {\n var self = this;\n Menubar.enhance(selector, {\n '[data-action=\"user-evidence-delete\"]': self._deleteEvidenceHandler.bind(self),\n '[data-action=\"link-competency\"]': self._createUserEvidenceCompetencyHandler.bind(self),\n '[data-action=\"send-competencies-review\"]': self._reviewUserEvidenceCompetenciesHandler.bind(self),\n });\n };\n\n /**\n * Register the events in the region.\n *\n * At this stage this cannot be used with enhanceMenubar or multiple handlers\n * will be added to the same node.\n */\n UserEvidenceActions.prototype.registerEvents = function() {\n var wrapper = $(this._region),\n self = this;\n\n wrapper.find('[data-action=\"user-evidence-delete\"]').click(self._deleteEvidenceHandler.bind(self));\n wrapper.find('[data-action=\"link-competency\"]').click(self._createUserEvidenceCompetencyHandler.bind(self));\n wrapper.find('[data-action=\"delete-competency-link\"]').click(self._deleteUserEvidenceCompetencyHandler.bind(self));\n wrapper.find('[data-action=\"send-competencies-review\"]').click(self._reviewUserEvidenceCompetenciesHandler.bind(self));\n };\n\n return /** @alias module:tool_lp/user_evidence_actions */ UserEvidenceActions;\n});\n"],"file":"user_evidence_actions.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/user_evidence_actions.js"],"names":["define","$","templates","ajax","notification","str","Menubar","PickerUserPlans","UserEvidenceActions","type","_type","_region","_evidenceNode","_template","_contextMethod","TypeError","prototype","_getContextArgs","evidenceData","self","args","id","userid","_renderView","context","render","then","newhtml","newjs","replaceNode","_callAndRefresh","calls","push","methodname","when","apply","call","arguments","length","fail","exception","_doDelete","deleteEvidence","requests","done","evidence","get_strings","key","component","param","name","strings","confirm","_deleteEvidenceHandler","e","preventDefault","data","_findEvidenceData","target","_doCreateUserEvidenceCompetency","competencyIds","each","index","competencyId","userevidenceid","competencyid","createUserEvidenceCompetency","picker","on","requestReview","display","_createUserEvidenceCompetencyHandler","_doDeleteUserEvidenceCompetency","deleteUserEvidenceCompetency","_deleteUserEvidenceCompetencyHandler","currentTarget","_doReviewUserEvidenceCompetencies","reviewUserEvidenceCompetencies","_reviewUserEvidenceCompetenciesHandler","node","parent","parentsUntil","Error","enhanceMenubar","selector","enhance","bind","registerEvents","wrapper","find","click"],"mappings":"AAsBAA,OAAM,iCAAC,CAAC,QAAD,CACC,gBADD,CAEC,WAFD,CAGC,mBAHD,CAIC,UAJD,CAKC,iBALD,CAMC,qCAND,CAAD,CAOE,SAASC,CAAT,CAAYC,CAAZ,CAAuBC,CAAvB,CAA6BC,CAA7B,CAA2CC,CAA3C,CAAgDC,CAAhD,CAAyDC,CAAzD,CAA0E,CAS9E,GAAIC,CAAAA,CAAmB,CAAG,SAASC,CAAT,CAAe,CACrC,KAAKC,KAAL,CAAaD,CAAb,CAEA,GAAa,UAAT,GAAAA,CAAJ,CAAyB,CAErB,KAAKE,OAAL,CAAe,sCAAf,CACA,KAAKC,aAAL,CAAqB,sCAArB,CACA,KAAKC,SAAL,CAAiB,4BAAjB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oCAAL,CAA0Ce,IAA1C,CAA+CnE,CAA/C,CAAtD,EACAqE,CAAO,CAACC,IAAR,CAAa,0CAAb,EAAuDC,KAAvD,CAA6DvE,CAAI,CAACuD,oCAAL,CAA0CY,IAA1C,CAA+CnE,CAA/C,CAA7D,EACAqE,CAAO,CAACC,IAAR,CAAa,4CAAb,EAAyDC,KAAzD,CAA+DvE,CAAI,CAAC2D,sCAAL,CAA4CQ,IAA5C,CAAiDnE,CAAjD,CAA/D,CACH,CARD,CAUA,MAA0DX,CAAAA,CAC7D,CAzXK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * User evidence actions.\n *\n * @module tool_lp/user_evidence_actions\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',\n 'core/templates',\n 'core/ajax',\n 'core/notification',\n 'core/str',\n 'tool_lp/menubar',\n 'tool_lp/competencypicker_user_plans'],\n function($, templates, ajax, notification, str, Menubar, PickerUserPlans) {\n\n /**\n * UserEvidenceActions class.\n *\n * Note that presently this cannot be instantiated more than once per page.\n *\n * @param {String} type The type of page we're in.\n */\n var UserEvidenceActions = function(type) {\n this._type = type;\n\n if (type === 'evidence') {\n // This is the page to view one evidence.\n this._region = '[data-region=\"user-evidence-page\"]';\n this._evidenceNode = '[data-region=\"user-evidence-page\"]';\n this._template = 'tool_lp/user_evidence_page';\n this._contextMethod = 'tool_lp_data_for_user_evidence_page';\n\n } else if (type === 'list') {\n // This is the page to view a list of evidence.\n this._region = '[data-region=\"user-evidence-list\"]';\n this._evidenceNode = '[data-region=\"user-evidence-node\"]';\n this._template = 'tool_lp/user_evidence_list_page';\n this._contextMethod = 'tool_lp_data_for_user_evidence_list_page';\n\n } else {\n throw new TypeError('Unexpected type.');\n }\n };\n\n /** @property {String} Ajax method to fetch the page data from. */\n UserEvidenceActions.prototype._contextMethod = null;\n /** @property {String} Selector to find the node describing the evidence. */\n UserEvidenceActions.prototype._evidenceNode = null;\n /** @property {String} Selector mapping to the region to update. Usually similar to wrapper. */\n UserEvidenceActions.prototype._region = null;\n /** @property {String} Name of the template used to render the region. */\n UserEvidenceActions.prototype._template = null;\n /** @property {String} Type of page/region we're in. */\n UserEvidenceActions.prototype._type = null;\n\n /**\n * Resolve the arguments to refresh the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @return {Object} List of arguments.\n */\n UserEvidenceActions.prototype._getContextArgs = function(evidenceData) {\n var self = this,\n args = {};\n\n if (self._type === 'evidence') {\n args = {\n id: evidenceData.id\n };\n\n } else if (self._type === 'list') {\n args = {\n userid: evidenceData.userid\n };\n }\n\n return args;\n };\n\n /**\n * Callback to render the region template.\n *\n * @param {Object} context The context for the template.\n * @return {Promise}\n */\n UserEvidenceActions.prototype._renderView = function(context) {\n var self = this;\n return templates.render(self._template, context)\n .then(function(newhtml, newjs) {\n templates.replaceNode($(self._region), newhtml, newjs);\n return;\n });\n };\n\n /**\n * Call multiple ajax methods, and refresh.\n *\n * @param {Array} calls List of Ajax calls.\n * @param {Object} evidenceData Evidence data from evidence node.\n * @return {Promise}\n */\n UserEvidenceActions.prototype._callAndRefresh = function(calls, evidenceData) {\n var self = this;\n calls.push({\n methodname: self._contextMethod,\n args: self._getContextArgs(evidenceData)\n });\n\n // Apply all the promises, and refresh when the last one is resolved.\n return $.when.apply($.when, ajax.call(calls))\n .then(function() {\n return self._renderView(arguments[arguments.length - 1]);\n })\n .fail(notification.exception);\n };\n\n /**\n * Delete a plan and reload the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype._doDelete = function(evidenceData) {\n var self = this,\n calls = [{\n methodname: 'core_competency_delete_user_evidence',\n args: {id: evidenceData.id}\n }];\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Delete a plan.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.deleteEvidence = function(evidenceData) {\n var self = this,\n requests;\n\n requests = ajax.call([{\n methodname: 'core_competency_read_user_evidence',\n args: {id: evidenceData.id}\n }]);\n\n requests[0].done(function(evidence) {\n str.get_strings([\n {key: 'confirm', component: 'moodle'},\n {key: 'deleteuserevidence', component: 'tool_lp', param: evidence.name},\n {key: 'delete', component: 'moodle'},\n {key: 'cancel', component: 'moodle'}\n ]).done(function(strings) {\n notification.confirm(\n strings[0], // Confirm.\n strings[1], // Delete evidence X?\n strings[2], // Delete.\n strings[3], // Cancel.\n function() {\n self._doDelete(evidenceData);\n }\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n\n };\n\n /**\n * Delete evidence handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._deleteEvidenceHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.deleteEvidence(data);\n };\n\n /**\n * Link a competency and reload.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyIds The competency IDs.\n */\n UserEvidenceActions.prototype._doCreateUserEvidenceCompetency = function(evidenceData, competencyIds) {\n var self = this,\n calls = [];\n\n $.each(competencyIds, function(index, competencyId) {\n calls.push({\n methodname: 'core_competency_create_user_evidence_competency',\n args: {\n userevidenceid: evidenceData.id,\n competencyid: competencyId,\n }\n });\n });\n\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Create a user evidence competency.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.createUserEvidenceCompetency = function(evidenceData) {\n var self = this,\n picker = new PickerUserPlans(evidenceData.userid);\n\n picker.on('save', function(e, data) {\n var competencyIds = data.competencyIds;\n self._doCreateUserEvidenceCompetency(evidenceData, competencyIds, data.requestReview);\n });\n\n picker.display();\n };\n\n /**\n * Create user evidence competency handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._createUserEvidenceCompetencyHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.createUserEvidenceCompetency(data);\n };\n\n /**\n * Remove a linked competency and reload.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyId The competency ID.\n */\n UserEvidenceActions.prototype._doDeleteUserEvidenceCompetency = function(evidenceData, competencyId) {\n var self = this,\n calls = [];\n\n calls.push({\n methodname: 'core_competency_delete_user_evidence_competency',\n args: {\n userevidenceid: evidenceData.id,\n competencyid: competencyId,\n }\n });\n\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Delete a user evidence competency.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n * @param {Number} competencyId The competency ID.\n */\n UserEvidenceActions.prototype.deleteUserEvidenceCompetency = function(evidenceData, competencyId) {\n this._doDeleteUserEvidenceCompetency(evidenceData, competencyId);\n };\n\n /**\n * Delete user evidence competency handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._deleteUserEvidenceCompetencyHandler = function(e) {\n var data = this._findEvidenceData($(e.currentTarget)),\n competencyId = $(e.currentTarget).data('id');\n e.preventDefault();\n this.deleteUserEvidenceCompetency(data, competencyId);\n };\n\n /**\n * Send request review for user evidence competencies and reload the region.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype._doReviewUserEvidenceCompetencies = function(evidenceData) {\n var self = this,\n calls = [{\n methodname: 'core_competency_request_review_of_user_evidence_linked_competencies',\n args: {id: evidenceData.id}\n }];\n self._callAndRefresh(calls, evidenceData);\n };\n\n /**\n * Send request review for user evidence competencies.\n *\n * @param {Object} evidenceData Evidence data from evidence node.\n */\n UserEvidenceActions.prototype.reviewUserEvidenceCompetencies = function(evidenceData) {\n var self = this,\n requests;\n\n requests = ajax.call([{\n methodname: 'core_competency_read_user_evidence',\n args: {id: evidenceData.id}\n }]);\n\n requests[0].done(function(evidence) {\n str.get_strings([\n {key: 'confirm', component: 'moodle'},\n {key: 'sendallcompetenciestoreview', component: 'tool_lp', param: evidence.name},\n {key: 'confirm', component: 'moodle'},\n {key: 'cancel', component: 'moodle'}\n ]).done(function(strings) {\n notification.confirm(\n strings[0], // Confirm.\n strings[1], // Send all competencies in review for X?\n strings[2], // Confirm.\n strings[3], // Cancel.\n function() {\n self._doReviewUserEvidenceCompetencies(evidenceData);\n }\n );\n }).fail(notification.exception);\n }).fail(notification.exception);\n\n };\n\n /**\n * Send request review for user evidence competencies handler.\n *\n * @param {Event} e The event.\n */\n UserEvidenceActions.prototype._reviewUserEvidenceCompetenciesHandler = function(e) {\n e.preventDefault();\n var data = this._findEvidenceData($(e.target));\n this.reviewUserEvidenceCompetencies(data);\n };\n\n /**\n * Find the evidence data from the evidence node.\n *\n * @param {Node} node The node to search from.\n * @return {Object} Evidence data.\n */\n UserEvidenceActions.prototype._findEvidenceData = function(node) {\n var parent = node.parentsUntil($(this._region).parent(), this._evidenceNode),\n data;\n\n if (parent.length != 1) {\n throw new Error('The evidence node was not located.');\n }\n\n data = parent.data();\n if (typeof data === 'undefined' || typeof data.id === 'undefined') {\n throw new Error('Evidence data could not be found.');\n }\n\n return data;\n };\n\n /**\n * Enhance a menu bar.\n *\n * @param {String} selector Menubar selector.\n */\n UserEvidenceActions.prototype.enhanceMenubar = function(selector) {\n var self = this;\n Menubar.enhance(selector, {\n '[data-action=\"user-evidence-delete\"]': self._deleteEvidenceHandler.bind(self),\n '[data-action=\"link-competency\"]': self._createUserEvidenceCompetencyHandler.bind(self),\n '[data-action=\"send-competencies-review\"]': self._reviewUserEvidenceCompetenciesHandler.bind(self),\n });\n };\n\n /**\n * Register the events in the region.\n *\n * At this stage this cannot be used with enhanceMenubar or multiple handlers\n * will be added to the same node.\n */\n UserEvidenceActions.prototype.registerEvents = function() {\n var wrapper = $(this._region),\n self = this;\n\n wrapper.find('[data-action=\"user-evidence-delete\"]').click(self._deleteEvidenceHandler.bind(self));\n wrapper.find('[data-action=\"link-competency\"]').click(self._createUserEvidenceCompetencyHandler.bind(self));\n wrapper.find('[data-action=\"delete-competency-link\"]').click(self._deleteUserEvidenceCompetencyHandler.bind(self));\n wrapper.find('[data-action=\"send-competencies-review\"]').click(self._reviewUserEvidenceCompetenciesHandler.bind(self));\n };\n\n return /** @alias module:tool_lp/user_evidence_actions */ UserEvidenceActions;\n});\n"],"file":"user_evidence_actions.min.js"} \ No newline at end of file diff --git a/admin/tool/lp/amd/src/competency_rule.js b/admin/tool/lp/amd/src/competency_rule.js index 130d6cbb9b469..ae648d8c9e6b9 100644 --- a/admin/tool/lp/amd/src/competency_rule.js +++ b/admin/tool/lp/amd/src/competency_rule.js @@ -98,8 +98,7 @@ define(['jquery'], function($) { /** * Callback to inject the template. * - * @param {Node} container Node to inject in. - * @return {Promise} Resolved when done. + * @returns {Promise} Resolved when done. * @method injectTemplate */ Rule.prototype.injectTemplate = function() { diff --git a/admin/tool/lp/amd/src/competencydialogue.js b/admin/tool/lp/amd/src/competencydialogue.js index 3159f339f51c4..812e77a0eea9b 100644 --- a/admin/tool/lp/amd/src/competencydialogue.js +++ b/admin/tool/lp/amd/src/competencydialogue.js @@ -37,9 +37,6 @@ define(['jquery', /** * Constructor for CompetencyDialogue. - * - * @param {Object} options - * */ var Competencydialogue = function() { // Intentionally left empty. diff --git a/admin/tool/lp/amd/src/competencyruleconfig.js b/admin/tool/lp/amd/src/competencyruleconfig.js index 0378ebc0d89d6..fac99a8d0ecf7 100644 --- a/admin/tool/lp/amd/src/competencyruleconfig.js +++ b/admin/tool/lp/amd/src/competencyruleconfig.js @@ -156,9 +156,8 @@ define(['jquery', /** * Opens the picker. * - * @param {Number} competencyId The competency ID of the competency to work on. * @method display - * @return {Promise} + * @returns {Promise} */ RuleConfig.prototype.display = function() { var self = this; diff --git a/admin/tool/lp/amd/src/course_competency_settings.js b/admin/tool/lp/amd/src/course_competency_settings.js index 6241bd0c1173c..1d4668b46b489 100644 --- a/admin/tool/lp/amd/src/course_competency_settings.js +++ b/admin/tool/lp/amd/src/course_competency_settings.js @@ -137,7 +137,6 @@ define(['jquery', /** * Refresh the course competencies page. * - * @param {Event} e * @method saveSettings */ settingsMod.prototype.refreshCourseCompetenciesPage = function() { diff --git a/admin/tool/lp/amd/src/dragdrop-reorder.js b/admin/tool/lp/amd/src/dragdrop-reorder.js index 9359cd94c11fb..0bdff315e5d4a 100644 --- a/admin/tool/lp/amd/src/dragdrop-reorder.js +++ b/admin/tool/lp/amd/src/dragdrop-reorder.js @@ -26,7 +26,7 @@ define(['core/str', 'core/yui'], function(str, Y) { /** * Store the current instance of the core drag drop. * - * @property dragDropInstance M.tool_lp.dragdrop_reorder + * @property {object} dragDropInstance M.tool_lp.dragdrop_reorder */ var dragDropInstance = null; diff --git a/admin/tool/lp/amd/src/grade_dialogue.js b/admin/tool/lp/amd/src/grade_dialogue.js index ae6edb22f781a..25bed4b4c9cf7 100644 --- a/admin/tool/lp/amd/src/grade_dialogue.js +++ b/admin/tool/lp/amd/src/grade_dialogue.js @@ -99,7 +99,6 @@ define(['jquery', /** * Opens the picker. * - * @param {Number} competencyId The competency ID of the competency to work on. * @method display * @return {Promise} */ diff --git a/admin/tool/lp/amd/src/menubar.js b/admin/tool/lp/amd/src/menubar.js index 6b0c0e07037c8..11a371823c6cc 100644 --- a/admin/tool/lp/amd/src/menubar.js +++ b/admin/tool/lp/amd/src/menubar.js @@ -43,8 +43,8 @@ define(['jquery'], function($) { /** * Constructor * - * @param {$} menuRoot Jquery collection matching the root of the menu. - * @param {Function[]} handlers, called when a menu item is chosen. + * @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. diff --git a/admin/tool/lp/amd/src/tree.js b/admin/tool/lp/amd/src/tree.js index c0d8501ee59f1..561878bf19ed8 100644 --- a/admin/tool/lp/amd/src/tree.js +++ b/admin/tool/lp/amd/src/tree.js @@ -574,8 +574,6 @@ define(['jquery', 'core/url', 'core/log'], function($, url, log) { * Handle a blur event * * @method handleBlur - * @param {Object} item item is the jquery id of the parent item of the group - * @param {Event} e The event. * @return {Boolean} */ Tree.prototype.handleBlur = function() { @@ -587,7 +585,6 @@ define(['jquery', 'core/url', 'core/log'], function($, url, log) { * * @method handleFocus * @param {Object} item item is the jquery id of the parent item of the group - * @param {Event} e The event. * @return {Boolean} */ Tree.prototype.handleFocus = function(item) { diff --git a/admin/tool/lp/amd/src/user_competency_workflow.js b/admin/tool/lp/amd/src/user_competency_workflow.js index b8824e3f36460..13572b1503de8 100644 --- a/admin/tool/lp/amd/src/user_competency_workflow.js +++ b/admin/tool/lp/amd/src/user_competency_workflow.js @@ -31,8 +31,6 @@ define(['jquery', /** * UserCompetencyWorkflow class. - * - * @param {String} selector The node containing the buttons to switch mode. */ var UserCompetencyWorkflow = function() { EventBase.prototype.constructor.apply(this, []); diff --git a/admin/tool/lp/amd/src/user_evidence_actions.js b/admin/tool/lp/amd/src/user_evidence_actions.js index 7bb30c3e56baf..c48f7e1f61a9a 100644 --- a/admin/tool/lp/amd/src/user_evidence_actions.js +++ b/admin/tool/lp/amd/src/user_evidence_actions.js @@ -195,7 +195,6 @@ define(['jquery', * * @param {Object} evidenceData Evidence data from evidence node. * @param {Number} competencyIds The competency IDs. - * @param {Boolean} requestReview Send competencies to review. */ UserEvidenceActions.prototype._doCreateUserEvidenceCompetency = function(evidenceData, competencyIds) { var self = this, diff --git a/admin/tool/policy/amd/build/policyactions.min.js.map b/admin/tool/policy/amd/build/policyactions.min.js.map index 7c9a1e2b698ac..6cfd15e5e921a 100644 --- a/admin/tool/policy/amd/build/policyactions.min.js.map +++ b/admin/tool/policy/amd/build/policyactions.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/policyactions.js"],"names":["define","$","Ajax","Notification","ModalFactory","ModalEvents","PolicyActions","root","registerEvents","prototype","on","e","preventDefault","versionid","data","behalfid","modalTitle","Deferred","modalBody","modal","create","title","body","large","then","getRoot","hidden","destroy","show","catch","exception","promises","call","methodname","args","when","result","policy","resolve","name","content","Error","warnings","message","hide","addNotification","type"],"mappings":"AAsBAA,OAAM,6BAAC,CACH,QADG,CAEH,WAFG,CAGH,mBAHG,CAIH,oBAJG,CAKH,mBALG,CAAD,CAMN,SAASC,CAAT,CAAYC,CAAZ,CAAkBC,CAAlB,CAAgCC,CAAhC,CAA8CC,CAA9C,CAA2D,CAKvD,GAAIC,CAAAA,CAAa,CAAG,SAASC,CAAT,CAAe,CAC/B,KAAKC,cAAL,CAAoBD,CAApB,CACH,CAFD,CAOAD,CAAa,CAACG,SAAd,CAAwBD,cAAxB,CAAyC,SAASD,CAAT,CAAe,CACpDA,CAAI,CAACG,EAAL,CAAQ,OAAR,CAAiB,SAASC,CAAT,CAAY,CACzBA,CAAC,CAACC,cAAF,GADyB,GAGrBC,CAAAA,CAAS,CAAGZ,CAAC,CAAC,IAAD,CAAD,CAAQa,IAAR,CAAa,WAAb,CAHS,CAIrBC,CAAQ,CAAGd,CAAC,CAAC,IAAD,CAAD,CAAQa,IAAR,CAAa,UAAb,CAJU,CAgBrBE,CAAU,CAAGf,CAAC,CAACgB,QAAF,EAhBQ,CAiBrBC,CAAS,CAAGjB,CAAC,CAACgB,QAAF,EAjBS,CAmBrBE,CAAK,CAAGf,CAAY,CAACgB,MAAb,CAAoB,CAC5BC,KAAK,CAAEL,CADqB,CAE5BM,IAAI,CAAEJ,CAFsB,CAG5BK,KAAK,GAHuB,CAApB,EAKXC,IALW,CAKN,SAASL,CAAT,CAAgB,CAElBA,CAAK,CAACM,OAAN,GAAgBf,EAAhB,CAAmBL,CAAW,CAACqB,MAA/B,CAAuC,UAAW,CAE9CP,CAAK,CAACQ,OAAN,EACH,CAHD,EAKA,MAAOR,CAAAA,CACV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AAD,CAAR,CACA,MAAO,IAAID,CAAAA,CAAJ,CAAkBC,CAAlB,CACV,CAZiD,CAczD,CAtGK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Policy actions.\n *\n * @module tool_policy/policyactions\n * @copyright 2018 Sara Arjona (sara@moodle.com)\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/ajax',\n 'core/notification',\n 'core/modal_factory',\n 'core/modal_events'],\nfunction($, Ajax, Notification, ModalFactory, ModalEvents) {\n\n /**\n * PolicyActions class.\n */\n var PolicyActions = function(root) {\n this.registerEvents(root);\n };\n\n /**\n * Register event listeners.\n */\n PolicyActions.prototype.registerEvents = function(root) {\n root.on(\"click\", function(e) {\n e.preventDefault();\n\n var versionid = $(this).data('versionid');\n var behalfid = $(this).data('behalfid');\n\n var params = {\n 'versionid': versionid,\n 'behalfid': behalfid\n };\n\n var request = {\n methodname: 'tool_policy_get_policy_version',\n args: params\n };\n\n var modalTitle = $.Deferred();\n var modalBody = $.Deferred();\n\n var modal = ModalFactory.create({\n title: modalTitle,\n body: modalBody,\n large: true\n })\n .then(function(modal) {\n // Handle hidden event.\n modal.getRoot().on(ModalEvents.hidden, function() {\n // Destroy when hidden.\n modal.destroy();\n });\n\n return modal;\n })\n .then(function(modal) {\n modal.show();\n\n return modal;\n })\n .catch(Notification.exception);\n\n // Make the request now that the modal is configured.\n var promises = Ajax.call([request]);\n $.when(promises[0]).then(function(data) {\n if (data.result.policy) {\n modalTitle.resolve(data.result.policy.name);\n modalBody.resolve(data.result.policy.content);\n\n return data;\n } else {\n throw new Error(data.warnings[0].message);\n }\n }).catch(function(message) {\n modal.then(function(modal) {\n modal.hide();\n modal.destroy();\n\n return modal;\n })\n .catch(Notification.exception);\n\n return Notification.addNotification({\n message: message,\n type: 'error'\n });\n });\n });\n\n };\n\n return /** @alias module:tool_policy/policyactions */ {\n // Public variables and functions.\n\n /**\n * Initialise the actions helper.\n *\n * @method init\n * @return {PolicyActions}\n */\n 'init': function(root) {\n root = $(root);\n return new PolicyActions(root);\n }\n };\n});\n"],"file":"policyactions.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/policyactions.js"],"names":["define","$","Ajax","Notification","ModalFactory","ModalEvents","PolicyActions","root","registerEvents","prototype","on","e","preventDefault","versionid","data","behalfid","modalTitle","Deferred","modalBody","modal","create","title","body","large","then","getRoot","hidden","destroy","show","catch","exception","promises","call","methodname","args","when","result","policy","resolve","name","content","Error","warnings","message","hide","addNotification","type"],"mappings":"AAsBAA,OAAM,6BAAC,CACH,QADG,CAEH,WAFG,CAGH,mBAHG,CAIH,oBAJG,CAKH,mBALG,CAAD,CAMN,SAASC,CAAT,CAAYC,CAAZ,CAAkBC,CAAlB,CAAgCC,CAAhC,CAA8CC,CAA9C,CAA2D,CAOvD,GAAIC,CAAAA,CAAa,CAAG,SAASC,CAAT,CAAe,CAC/B,KAAKC,cAAL,CAAoBD,CAApB,CACH,CAFD,CASAD,CAAa,CAACG,SAAd,CAAwBD,cAAxB,CAAyC,SAASD,CAAT,CAAe,CACpDA,CAAI,CAACG,EAAL,CAAQ,OAAR,CAAiB,SAASC,CAAT,CAAY,CACzBA,CAAC,CAACC,cAAF,GADyB,GAGrBC,CAAAA,CAAS,CAAGZ,CAAC,CAAC,IAAD,CAAD,CAAQa,IAAR,CAAa,WAAb,CAHS,CAIrBC,CAAQ,CAAGd,CAAC,CAAC,IAAD,CAAD,CAAQa,IAAR,CAAa,UAAb,CAJU,CAgBrBE,CAAU,CAA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B,CAAK,CAACK,IAAN,CAAW,SAASL,CAAT,CAAgB,CACvBA,CAAK,CAACyB,IAAN,GACAzB,CAAK,CAACQ,OAAN,GAEA,MAAOR,CAAAA,CACV,CALD,EAMCU,KAND,CAMO1B,CAAY,CAAC2B,SANpB,EAQA,MAAO3B,CAAAA,CAAY,CAAC0C,eAAb,CAA6B,CAChCF,OAAO,CAAEA,CADuB,CAEhCG,IAAI,CAAE,OAF0B,CAA7B,CAIV,CAtBD,CAuBH,CAjED,CAmEH,CApED,CAsEA,MAAsD,CAUlD,KAAQ,cAASvC,CAAT,CAAe,CACnBA,CAAI,CAAGN,CAAC,CAACM,CAAD,CAAR,CACA,MAAO,IAAID,CAAAA,CAAJ,CAAkBC,CAAlB,CACV,CAbiD,CAezD,CA3GK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Policy actions.\n *\n * @module tool_policy/policyactions\n * @copyright 2018 Sara Arjona (sara@moodle.com)\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/ajax',\n 'core/notification',\n 'core/modal_factory',\n 'core/modal_events'],\nfunction($, Ajax, Notification, ModalFactory, ModalEvents) {\n\n /**\n * PolicyActions class.\n *\n * @param {jQuery} root\n */\n var PolicyActions = function(root) {\n this.registerEvents(root);\n };\n\n /**\n * Register event listeners.\n *\n * @param {jQuery} root\n */\n PolicyActions.prototype.registerEvents = function(root) {\n root.on(\"click\", function(e) {\n e.preventDefault();\n\n var versionid = $(this).data('versionid');\n var behalfid = $(this).data('behalfid');\n\n var params = {\n 'versionid': versionid,\n 'behalfid': behalfid\n };\n\n var request = {\n methodname: 'tool_policy_get_policy_version',\n args: params\n };\n\n var modalTitle = $.Deferred();\n var modalBody = $.Deferred();\n\n var modal = ModalFactory.create({\n title: modalTitle,\n body: modalBody,\n large: true\n })\n .then(function(modal) {\n // Handle hidden event.\n modal.getRoot().on(ModalEvents.hidden, function() {\n // Destroy when hidden.\n modal.destroy();\n });\n\n return modal;\n })\n .then(function(modal) {\n modal.show();\n\n return modal;\n })\n .catch(Notification.exception);\n\n // Make the request now that the modal is configured.\n var promises = Ajax.call([request]);\n $.when(promises[0]).then(function(data) {\n if (data.result.policy) {\n modalTitle.resolve(data.result.policy.name);\n modalBody.resolve(data.result.policy.content);\n\n return data;\n } else {\n throw new Error(data.warnings[0].message);\n }\n }).catch(function(message) {\n modal.then(function(modal) {\n modal.hide();\n modal.destroy();\n\n return modal;\n })\n .catch(Notification.exception);\n\n return Notification.addNotification({\n message: message,\n type: 'error'\n });\n });\n });\n\n };\n\n return /** @alias module:tool_policy/policyactions */ {\n // Public variables and functions.\n\n /**\n * Initialise the actions helper.\n *\n * @method init\n * @param {object} root\n * @return {PolicyActions}\n */\n 'init': function(root) {\n root = $(root);\n return new PolicyActions(root);\n }\n };\n});\n"],"file":"policyactions.min.js"} \ No newline at end of file diff --git a/admin/tool/policy/amd/src/policyactions.js b/admin/tool/policy/amd/src/policyactions.js index eead0a81470f2..c4c7bf1e80737 100644 --- a/admin/tool/policy/amd/src/policyactions.js +++ b/admin/tool/policy/amd/src/policyactions.js @@ -30,6 +30,8 @@ function($, Ajax, Notification, ModalFactory, ModalEvents) { /** * PolicyActions class. + * + * @param {jQuery} root */ var PolicyActions = function(root) { this.registerEvents(root); @@ -37,6 +39,8 @@ function($, Ajax, Notification, ModalFactory, ModalEvents) { /** * Register event listeners. + * + * @param {jQuery} root */ PolicyActions.prototype.registerEvents = function(root) { root.on("click", function(e) { @@ -115,6 +119,7 @@ function($, Ajax, Notification, ModalFactory, ModalEvents) { * Initialise the actions helper. * * @method init + * @param {object} root * @return {PolicyActions} */ 'init': function(root) { diff --git a/admin/tool/usertours/amd/build/events.min.js.map b/admin/tool/usertours/amd/build/events.min.js.map index a178770854d49..aa04927359ed5 100644 --- a/admin/tool/usertours/amd/build/events.min.js.map +++ b/admin/tool/usertours/amd/build/events.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/events.js"],"names":["stepRender","stepRendered","tourStart","tourStarted","tourEnd","tourEnded","stepHide","stepHidden"],"mappings":"uJA4C0B,CAYtBA,UAAU,CAAE,2BAZU,CAuBtBC,YAAY,CAAE,6BAvBQ,CAoCtBC,SAAS,CAAE,0BApCW,CA8CtBC,WAAW,CAAE,4BA9CS,CA0DtBC,OAAO,CAAE,wBA1Da,CAoEtBC,SAAS,CAAE,0BApEW,CAgFtBC,QAAQ,CAAE,yBAhFY,CA0FtBC,UAAU,CAAE,2BA1FU,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript events for the `tool_usertours` subsystem.\n *\n * @module tool_usertours/events\n * @copyright 2021 Andrew Lyons \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n *\n * @example Example of listening to a step rendering event and cancelling it.\n * import {eventTypes as userTourEvents} from 'tool_usertours/events';\n *\n * document.addEventListener(userTourEvents.stepRender, e => {\n * console.log(e.detail.tour); // The Tour instance\n * e.preventDefault();\n * });\n */\n\n/**\n * Events for the component.\n *\n * @constant\n * @property {String} eventTypes.stepRender See {@link event:tool_usertours/stepRender}\n * @property {String} eventTypes.stepRendered See {@link event:tool_usertours/stepRendered}\n * @property {String} eventTypes.tourStart See {@link event:tool_usertours/tourStart}\n * @property {String} eventTypes.tourStarted See {@link event:tool_usertours/tourStarted}\n * @property {String} eventTypes.tourEnd See {@link event:tool_usertours/tourEnd}\n * @property {String} eventTypes.tourEnded See {@link event:tool_usertours/tourEnded}\n * @property {String} eventTypes.stepHide See {@link event:tool_usertours/stepHide}\n * @property {String} eventTypes.stepHidden See {@link event:tool_usertours/stepHidden}\n */\nexport const eventTypes = {\n /**\n * An event triggered before a user tour step is rendered.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/stepRender\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {object} detail.stepConfig\n */\n stepRender: 'tool_usertours/stepRender',\n\n /**\n * An event triggered after a user tour step has been rendered.\n *\n * @event tool_usertours/stepRendered\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {object} detail.stepConfig\n */\n stepRendered: 'tool_usertours/stepRendered',\n\n /**\n * An event triggered before a user tour starts.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/tourStart\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {Number} detail.startAt\n */\n tourStart: 'tool_usertours/tourStart',\n\n /**\n * An event triggered after a user tour has started.\n *\n * @event tool_usertours/tourStarted\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourStarted: 'tool_usertours/tourStarted',\n\n /**\n * An event triggered before a tour ends.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/tourEnd\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourEnd: 'tool_usertours/tourEnd',\n\n /**\n * An event triggered after a tour has ended.\n *\n * @event tool_usertours/tourEnded\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourEnded: 'tool_usertours/tourEnded',\n\n /**\n * An event triggered before a step is hidden.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/stepHide\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n stepHide: 'tool_usertours/stepHide',\n\n /**\n * An event triggered after a step has been hidden.\n *\n * @event tool_usertours/stepHidden\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n stepHidden: 'tool_usertours/stepHidden',\n};\n"],"file":"events.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/events.js"],"names":["stepRender","stepRendered","tourStart","tourStarted","tourEnd","tourEnded","stepHide","stepHidden"],"mappings":"uJA6C0B,CAYtBA,UAAU,CAAE,2BAZU,CAuBtBC,YAAY,CAAE,6BAvBQ,CAoCtBC,SAAS,CAAE,0BApCW,CA8CtBC,WAAW,CAAE,4BA9CS,CA0DtBC,OAAO,CAAE,wBA1Da,CAoEtBC,SAAS,CAAE,0BApEW,CAgFtBC,QAAQ,CAAE,yBAhFY,CA0FtBC,UAAU,CAAE,2BA1FU,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript events for the `tool_usertours` subsystem.\n *\n * @module tool_usertours/events\n * @copyright 2021 Andrew Lyons \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n *\n * @example Example of listening to a step rendering event and cancelling it.\n * import {eventTypes as userTourEvents} from 'tool_usertours/events';\n *\n * document.addEventListener(userTourEvents.stepRender, e => {\n * console.log(e.detail.tour); // The Tour instance\n * e.preventDefault();\n * });\n */\n\n/**\n * Events for the component.\n *\n * @constant\n * @property {object} eventTypes\n * @property {String} eventTypes.stepRender See {@link event:tool_usertours/stepRender}\n * @property {String} eventTypes.stepRendered See {@link event:tool_usertours/stepRendered}\n * @property {String} eventTypes.tourStart See {@link event:tool_usertours/tourStart}\n * @property {String} eventTypes.tourStarted See {@link event:tool_usertours/tourStarted}\n * @property {String} eventTypes.tourEnd See {@link event:tool_usertours/tourEnd}\n * @property {String} eventTypes.tourEnded See {@link event:tool_usertours/tourEnded}\n * @property {String} eventTypes.stepHide See {@link event:tool_usertours/stepHide}\n * @property {String} eventTypes.stepHidden See {@link event:tool_usertours/stepHidden}\n */\nexport const eventTypes = {\n /**\n * An event triggered before a user tour step is rendered.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/stepRender\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {object} detail.stepConfig\n */\n stepRender: 'tool_usertours/stepRender',\n\n /**\n * An event triggered after a user tour step has been rendered.\n *\n * @event tool_usertours/stepRendered\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {object} detail.stepConfig\n */\n stepRendered: 'tool_usertours/stepRendered',\n\n /**\n * An event triggered before a user tour starts.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/tourStart\n * @type {CustomEvent}\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @property {Number} detail.startAt\n */\n tourStart: 'tool_usertours/tourStart',\n\n /**\n * An event triggered after a user tour has started.\n *\n * @event tool_usertours/tourStarted\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourStarted: 'tool_usertours/tourStarted',\n\n /**\n * An event triggered before a tour ends.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/tourEnd\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourEnd: 'tool_usertours/tourEnd',\n\n /**\n * An event triggered after a tour has ended.\n *\n * @event tool_usertours/tourEnded\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n tourEnded: 'tool_usertours/tourEnded',\n\n /**\n * An event triggered before a step is hidden.\n *\n * This event is cancellable.\n *\n * @event tool_usertours/stepHide\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n stepHide: 'tool_usertours/stepHide',\n\n /**\n * An event triggered after a step has been hidden.\n *\n * @event tool_usertours/stepHidden\n * @property {object} detail\n * @property {tool_usertours/tour} detail.tour\n * @type {CustomEvent}\n */\n stepHidden: 'tool_usertours/stepHidden',\n};\n"],"file":"events.min.js"} \ No newline at end of file diff --git a/admin/tool/usertours/amd/src/events.js b/admin/tool/usertours/amd/src/events.js index fb897fba2edde..ac6c94ba7ec93 100644 --- a/admin/tool/usertours/amd/src/events.js +++ b/admin/tool/usertours/amd/src/events.js @@ -33,6 +33,7 @@ * Events for the component. * * @constant + * @property {object} eventTypes * @property {String} eventTypes.stepRender See {@link event:tool_usertours/stepRender} * @property {String} eventTypes.stepRendered See {@link event:tool_usertours/stepRendered} * @property {String} eventTypes.tourStart See {@link event:tool_usertours/tourStart} diff --git a/blocks/accessreview/amd/build/module.min.js.map b/blocks/accessreview/amd/build/module.min.js.map index e1e6084fc0778..2129aef26834b 100644 --- a/blocks/accessreview/amd/build/module.min.js.map +++ b/blocks/accessreview/amd/build/module.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/module.js"],"names":["toggleState","renderTemplate","element","errorCount","checkCount","displayFormat","minViews","viewDelta","weight","parseInt","context","resultPassed","classList","passRate","failureRate","Math","round","Promise","resolve","elementClassList","push","showIcons","showBackground","add","join","Templates","renderForPromise","then","html","js","appendNodeContents","catch","showAccessMap","courseId","updatePreference","all","fetchReviewData","sectionData","moduleData","getErrorTotals","forEach","section","document","querySelector","numerrors","numchecks","module","getElementById","cmid","remove","displayError","hideAccessMap","querySelectorAll","node","setToggleStatePreference","toggleAccessMap","totals","totalErrors","totalUsers","maxViews","concat","item","registerEventListeners","addEventListener","e","target","closest","preventDefault","getTogglePreferenceParams","methodname","args","preferences","type","value","courseid","calls","init","toggled"],"mappings":"keAyBA,O,qgDAaIA,CAAAA,CAAW,G,CAYTC,CAAc,CAAG,SAACC,CAAD,CAAUC,CAAV,CAAsBC,CAAtB,CAAkCC,CAAlC,CAAiDC,CAAjD,CAA2DC,CAA3D,CAAyE,IAEtFC,CAAAA,CAAM,CAAGC,QAAQ,CAAC,CAACN,CAAU,CAAGG,CAAd,EAA0BC,CAA1B,EAAD,CAFqE,CAItFG,CAAO,CAAG,CACZC,YAAY,CAAE,CAACR,CADH,CAEZS,SAAS,CAAE,EAFC,CAGZC,QAAQ,CAAE,CACNV,UAAU,CAAVA,CADM,CAENC,UAAU,CAAVA,CAFM,CAGNU,WAAW,CAAEC,IAAI,CAACC,KAAL,CAAqC,GAA1B,EAAAb,CAAU,CAAGC,CAAb,CAAX,CAHP,CAHE,CAJ4E,CAc5F,GAAI,CAACF,CAAL,CAAc,CACV,MAAOe,CAAAA,OAAO,CAACC,OAAR,EACV,CAED,GAAMC,CAAAA,CAAgB,CAAG,CAAC,oBAAD,CAAzB,CACA,GAAIT,CAAO,CAACC,YAAZ,CAA0B,CACtBQ,CAAgB,CAACC,IAAjB,CAAsB,4BAAtB,CACH,CAFD,IAEO,IAAIZ,CAAJ,CAAY,CACfW,CAAgB,CAACC,IAAjB,CAAsB,2BAAtB,CACH,CAFM,IAEA,CACHD,CAAgB,CAACC,IAAjB,CAAsB,4BAAtB,CACH,CAzB2F,GA2BtFC,CAAAA,CAAS,CAAqB,WAAjB,EAAAhB,CAAD,EAAoD,UAAjB,EAAAA,CA3BuC,CA4BtFiB,CAAc,CAAqB,gBAAjB,EAAAjB,CAAD,EAAyD,UAAjB,EAAAA,CA5B6B,CA8B5F,GAAIiB,CAAc,EAAI,CAACD,CAAvB,CAAkC,OAI9B,GAAAnB,CAAO,CAACU,SAAR,EA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CAACqB,gBAAT,CAA0B,OAA1B,CAAmC,SAAAC,CAAC,CAAI,CACpC,GAAIA,CAAC,CAACC,MAAF,CAASC,OAAT,CAAiB,mBAAjB,CAAJ,CAA2C,CACvCF,CAAC,CAACG,cAAF,GACAZ,CAAe,CAACtB,CAAD,CAAW5B,CAAX,CAClB,CACJ,CALD,CAMH,C,CAQK+D,CAAyB,CAAG,SAAApE,CAAW,CAAI,CAC7C,MAAO,CACHqE,UAAU,CAAE,mCADT,CAEHC,IAAI,CAAE,CACFC,WAAW,CAAE,CAAC,CACVC,IAAI,CAAE,+BADI,CAEVC,KAAK,CAAEzE,CAFG,CAAD,CADX,CAFH,CASV,C,CAEKsD,CAAwB,CAAG,SAAAtD,CAAW,QAAI,WAAU,CAACoE,CAAyB,CAACpE,CAAD,CAA1B,CAAV,CAAJ,C,CAStCoC,CAAe,CAAG,SAACsC,CAAD,CAAwC,IAA7BxC,CAAAA,CAA6B,2DACtDyC,CAAK,CAAG,CACV,CACIN,UAAU,CAAE,qCADhB,CAEIC,IAAI,CAAE,CAACI,QAAQ,CAARA,CAAD,CAFV,CADU,CAKV,CACIL,UAAU,CAAE,oCADhB,CAEIC,IAAI,CAAE,CAACI,QAAQ,CAARA,CAAD,CAFV,CALU,CAD8C,CAY5D,GAAIxC,CAAJ,CAAsB,CAClByC,CAAK,CAACvD,IAAN,CAAWgD,CAAyB,IAApC,CACH,CAED,MAAO,WAAUO,CAAV,CACV,C,CASYC,CAAI,CAAG,SAACC,CAAD,CAAUxE,CAAV,CAAyB4B,CAAzB,CAAsC,CAEtDjC,CAAW,CAAc,CAAX,EAAA6E,CAAd,CAEA,GAAI7E,CAAJ,CAAiB,CACbgC,CAAa,CAACC,CAAD,CAAW5B,CAAX,CAChB,CAEDyD,CAAsB,CAAC7B,CAAD,CAAW5B,CAAX,CACzB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Manager for the accessreview block.\n *\n * @module block_accessreview/module\n * @author Max Larkin \n * @copyright 2020 Brickfield Education Labs \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {call as fetchMany} from 'core/ajax';\nimport * as Templates from 'core/templates';\nimport {exception as displayError} from 'core/notification';\n\n/**\n * The number of colours used to represent the heatmap. (Indexed on 0.)\n * @type {number}\n */\nconst numColours = 2;\n\n/**\n * The toggle state of the heatmap.\n * @type {boolean}\n */\nlet toggleState = true;\n\n/**\n * Renders the HTML template onto a particular HTML element.\n * @param {HTMLElement} element The element to attach the HTML to.\n * @param {number} errorCount The number of errors on this module/section.\n * @param {number} checkCount The number of checks triggered on this module/section.\n * @param {String} displayFormat\n * @param {Number} minViews\n * @param {Number} viewDelta\n * @returns {Promise}\n */\nconst renderTemplate = (element, errorCount, checkCount, displayFormat, minViews, viewDelta) => {\n // Calculate a weight?\n const weight = parseInt((errorCount - minViews) / viewDelta * numColours);\n\n const context = {\n resultPassed: !errorCount,\n classList: '',\n passRate: {\n errorCount,\n checkCount,\n failureRate: Math.round(errorCount / checkCount * 100),\n },\n };\n\n if (!element) {\n return Promise.resolve();\n }\n\n const elementClassList = ['block_accessreview'];\n if (context.resultPassed) {\n elementClassList.push('block_accessreview_success');\n } else if (weight) {\n elementClassList.push('block_accessreview_danger');\n } else {\n elementClassList.push('block_accessreview_warning');\n }\n\n const showIcons = (displayFormat == 'showicons') || (displayFormat == 'showboth');\n const showBackground = (displayFormat == 'showbackground') || (displayFormat == 'showboth');\n\n if (showBackground && !showIcons) {\n // Only the background is displayed.\n // No need to display the template.\n // Note: The case where both the background and icons are shown is handled later to avoid jankiness.\n element.classList.add(...elementClassList, 'alert');\n\n return Promise.resolve();\n }\n\n if (showIcons && !showBackground) {\n context.classList = elementClassList.join(' ');\n }\n\n // The icons are displayed either with, or without, the background.\n return Templates.renderForPromise('block_accessreview/status', context)\n .then(({html, js}) => {\n Templates.appendNodeContents(element, html, js);\n\n if (showBackground) {\n element.classList.add(...elementClassList, 'alert');\n }\n\n return;\n })\n .catch();\n};\n\n/**\n * Applies the template to all sections and modules on the course page.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n * @param {Boolean} updatePreference\n * @returns {Promise}\n */\nconst showAccessMap = (courseId, displayFormat, updatePreference = false) => {\n // Get error data.\n return Promise.all(fetchReviewData(courseId, updatePreference))\n .then(([sectionData, moduleData]) => {\n // Get total data.\n const {minViews, viewDelta} = getErrorTotals(sectionData, moduleData);\n\n sectionData.forEach(section => {\n const element = document.querySelector(`#section-${section.section} .summary`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, section.numerrors, section.numchecks, displayFormat, minViews, viewDelta);\n });\n\n moduleData.forEach(module => {\n const element = document.getElementById(`module-${module.cmid}`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, module.numerrors, module.numchecks, displayFormat, minViews, viewDelta);\n });\n\n // Change the icon display.\n document.querySelector('.icon-accessmap').classList.remove(...['fa-eye-slash']);\n document.querySelector('.icon-accessmap').classList.add(...['fa-eye']);\n\n return {\n sectionData,\n moduleData,\n };\n })\n .catch(displayError);\n};\n\n\n/**\n * Hides or removes the templates from the HTML of the current page.\n *\n * @param {Boolean} updatePreference\n */\nconst hideAccessMap = (updatePreference = false) => {\n // Removes the added elements.\n document.querySelectorAll('.block_accessreview_view').forEach(node => node.remove());\n\n const classList = [\n 'block_accessreview',\n 'block_accessreview_success',\n 'block_accessreview_warning',\n 'block_accessreview_danger',\n 'block_accessreview_view',\n 'alert',\n ];\n\n // Removes the added classes.\n document.querySelectorAll('.block_accessreview').forEach(node => node.classList.remove(...classList));\n\n if (updatePreference) {\n setToggleStatePreference(false);\n }\n\n // Change the icon display.\n document.querySelector('.icon-accessmap').classList.remove(...['fa-eye']);\n document.querySelector('.icon-accessmap').classList.add(...['fa-eye-slash']);\n};\n\n\n/**\n * Toggles the heatmap on/off.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n */\nconst toggleAccessMap = (courseId, displayFormat) => {\n toggleState = !toggleState;\n if (!toggleState) {\n hideAccessMap(true);\n } else {\n showAccessMap(courseId, displayFormat, true);\n }\n};\n\n/**\n * Parses information on the errors, generating the min, max and totals.\n *\n * @param {Object[]} sectionData The error data for course sections.\n * @param {Object[]} moduleData The error data for course modules.\n * @returns {Object} An object representing the extra error information.\n*/\nconst getErrorTotals = (sectionData, moduleData) => {\n const totals = {\n totalErrors: 0,\n totalUsers: 0,\n minViews: 0,\n maxViews: 0,\n viewDelta: 0,\n };\n\n [].concat(sectionData, moduleData).forEach(item => {\n totals.totalErrors += item.numerrors;\n if (item.numerrors < totals.minViews) {\n totals.minViews = item.numerrors;\n }\n\n if (item.numerrors > totals.maxViews) {\n totals.maxViews = item.numerrors;\n }\n totals.totalUsers += item.numchecks;\n });\n\n totals.viewDelta = totals.maxViews - totals.minViews + 1;\n\n return totals;\n};\n\nconst registerEventListeners = (courseId, displayFormat) => {\n document.addEventListener('click', e => {\n if (e.target.closest('#toggle-accessmap')) {\n e.preventDefault();\n toggleAccessMap(courseId, displayFormat);\n }\n });\n};\n\n/**\n * Set the user preference for the toggle value.\n *\n * @param {Boolean} toggleState\n * @returns {Promise}\n */\nconst getTogglePreferenceParams = toggleState => {\n return {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [{\n type: 'block_accessreviewtogglestate',\n value: toggleState,\n }],\n }\n };\n};\n\nconst setToggleStatePreference = toggleState => fetchMany([getTogglePreferenceParams(toggleState)]);\n\n/**\n * Fetch the review data.\n *\n * @param {Number} courseid\n * @param {Boolean} updatePreference\n * @returns {Promise[]}\n */\nconst fetchReviewData = (courseid, updatePreference = false) => {\n const calls = [\n {\n methodname: 'block_accessreview_get_section_data',\n args: {courseid}\n },\n {\n methodname: 'block_accessreview_get_module_data',\n args: {courseid}\n },\n ];\n\n if (updatePreference) {\n calls.push(getTogglePreferenceParams(true));\n }\n\n return fetchMany(calls);\n};\n\n/**\n * Setting up the access review module.\n * @param {number} toggled A number represnting the state of the review toggle.\n * @param {string} displayFormat A string representing the display format for icons.\n * @param {number} courseId The course ID.\n * @param {number} userId The id of the currently logged-in user.\n */\nexport const init = (toggled, displayFormat, courseId) => {\n // Settings consts.\n toggleState = toggled == 1;\n\n if (toggleState) {\n showAccessMap(courseId, displayFormat);\n }\n\n registerEventListeners(courseId, displayFormat);\n};\n"],"file":"module.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/module.js"],"names":["toggleState","renderTemplate","element","errorCount","checkCount","displayFormat","minViews","viewDelta","weight","parseInt","context","resultPassed","classList","passRate","failureRate","Math","round","Promise","resolve","elementClassList","push","showIcons","showBackground","add","join","Templates","renderForPromise","then","html","js","appendNodeContents","catch","showAccessMap","courseId","updatePreference","all","fetchReviewData","sectionData","moduleData","getErrorTotals","forEach","section","document","querySelector","numerrors","numchecks","module","getElementById","cmid","remove","displayError","hideAccessMap","querySelectorAll","node","setToggleStatePreference","toggleAccessMap","totals","totalErrors","totalUsers","maxViews","concat","item","registerEventListeners","addEventListener","e","target","closest","preventDefault","getTogglePreferenceParams","methodname","args","preferences","type","value","courseid","calls","init","toggled"],"mappings":"keAyBA,O,qgDAaIA,CAAAA,CAAW,G,CAYTC,CAAc,CAAG,SAACC,CAAD,CAAUC,CAAV,CAAsBC,CAAtB,CAAkCC,CAAlC,CAAiDC,CAAjD,CAA2DC,CAA3D,CAAyE,IAEtFC,CAAAA,CAAM,CAAGC,QAAQ,CAAC,CAACN,CAAU,CAAGG,CAAd,EAA0BC,CAA1B,EAAD,CAFqE,CAItFG,CAAO,CAAG,CACZC,YAAY,CAAE,CAACR,CADH,CAEZS,SAAS,CAAE,EAFC,CAGZC,QAAQ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AAU,CAACoE,CAAyB,CAACpE,CAAD,CAA1B,CAAV,CAAJ,C,CAStCoC,CAAe,CAAG,SAACsC,CAAD,CAAwC,IAA7BxC,CAAAA,CAA6B,2DACtDyC,CAAK,CAAG,CACV,CACIN,UAAU,CAAE,qCADhB,CAEIC,IAAI,CAAE,CAACI,QAAQ,CAARA,CAAD,CAFV,CADU,CAKV,CACIL,UAAU,CAAE,oCADhB,CAEIC,IAAI,CAAE,CAACI,QAAQ,CAARA,CAAD,CAFV,CALU,CAD8C,CAY5D,GAAIxC,CAAJ,CAAsB,CAClByC,CAAK,CAACvD,IAAN,CAAWgD,CAAyB,IAApC,CACH,CAED,MAAO,WAAUO,CAAV,CACV,C,CAQYC,CAAI,CAAG,SAACC,CAAD,CAAUxE,CAAV,CAAyB4B,CAAzB,CAAsC,CAEtDjC,CAAW,CAAc,CAAX,EAAA6E,CAAd,CAEA,GAAI7E,CAAJ,CAAiB,CACbgC,CAAa,CAACC,CAAD,CAAW5B,CAAX,CAChB,CAEDyD,CAAsB,CAAC7B,CAAD,CAAW5B,CAAX,CACzB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Manager for the accessreview block.\n *\n * @module block_accessreview/module\n * @author Max Larkin \n * @copyright 2020 Brickfield Education Labs \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {call as fetchMany} from 'core/ajax';\nimport * as Templates from 'core/templates';\nimport {exception as displayError} from 'core/notification';\n\n/**\n * The number of colours used to represent the heatmap. (Indexed on 0.)\n * @type {number}\n */\nconst numColours = 2;\n\n/**\n * The toggle state of the heatmap.\n * @type {boolean}\n */\nlet toggleState = true;\n\n/**\n * Renders the HTML template onto a particular HTML element.\n * @param {HTMLElement} element The element to attach the HTML to.\n * @param {number} errorCount The number of errors on this module/section.\n * @param {number} checkCount The number of checks triggered on this module/section.\n * @param {String} displayFormat\n * @param {Number} minViews\n * @param {Number} viewDelta\n * @returns {Promise}\n */\nconst renderTemplate = (element, errorCount, checkCount, displayFormat, minViews, viewDelta) => {\n // Calculate a weight?\n const weight = parseInt((errorCount - minViews) / viewDelta * numColours);\n\n const context = {\n resultPassed: !errorCount,\n classList: '',\n passRate: {\n errorCount,\n checkCount,\n failureRate: Math.round(errorCount / checkCount * 100),\n },\n };\n\n if (!element) {\n return Promise.resolve();\n }\n\n const elementClassList = ['block_accessreview'];\n if (context.resultPassed) {\n elementClassList.push('block_accessreview_success');\n } else if (weight) {\n elementClassList.push('block_accessreview_danger');\n } else {\n elementClassList.push('block_accessreview_warning');\n }\n\n const showIcons = (displayFormat == 'showicons') || (displayFormat == 'showboth');\n const showBackground = (displayFormat == 'showbackground') || (displayFormat == 'showboth');\n\n if (showBackground && !showIcons) {\n // Only the background is displayed.\n // No need to display the template.\n // Note: The case where both the background and icons are shown is handled later to avoid jankiness.\n element.classList.add(...elementClassList, 'alert');\n\n return Promise.resolve();\n }\n\n if (showIcons && !showBackground) {\n context.classList = elementClassList.join(' ');\n }\n\n // The icons are displayed either with, or without, the background.\n return Templates.renderForPromise('block_accessreview/status', context)\n .then(({html, js}) => {\n Templates.appendNodeContents(element, html, js);\n\n if (showBackground) {\n element.classList.add(...elementClassList, 'alert');\n }\n\n return;\n })\n .catch();\n};\n\n/**\n * Applies the template to all sections and modules on the course page.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n * @param {Boolean} updatePreference\n * @returns {Promise}\n */\nconst showAccessMap = (courseId, displayFormat, updatePreference = false) => {\n // Get error data.\n return Promise.all(fetchReviewData(courseId, updatePreference))\n .then(([sectionData, moduleData]) => {\n // Get total data.\n const {minViews, viewDelta} = getErrorTotals(sectionData, moduleData);\n\n sectionData.forEach(section => {\n const element = document.querySelector(`#section-${section.section} .summary`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, section.numerrors, section.numchecks, displayFormat, minViews, viewDelta);\n });\n\n moduleData.forEach(module => {\n const element = document.getElementById(`module-${module.cmid}`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, module.numerrors, module.numchecks, displayFormat, minViews, viewDelta);\n });\n\n // Change the icon display.\n document.querySelector('.icon-accessmap').classList.remove(...['fa-eye-slash']);\n document.querySelector('.icon-accessmap').classList.add(...['fa-eye']);\n\n return {\n sectionData,\n moduleData,\n };\n })\n .catch(displayError);\n};\n\n\n/**\n * Hides or removes the templates from the HTML of the current page.\n *\n * @param {Boolean} updatePreference\n */\nconst hideAccessMap = (updatePreference = false) => {\n // Removes the added elements.\n document.querySelectorAll('.block_accessreview_view').forEach(node => node.remove());\n\n const classList = [\n 'block_accessreview',\n 'block_accessreview_success',\n 'block_accessreview_warning',\n 'block_accessreview_danger',\n 'block_accessreview_view',\n 'alert',\n ];\n\n // Removes the added classes.\n document.querySelectorAll('.block_accessreview').forEach(node => node.classList.remove(...classList));\n\n if (updatePreference) {\n setToggleStatePreference(false);\n }\n\n // Change the icon display.\n document.querySelector('.icon-accessmap').classList.remove(...['fa-eye']);\n document.querySelector('.icon-accessmap').classList.add(...['fa-eye-slash']);\n};\n\n\n/**\n * Toggles the heatmap on/off.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n */\nconst toggleAccessMap = (courseId, displayFormat) => {\n toggleState = !toggleState;\n if (!toggleState) {\n hideAccessMap(true);\n } else {\n showAccessMap(courseId, displayFormat, true);\n }\n};\n\n/**\n * Parses information on the errors, generating the min, max and totals.\n *\n * @param {Object[]} sectionData The error data for course sections.\n * @param {Object[]} moduleData The error data for course modules.\n * @returns {Object} An object representing the extra error information.\n */\nconst getErrorTotals = (sectionData, moduleData) => {\n const totals = {\n totalErrors: 0,\n totalUsers: 0,\n minViews: 0,\n maxViews: 0,\n viewDelta: 0,\n };\n\n [].concat(sectionData, moduleData).forEach(item => {\n totals.totalErrors += item.numerrors;\n if (item.numerrors < totals.minViews) {\n totals.minViews = item.numerrors;\n }\n\n if (item.numerrors > totals.maxViews) {\n totals.maxViews = item.numerrors;\n }\n totals.totalUsers += item.numchecks;\n });\n\n totals.viewDelta = totals.maxViews - totals.minViews + 1;\n\n return totals;\n};\n\nconst registerEventListeners = (courseId, displayFormat) => {\n document.addEventListener('click', e => {\n if (e.target.closest('#toggle-accessmap')) {\n e.preventDefault();\n toggleAccessMap(courseId, displayFormat);\n }\n });\n};\n\n/**\n * Set the user preference for the toggle value.\n *\n * @param {Boolean} toggleState\n * @returns {Promise}\n */\nconst getTogglePreferenceParams = toggleState => {\n return {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [{\n type: 'block_accessreviewtogglestate',\n value: toggleState,\n }],\n }\n };\n};\n\nconst setToggleStatePreference = toggleState => fetchMany([getTogglePreferenceParams(toggleState)]);\n\n/**\n * Fetch the review data.\n *\n * @param {Number} courseid\n * @param {Boolean} updatePreference\n * @returns {Promise[]}\n */\nconst fetchReviewData = (courseid, updatePreference = false) => {\n const calls = [\n {\n methodname: 'block_accessreview_get_section_data',\n args: {courseid}\n },\n {\n methodname: 'block_accessreview_get_module_data',\n args: {courseid}\n },\n ];\n\n if (updatePreference) {\n calls.push(getTogglePreferenceParams(true));\n }\n\n return fetchMany(calls);\n};\n\n/**\n * Setting up the access review module.\n * @param {number} toggled A number represnting the state of the review toggle.\n * @param {string} displayFormat A string representing the display format for icons.\n * @param {number} courseId The course ID.\n */\nexport const init = (toggled, displayFormat, courseId) => {\n // Settings consts.\n toggleState = toggled == 1;\n\n if (toggleState) {\n showAccessMap(courseId, displayFormat);\n }\n\n registerEventListeners(courseId, displayFormat);\n};\n"],"file":"module.min.js"} \ No newline at end of file diff --git a/blocks/accessreview/amd/src/module.js b/blocks/accessreview/amd/src/module.js index 58360bdcb43e2..6f9fc1858c19a 100644 --- a/blocks/accessreview/amd/src/module.js +++ b/blocks/accessreview/amd/src/module.js @@ -203,7 +203,7 @@ const toggleAccessMap = (courseId, displayFormat) => { * @param {Object[]} sectionData The error data for course sections. * @param {Object[]} moduleData The error data for course modules. * @returns {Object} An object representing the extra error information. -*/ + */ const getErrorTotals = (sectionData, moduleData) => { const totals = { totalErrors: 0, @@ -290,7 +290,6 @@ const fetchReviewData = (courseid, updatePreference = false) => { * @param {number} toggled A number represnting the state of the review toggle. * @param {string} displayFormat A string representing the display format for icons. * @param {number} courseId The course ID. - * @param {number} userId The id of the currently logged-in user. */ export const init = (toggled, displayFormat, courseId) => { // Settings consts. diff --git a/calendar/amd/build/month_navigation_drag_drop.min.js.map b/calendar/amd/build/month_navigation_drag_drop.min.js.map index fcca9e5d45fb3..3bbc5f3cb11d2 100644 --- a/calendar/amd/build/month_navigation_drag_drop.min.js.map +++ b/calendar/amd/build/month_navigation_drag_drop.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/month_navigation_drag_drop.js"],"names":["define","$","DataStore","SELECTORS","DRAGGABLE","DROP_ZONE","HOVER_CLASS","TARGET_CLASS","registered","hoverTimer","root","updateHoverState","target","hovered","addClass","removeClass","addDropZoneIndicator","find","removeDropZoneIndicator","getTargetFromEvent","e","closest","length","dragstartHandler","eventElement","dragoverHandler","hasEventId","preventDefault","setTimeout","click","dragleaveHandler","clearTimeout","dropHandler","init","rootElement","document","addEventListener"],"mappings":"AA2BAA,OAAM,4CAAC,CACK,QADL,CAEK,oCAFL,CAAD,CAIE,SACIC,CADJ,CAEIC,CAFJ,CAGE,IAEFC,CAAAA,CAAS,CAAG,CACZC,SAAS,CAAE,kDADC,CAEZC,SAAS,CAAE,+BAFC,CAFV,CAMFC,CAAW,CAAG,uBANZ,CAOFC,CAAY,CAAG,aAPb,CAeFC,CAAU,GAfR,CAiBFC,CAAU,CAAG,IAjBX,CAmBFC,CAAI,CAAG,I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AIDE,CAAI,CAAGT,CAAC,CAACiC,CAAD,CAAR,CAGA,GAAIhC,CAAS,CAACwB,UAAV,EAAJ,CAA4B,CACxBV,CAAoB,EACvB,CACJ,CA7BE,CA+BV,CA9MK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A javascript module to handle calendar drag and drop in the calendar\n * month view navigation.\n *\n * This code is run each time the calendar month view is re-rendered. We\n * only register the event handlers once per page load so that the in place\n * DOM updates that happen on month change don't continue to register handlers.\n *\n * @module core_calendar/month_navigation_drag_drop\n * @copyright 2017 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core_calendar/drag_drop_data_store',\n ],\n function(\n $,\n DataStore\n ) {\n\n var SELECTORS = {\n DRAGGABLE: '[draggable=\"true\"][data-region=\"event-item\"]',\n DROP_ZONE: '[data-drop-zone=\"nav-link\"]',\n };\n var HOVER_CLASS = 'bg-primary text-white';\n var TARGET_CLASS = 'drop-target';\n var HOVER_TIME = 1000; // 1 second hover to change month.\n\n // We store some static variables at the module level because this\n // module is called each time the calendar month view is reloaded but\n // we want some actions to only occur ones.\n\n /* @var {bool} registered If the event listeners have been added */\n var registered = false;\n /* @var {int} hoverTimer The timeout id of any timeout waiting for hover */\n var hoverTimer = null;\n /* @var {object} root The root nav element we're operating on */\n var root = null;\n\n /**\n * Add or remove the appropriate styling to indicate whether\n * the drop target is being hovered over.\n *\n * @param {object} target The target drop zone element\n * @param {bool} hovered If the element is hovered over ot not\n */\n var updateHoverState = function(target, hovered) {\n if (hovered) {\n target.addClass(HOVER_CLASS);\n } else {\n target.removeClass(HOVER_CLASS);\n }\n };\n\n /**\n * Add some styling to the UI to indicate that the nav links\n * are an acceptable drop target.\n */\n var addDropZoneIndicator = function() {\n root.find(SELECTORS.DROP_ZONE).addClass(TARGET_CLASS);\n };\n\n /**\n * Remove the styling from the nav links.\n */\n var removeDropZoneIndicator = function() {\n root.find(SELECTORS.DROP_ZONE).removeClass(TARGET_CLASS);\n };\n\n /**\n * Get the drop zone target from the event, if one is found.\n *\n * @param {event} e Javascript event\n * @return {object|null}\n */\n var getTargetFromEvent = function(e) {\n var target = $(e.target).closest(SELECTORS.DROP_ZONE);\n return (target.length) ? target : null;\n };\n\n /**\n * This will add a visual indicator to the calendar UI to\n * indicate which nav link is a valid drop zone.\n */\n var dragstartHandler = function(e) {\n // Make sure the drag event is for a calendar event.\n var eventElement = $(e.target).closest(SELECTORS.DRAGGABLE);\n\n if (eventElement.length) {\n addDropZoneIndicator();\n }\n };\n\n /**\n * Update the hover state of the target nav element when\n * the user is dragging an event over it.\n *\n * This will add a visual indicator to the calendar UI to\n * indicate which nav link is being hovered.\n *\n * @param {event} e The dragover event\n */\n var dragoverHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n e.preventDefault();\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n // If we're not draggin a calendar event then\n // ignore it.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n if (!hoverTimer) {\n hoverTimer = setTimeout(function() {\n target.click();\n hoverTimer = null;\n }, HOVER_TIME);\n }\n\n updateHoverState(target, true);\n removeDropZoneIndicator();\n };\n\n /**\n * Update the hover state of the target nav element that was\n * previously dragged over but has is no longer a drag target.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dragleaveHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n if (hoverTimer) {\n clearTimeout(hoverTimer);\n hoverTimer = null;\n }\n\n updateHoverState(target, false);\n addDropZoneIndicator();\n e.preventDefault();\n };\n\n /**\n * Remove the visual indicator from the calendar UI that was\n * added by the dragoverHandler.\n *\n * @param {event} e The drop event\n */\n var dropHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n removeDropZoneIndicator();\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n updateHoverState(target, false);\n e.preventDefault();\n };\n\n return {\n /**\n * Initialise the event handlers for the drag events.\n *\n * @param {object} rootElement The element containing calendar nav links\n */\n init: function(rootElement) {\n // Only register the handlers once on the first load.\n if (!registered) {\n // These handlers are only added the first time the module\n // is loaded because we don't want to have a new listener\n // added each time the \"init\" function is called otherwise we'll\n // end up with lots of stale handlers.\n document.addEventListener('dragstart', dragstartHandler, false);\n document.addEventListener('dragover', dragoverHandler, false);\n document.addEventListener('dragleave', dragleaveHandler, false);\n document.addEventListener('drop', dropHandler, false);\n document.addEventListener('dragend', removeDropZoneIndicator, false);\n registered = true;\n }\n\n // Update the module variable to operate on the given\n // root element.\n root = $(rootElement);\n\n // If we're currently dragging then add the indicators.\n if (DataStore.hasEventId()) {\n addDropZoneIndicator();\n }\n },\n };\n});\n"],"file":"month_navigation_drag_drop.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/month_navigation_drag_drop.js"],"names":["define","$","DataStore","SELECTORS","DRAGGABLE","DROP_ZONE","HOVER_CLASS","TARGET_CLASS","registered","hoverTimer","root","updateHoverState","target","hovered","addClass","removeClass","addDropZoneIndicator","find","removeDropZoneIndicator","getTargetFromEvent","e","closest","length","dragstartHandler","eventElement","dragoverHandler","hasEventId","preventDefault","setTimeout","click","dragleaveHandler","clearTimeout","dropHandler","init","rootElement","document","addEventListener"],"mappings":"AA2BAA,OAAM,4CAAC,CACK,QADL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B,CAAuCb,CAAvC,KACAY,QAAQ,CAACC,gBAAT,CAA0B,UAA1B,CAAsCX,CAAtC,KACAU,QAAQ,CAACC,gBAAT,CAA0B,WAA1B,CAAuCN,CAAvC,KACAK,QAAQ,CAACC,gBAAT,CAA0B,MAA1B,CAAkCJ,CAAlC,KACAG,QAAQ,CAACC,gBAAT,CAA0B,SAA1B,CAAqClB,CAArC,KACAV,CAAU,GACb,CAIDE,CAAI,CAAGT,CAAC,CAACiC,CAAD,CAAR,CAGA,GAAIhC,CAAS,CAACwB,UAAV,EAAJ,CAA4B,CACxBV,CAAoB,EACvB,CACJ,CA7BE,CA+BV,CAhNK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A javascript module to handle calendar drag and drop in the calendar\n * month view navigation.\n *\n * This code is run each time the calendar month view is re-rendered. We\n * only register the event handlers once per page load so that the in place\n * DOM updates that happen on month change don't continue to register handlers.\n *\n * @module core_calendar/month_navigation_drag_drop\n * @copyright 2017 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core_calendar/drag_drop_data_store',\n ],\n function(\n $,\n DataStore\n ) {\n\n var SELECTORS = {\n DRAGGABLE: '[draggable=\"true\"][data-region=\"event-item\"]',\n DROP_ZONE: '[data-drop-zone=\"nav-link\"]',\n };\n var HOVER_CLASS = 'bg-primary text-white';\n var TARGET_CLASS = 'drop-target';\n var HOVER_TIME = 1000; // 1 second hover to change month.\n\n // We store some static variables at the module level because this\n // module is called each time the calendar month view is reloaded but\n // we want some actions to only occur ones.\n\n /* @var {bool} registered If the event listeners have been added */\n var registered = false;\n /* @var {int} hoverTimer The timeout id of any timeout waiting for hover */\n var hoverTimer = null;\n /* @var {object} root The root nav element we're operating on */\n var root = null;\n\n /**\n * Add or remove the appropriate styling to indicate whether\n * the drop target is being hovered over.\n *\n * @param {object} target The target drop zone element\n * @param {bool} hovered If the element is hovered over ot not\n */\n var updateHoverState = function(target, hovered) {\n if (hovered) {\n target.addClass(HOVER_CLASS);\n } else {\n target.removeClass(HOVER_CLASS);\n }\n };\n\n /**\n * Add some styling to the UI to indicate that the nav links\n * are an acceptable drop target.\n */\n var addDropZoneIndicator = function() {\n root.find(SELECTORS.DROP_ZONE).addClass(TARGET_CLASS);\n };\n\n /**\n * Remove the styling from the nav links.\n */\n var removeDropZoneIndicator = function() {\n root.find(SELECTORS.DROP_ZONE).removeClass(TARGET_CLASS);\n };\n\n /**\n * Get the drop zone target from the event, if one is found.\n *\n * @param {event} e Javascript event\n * @return {object|null}\n */\n var getTargetFromEvent = function(e) {\n var target = $(e.target).closest(SELECTORS.DROP_ZONE);\n return (target.length) ? target : null;\n };\n\n /**\n * This will add a visual indicator to the calendar UI to\n * indicate which nav link is a valid drop zone.\n *\n * @param {Event} e\n */\n var dragstartHandler = function(e) {\n // Make sure the drag event is for a calendar event.\n var eventElement = $(e.target).closest(SELECTORS.DRAGGABLE);\n\n if (eventElement.length) {\n addDropZoneIndicator();\n }\n };\n\n /**\n * Update the hover state of the target nav element when\n * the user is dragging an event over it.\n *\n * This will add a visual indicator to the calendar UI to\n * indicate which nav link is being hovered.\n *\n * @param {event} e The dragover event\n */\n var dragoverHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n e.preventDefault();\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n // If we're not draggin a calendar event then\n // ignore it.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n if (!hoverTimer) {\n hoverTimer = setTimeout(function() {\n target.click();\n hoverTimer = null;\n }, HOVER_TIME);\n }\n\n updateHoverState(target, true);\n removeDropZoneIndicator();\n };\n\n /**\n * Update the hover state of the target nav element that was\n * previously dragged over but has is no longer a drag target.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dragleaveHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n if (hoverTimer) {\n clearTimeout(hoverTimer);\n hoverTimer = null;\n }\n\n updateHoverState(target, false);\n addDropZoneIndicator();\n e.preventDefault();\n };\n\n /**\n * Remove the visual indicator from the calendar UI that was\n * added by the dragoverHandler.\n *\n * @param {event} e The drop event\n */\n var dropHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n removeDropZoneIndicator();\n var target = getTargetFromEvent(e);\n\n if (!target) {\n return;\n }\n\n updateHoverState(target, false);\n e.preventDefault();\n };\n\n return {\n /**\n * Initialise the event handlers for the drag events.\n *\n * @param {object} rootElement The element containing calendar nav links\n */\n init: function(rootElement) {\n // Only register the handlers once on the first load.\n if (!registered) {\n // These handlers are only added the first time the module\n // is loaded because we don't want to have a new listener\n // added each time the \"init\" function is called otherwise we'll\n // end up with lots of stale handlers.\n document.addEventListener('dragstart', dragstartHandler, false);\n document.addEventListener('dragover', dragoverHandler, false);\n document.addEventListener('dragleave', dragleaveHandler, false);\n document.addEventListener('drop', dropHandler, false);\n document.addEventListener('dragend', removeDropZoneIndicator, false);\n registered = true;\n }\n\n // Update the module variable to operate on the given\n // root element.\n root = $(rootElement);\n\n // If we're currently dragging then add the indicators.\n if (DataStore.hasEventId()) {\n addDropZoneIndicator();\n }\n },\n };\n});\n"],"file":"month_navigation_drag_drop.min.js"} \ No newline at end of file diff --git a/calendar/amd/build/month_view_drag_drop.min.js.map b/calendar/amd/build/month_view_drag_drop.min.js.map index ef439dbbd148d..7e914a31f8a5f 100644 --- a/calendar/amd/build/month_view_drag_drop.min.js.map +++ b/calendar/amd/build/month_view_drag_drop.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/month_view_drag_drop.js"],"names":["define","$","Notification","Str","CalendarEvents","DataStore","SELECTORS","ROOT","DRAGGABLE","DROP_ZONE","WEEK","INVALID_DROP_ZONE_CLASS","INVALID_HOVER_CLASS","VALID_HOVER_CLASS","ALL_CLASSES","registered","getDropZoneFromEvent","e","dropZone","target","closest","length","isValidDropZone","dropTimestamp","attr","minTimestart","getMinTimestart","maxTimestart","getMaxTimestart","getDropZoneError","getMinError","getMaxError","clearAllDropZonesState","find","each","index","removeClass","updateHoverState","hovered","count","getDurationDays","valid","addClass","nextDropZone","next","nextWeek","children","first","updateAllDropZonesState","dragstartHandler","draggableElement","eventElement","eventId","minError","maxError","eventsSelector","duration","setEventId","setDurationDays","setMinTimestart","setMaxTimestart","setMinError","setMaxError","dataTransfer","effectAllowed","dropEffect","setData","dragoverHandler","hasEventId","preventDefault","dragleaveHandler","dropHandler","clearAll","getEventId","eventElementSelector","origin","trigger","moveEvent","message","get_string","then","string","exception","name","dragendHandler","calendarMonthChangedHandler","init","document","addEventListener","on","monthChanged"],"mappings":"AAuBAA,OAAM,sCAAC,CACK,QADL,CAEK,mBAFL,CAGK,UAHL,CAIK,sBAJL,CAKK,oCALL,CAAD,CAOE,SACIC,CADJ,CAEIC,CAFJ,CAGIC,CAHJ,CAIIC,CAJJ,CAKIC,CALJ,CAME,IAEFC,CAAAA,CAAS,CAAG,CACZC,IAAI,CAAE,0BADM,CAEZC,SAAS,CAAE,kDAFC,CAGZC,SAAS,CAAE,qCAHC,CAIZC,IAAI,CAAE,mCAJM,CAFV,CAQFC,CAAuB,CAAG,UARxB,CASFC,CAAmB,CAAG,sBATpB,CAUFC,CAAiB,CAAG,uBAVlB,CAWFC,CAAW,CAAGH,CAAuB,CAAG,GAA1B,CAAgCC,CA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,MAAO,CAIHsC,IAAI,CAAE,eAAW,CACb,GAAI,CAACvE,CAAL,CAAiB,CAKbwE,QAAQ,CAACC,gBAAT,CAA0B,WAA1B,CAAuCvC,CAAvC,KACAsC,QAAQ,CAACC,gBAAT,CAA0B,UAA1B,CAAsCrB,CAAtC,KACAoB,QAAQ,CAACC,gBAAT,CAA0B,WAA1B,CAAuClB,CAAvC,KACAiB,QAAQ,CAACC,gBAAT,CAA0B,MAA1B,CAAkCjB,CAAlC,KACAgB,QAAQ,CAACC,gBAAT,CAA0B,SAA1B,CAAqCJ,CAArC,KACAnF,CAAC,CAAC,MAAD,CAAD,CAAUwF,EAAV,CAAarF,CAAc,CAACsF,YAA5B,CAA0CL,CAA1C,EACAtE,CAAU,GACb,CACJ,CAlBE,CAoBV,CA3XK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A javascript module to handle calendar drag and drop in the calendar\n * month view.\n *\n * @module core_calendar/month_view_drag_drop\n * @copyright 2017 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/notification',\n 'core/str',\n 'core_calendar/events',\n 'core_calendar/drag_drop_data_store'\n ],\n function(\n $,\n Notification,\n Str,\n CalendarEvents,\n DataStore\n ) {\n\n var SELECTORS = {\n ROOT: \"[data-region='calendar']\",\n DRAGGABLE: '[draggable=\"true\"][data-region=\"event-item\"]',\n DROP_ZONE: '[data-drop-zone=\"month-view-day\"]',\n WEEK: '[data-region=\"month-view-week\"]',\n };\n var INVALID_DROP_ZONE_CLASS = 'bg-faded';\n var INVALID_HOVER_CLASS = 'bg-danger text-white';\n var VALID_HOVER_CLASS = 'bg-primary text-white';\n var ALL_CLASSES = INVALID_DROP_ZONE_CLASS + ' ' + INVALID_HOVER_CLASS + ' ' + VALID_HOVER_CLASS;\n /* @var {bool} registered If the event listeners have been added */\n var registered = false;\n\n /**\n * Get the correct drop zone element from the given javascript\n * event.\n *\n * @param {event} e The javascript event\n * @return {object|null}\n */\n var getDropZoneFromEvent = function(e) {\n var dropZone = $(e.target).closest(SELECTORS.DROP_ZONE);\n return (dropZone.length) ? dropZone : null;\n };\n\n /**\n * Determine if the given dropzone element is within the acceptable\n * time range.\n *\n * The drop zone timestamp is midnight on that day so we should check\n * that the event's acceptable timestart value\n *\n * @param {object} dropZone The drop zone day from the calendar\n * @return {bool}\n */\n var isValidDropZone = function(dropZone) {\n var dropTimestamp = dropZone.attr('data-day-timestamp');\n var minTimestart = DataStore.getMinTimestart();\n var maxTimestart = DataStore.getMaxTimestart();\n\n if (minTimestart && minTimestart > dropTimestamp) {\n return false;\n }\n\n if (maxTimestart && maxTimestart < dropTimestamp) {\n return false;\n }\n\n return true;\n };\n\n /**\n * Get the error string to display for a given drop zone element\n * if it is invalid.\n *\n * @param {object} dropZone The drop zone day from the calendar\n * @return {string}\n */\n var getDropZoneError = function(dropZone) {\n var dropTimestamp = dropZone.attr('data-day-timestamp');\n var minTimestart = DataStore.getMinTimestart();\n var maxTimestart = DataStore.getMaxTimestart();\n\n if (minTimestart && minTimestart > dropTimestamp) {\n return DataStore.getMinError();\n }\n\n if (maxTimestart && maxTimestart < dropTimestamp) {\n return DataStore.getMaxError();\n }\n\n return null;\n };\n\n /**\n * Remove all of the styling from each of the drop zones in the calendar.\n */\n var clearAllDropZonesState = function() {\n $(SELECTORS.ROOT).find(SELECTORS.DROP_ZONE).each(function(index, dropZone) {\n dropZone = $(dropZone);\n dropZone.removeClass(ALL_CLASSES);\n });\n };\n\n /**\n * Update the hover state for the event in the calendar to reflect\n * which days the event will be moved to.\n *\n * If the drop zone is not being hovered then it will apply some\n * styling to reflect whether the drop zone is a valid or invalid\n * drop place for the current dragging event.\n *\n * This funciton supports events spanning multiple days and will\n * recurse to highlight (or remove highlight) each of the days\n * that the event will be moved to.\n *\n * For example: An event with a duration of 3 days will have\n * 3 days highlighted when it's dragged elsewhere in the calendar.\n * The current drag target and the 2 days following it (including\n * wrapping to the next week if necessary).\n *\n * @param {string|object} target The drag target element\n * @param {bool} hovered If the target is hovered or not\n * @param {int} count How many days to highlight (default to duration)\n */\n var updateHoverState = function(dropZone, hovered, count) {\n if (typeof count === 'undefined') {\n // This is how many days we need to highlight.\n count = DataStore.getDurationDays();\n }\n\n var valid = isValidDropZone(dropZone);\n dropZone.removeClass(ALL_CLASSES);\n\n if (hovered) {\n\n if (valid) {\n dropZone.addClass(VALID_HOVER_CLASS);\n } else {\n dropZone.addClass(INVALID_HOVER_CLASS);\n }\n } else {\n dropZone.removeClass(VALID_HOVER_CLASS + ' ' + INVALID_HOVER_CLASS);\n\n if (!valid) {\n dropZone.addClass(INVALID_DROP_ZONE_CLASS);\n }\n }\n\n count--;\n\n // If we've still got days to highlight then we should\n // find the next day.\n if (count > 0) {\n var nextDropZone = dropZone.next();\n\n // If there are no more days in this week then we\n // need to move down to the next week in the calendar.\n if (!nextDropZone.length) {\n var nextWeek = dropZone.closest(SELECTORS.WEEK).next();\n\n if (nextWeek.length) {\n nextDropZone = nextWeek.children(SELECTORS.DROP_ZONE).first();\n }\n }\n\n // If we found another day then let's recursively\n // update it's hover state.\n if (nextDropZone.length) {\n updateHoverState(nextDropZone, hovered, count);\n }\n }\n };\n\n /**\n * Find all of the calendar event drop zones in the calendar and update the display\n * for the user to indicate which zones are valid and invalid.\n */\n var updateAllDropZonesState = function() {\n $(SELECTORS.ROOT).find(SELECTORS.DROP_ZONE).each(function(index, dropZone) {\n dropZone = $(dropZone);\n\n if (!isValidDropZone(dropZone)) {\n updateHoverState(dropZone, false);\n }\n });\n };\n\n\n /**\n * Set up the module level variables to track which event is being\n * dragged and how many days it spans.\n *\n * @param {event} e The dragstart event\n */\n var dragstartHandler = function(e) {\n var target = $(e.target);\n var draggableElement = target.closest(SELECTORS.DRAGGABLE);\n\n if (!draggableElement.length) {\n return;\n }\n\n var eventElement = draggableElement.find('[data-event-id]');\n var eventId = eventElement.attr('data-event-id');\n var minTimestart = draggableElement.attr('data-min-day-timestamp');\n var maxTimestart = draggableElement.attr('data-max-day-timestamp');\n var minError = draggableElement.attr('data-min-day-error');\n var maxError = draggableElement.attr('data-max-day-error');\n var eventsSelector = SELECTORS.ROOT + ' [data-event-id=\"' + eventId + '\"]';\n var duration = $(eventsSelector).length;\n\n DataStore.setEventId(eventId);\n DataStore.setDurationDays(duration);\n\n if (minTimestart) {\n DataStore.setMinTimestart(minTimestart);\n }\n\n if (maxTimestart) {\n DataStore.setMaxTimestart(maxTimestart);\n }\n\n if (minError) {\n DataStore.setMinError(minError);\n }\n\n if (maxError) {\n DataStore.setMaxError(maxError);\n }\n\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.dropEffect = \"move\";\n // Firefox requires a value to be set here or the drag won't\n // work and the dragover handler won't fire.\n e.dataTransfer.setData('text/plain', eventId);\n e.dropEffect = \"move\";\n\n updateAllDropZonesState();\n };\n\n /**\n * Update the hover state of the target day element when\n * the user is dragging an event over it.\n *\n * This will add a visual indicator to the calendar UI to\n * indicate which day(s) the event will be moved to.\n *\n * @param {event} e The dragstart event\n */\n var dragoverHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n e.preventDefault();\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n return;\n }\n\n updateHoverState(dropZone, true);\n };\n\n /**\n * Update the hover state of the target day element that was\n * previously dragged over but has is no longer a drag target.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dragleaveHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n return;\n }\n\n updateHoverState(dropZone, false);\n e.preventDefault();\n };\n\n /**\n * Determines the event element, origin day, and destination day\n * once the user drops the calendar event. These three bits of data\n * are provided as the payload to the \"moveEvent\" calendar javascript\n * event that is fired.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dropHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n DataStore.clearAll();\n clearAllDropZonesState();\n return;\n }\n\n if (isValidDropZone(dropZone)) {\n var eventId = DataStore.getEventId();\n var eventElementSelector = SELECTORS.ROOT + ' [data-event-id=\"' + eventId + '\"]';\n var eventElement = $(eventElementSelector);\n var origin = null;\n\n if (eventElement.length) {\n origin = eventElement.closest(SELECTORS.DROP_ZONE);\n }\n\n $('body').trigger(CalendarEvents.moveEvent, [eventId, origin, dropZone]);\n } else {\n // If the drop zone is not valid then there is not need for us to\n // try to process it. Instead we can just show an error to the user.\n var message = getDropZoneError(dropZone);\n Str.get_string('errorinvaliddate', 'calendar').then(function(string) {\n Notification.exception({\n name: string,\n message: message || string\n });\n });\n }\n\n DataStore.clearAll();\n clearAllDropZonesState();\n\n e.preventDefault();\n };\n\n /**\n * Clear the data store and remove the drag indicators from the UI\n * when the drag event has finished.\n */\n var dragendHandler = function() {\n DataStore.clearAll();\n clearAllDropZonesState();\n };\n\n /**\n * Re-render the drop zones in the new month to highlight\n * which areas are or aren't acceptable to drop the calendar\n * event.\n */\n var calendarMonthChangedHandler = function() {\n updateAllDropZonesState();\n };\n\n return {\n /**\n * Initialise the event handlers for the drag events.\n */\n init: function() {\n if (!registered) {\n // These handlers are only added the first time the module\n // is loaded because we don't want to have a new listener\n // added each time the \"init\" function is called otherwise we'll\n // end up with lots of stale handlers.\n document.addEventListener('dragstart', dragstartHandler, false);\n document.addEventListener('dragover', dragoverHandler, false);\n document.addEventListener('dragleave', dragleaveHandler, false);\n document.addEventListener('drop', dropHandler, false);\n document.addEventListener('dragend', dragendHandler, false);\n $('body').on(CalendarEvents.monthChanged, calendarMonthChangedHandler);\n registered = true;\n }\n },\n };\n});\n"],"file":"month_view_drag_drop.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/month_view_drag_drop.js"],"names":["define","$","Notification","Str","CalendarEvents","DataStore","SELECTORS","ROOT","DRAGGABLE","DROP_ZONE","WEEK","INVALID_DROP_ZONE_CLASS","INVALID_HOVER_CLASS","VALID_HOVER_CLASS","ALL_CLASSES","registered","getDropZoneFromEvent","e","dropZone","target","closest","length","isValidDropZone","dropTimestamp","attr","minTimestart","getMinTimestart","maxTimestart","getMaxTimestart","getDropZoneError","getMinError","getMaxError","clearAllDropZonesState","find","each","index","removeClass","updateHoverState","hovered","count","getDurationDays","valid","addClass","nextDropZone","next","nextWeek","children","first","updateAllDropZonesState","dragstartHandler","draggableElement","eventElement","eventId","minError","maxError","eventsSelector","duration","setEventId","setDurationDays","setMinTimestart","setMaxTimestart","setMinError","setMaxError","dataTransfer","effectAllowed","dropEffect","setData","dragoverHandler","hasEventId","preventDefault","dragleaveHandler","dropHandler","clearAll","getEventId","eventElementSelector","origin","trigger","moveEvent","message","get_string","then","string","exception","name","dragendHandler","calendarMonthChangedHandler","init","document","addEventListener","on","monthChanged"],"mappings":"AAuBAA,OAAM,sCAAC,CACK,QADL,CAEK,mBAFL,CAGK,UAHL,CAIK,sBAJL,CAKK,oCALL,CAAD,CAOE,SACIC,CADJ,CAEIC,CAFJ,CAGIC,CAHJ,CAIIC,CAJJ,CAKIC,CALJ,CAME,IAEFC,CAAAA,CAAS,CAAG,CACZC,IAAI,CAAE,0BADM,CAEZC,SAAS,CAAE,kDAFC,CAGZC,SAAS,CAAE,qCAHC,CAIZC,IAAI,CAAE,mCAJM,CAF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c,CAAG,UAAW,CAC5B/E,CAAS,CAACmE,QAAV,GACAxC,CAAsB,EACzB,CA/UK,CAsVFqD,CAA2B,CAAG,UAAW,CACzCrC,CAAuB,EAC1B,CAxVK,CA0VN,MAAO,CAIHsC,IAAI,CAAE,eAAW,CACb,GAAI,CAACvE,CAAL,CAAiB,CAKbwE,QAAQ,CAACC,gBAAT,CAA0B,WAA1B,CAAuCvC,CAAvC,KACAsC,QAAQ,CAACC,gBAAT,CAA0B,UAA1B,CAAsCrB,CAAtC,KACAoB,QAAQ,CAACC,gBAAT,CAA0B,WAA1B,CAAuClB,CAAvC,KACAiB,QAAQ,CAACC,gBAAT,CAA0B,MAA1B,CAAkCjB,CAAlC,KACAgB,QAAQ,CAACC,gBAAT,CAA0B,SAA1B,CAAqCJ,CAArC,KACAnF,CAAC,CAAC,MAAD,CAAD,CAAUwF,EAAV,CAAarF,CAAc,CAACsF,YAA5B,CAA0CL,CAA1C,EACAtE,CAAU,GACb,CACJ,CAlBE,CAoBV,CA3XK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A javascript module to handle calendar drag and drop in the calendar\n * month view.\n *\n * @module core_calendar/month_view_drag_drop\n * @copyright 2017 Ryan Wyllie \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine([\n 'jquery',\n 'core/notification',\n 'core/str',\n 'core_calendar/events',\n 'core_calendar/drag_drop_data_store'\n ],\n function(\n $,\n Notification,\n Str,\n CalendarEvents,\n DataStore\n ) {\n\n var SELECTORS = {\n ROOT: \"[data-region='calendar']\",\n DRAGGABLE: '[draggable=\"true\"][data-region=\"event-item\"]',\n DROP_ZONE: '[data-drop-zone=\"month-view-day\"]',\n WEEK: '[data-region=\"month-view-week\"]',\n };\n var INVALID_DROP_ZONE_CLASS = 'bg-faded';\n var INVALID_HOVER_CLASS = 'bg-danger text-white';\n var VALID_HOVER_CLASS = 'bg-primary text-white';\n var ALL_CLASSES = INVALID_DROP_ZONE_CLASS + ' ' + INVALID_HOVER_CLASS + ' ' + VALID_HOVER_CLASS;\n /* @var {bool} registered If the event listeners have been added */\n var registered = false;\n\n /**\n * Get the correct drop zone element from the given javascript\n * event.\n *\n * @param {event} e The javascript event\n * @return {object|null}\n */\n var getDropZoneFromEvent = function(e) {\n var dropZone = $(e.target).closest(SELECTORS.DROP_ZONE);\n return (dropZone.length) ? dropZone : null;\n };\n\n /**\n * Determine if the given dropzone element is within the acceptable\n * time range.\n *\n * The drop zone timestamp is midnight on that day so we should check\n * that the event's acceptable timestart value\n *\n * @param {object} dropZone The drop zone day from the calendar\n * @return {bool}\n */\n var isValidDropZone = function(dropZone) {\n var dropTimestamp = dropZone.attr('data-day-timestamp');\n var minTimestart = DataStore.getMinTimestart();\n var maxTimestart = DataStore.getMaxTimestart();\n\n if (minTimestart && minTimestart > dropTimestamp) {\n return false;\n }\n\n if (maxTimestart && maxTimestart < dropTimestamp) {\n return false;\n }\n\n return true;\n };\n\n /**\n * Get the error string to display for a given drop zone element\n * if it is invalid.\n *\n * @param {object} dropZone The drop zone day from the calendar\n * @return {string}\n */\n var getDropZoneError = function(dropZone) {\n var dropTimestamp = dropZone.attr('data-day-timestamp');\n var minTimestart = DataStore.getMinTimestart();\n var maxTimestart = DataStore.getMaxTimestart();\n\n if (minTimestart && minTimestart > dropTimestamp) {\n return DataStore.getMinError();\n }\n\n if (maxTimestart && maxTimestart < dropTimestamp) {\n return DataStore.getMaxError();\n }\n\n return null;\n };\n\n /**\n * Remove all of the styling from each of the drop zones in the calendar.\n */\n var clearAllDropZonesState = function() {\n $(SELECTORS.ROOT).find(SELECTORS.DROP_ZONE).each(function(index, dropZone) {\n dropZone = $(dropZone);\n dropZone.removeClass(ALL_CLASSES);\n });\n };\n\n /**\n * Update the hover state for the event in the calendar to reflect\n * which days the event will be moved to.\n *\n * If the drop zone is not being hovered then it will apply some\n * styling to reflect whether the drop zone is a valid or invalid\n * drop place for the current dragging event.\n *\n * This funciton supports events spanning multiple days and will\n * recurse to highlight (or remove highlight) each of the days\n * that the event will be moved to.\n *\n * For example: An event with a duration of 3 days will have\n * 3 days highlighted when it's dragged elsewhere in the calendar.\n * The current drag target and the 2 days following it (including\n * wrapping to the next week if necessary).\n *\n * @param {string|object} dropZone The drag target element\n * @param {bool} hovered If the target is hovered or not\n * @param {Number} count How many days to highlight (default to duration)\n */\n var updateHoverState = function(dropZone, hovered, count) {\n if (typeof count === 'undefined') {\n // This is how many days we need to highlight.\n count = DataStore.getDurationDays();\n }\n\n var valid = isValidDropZone(dropZone);\n dropZone.removeClass(ALL_CLASSES);\n\n if (hovered) {\n\n if (valid) {\n dropZone.addClass(VALID_HOVER_CLASS);\n } else {\n dropZone.addClass(INVALID_HOVER_CLASS);\n }\n } else {\n dropZone.removeClass(VALID_HOVER_CLASS + ' ' + INVALID_HOVER_CLASS);\n\n if (!valid) {\n dropZone.addClass(INVALID_DROP_ZONE_CLASS);\n }\n }\n\n count--;\n\n // If we've still got days to highlight then we should\n // find the next day.\n if (count > 0) {\n var nextDropZone = dropZone.next();\n\n // If there are no more days in this week then we\n // need to move down to the next week in the calendar.\n if (!nextDropZone.length) {\n var nextWeek = dropZone.closest(SELECTORS.WEEK).next();\n\n if (nextWeek.length) {\n nextDropZone = nextWeek.children(SELECTORS.DROP_ZONE).first();\n }\n }\n\n // If we found another day then let's recursively\n // update it's hover state.\n if (nextDropZone.length) {\n updateHoverState(nextDropZone, hovered, count);\n }\n }\n };\n\n /**\n * Find all of the calendar event drop zones in the calendar and update the display\n * for the user to indicate which zones are valid and invalid.\n */\n var updateAllDropZonesState = function() {\n $(SELECTORS.ROOT).find(SELECTORS.DROP_ZONE).each(function(index, dropZone) {\n dropZone = $(dropZone);\n\n if (!isValidDropZone(dropZone)) {\n updateHoverState(dropZone, false);\n }\n });\n };\n\n\n /**\n * Set up the module level variables to track which event is being\n * dragged and how many days it spans.\n *\n * @param {event} e The dragstart event\n */\n var dragstartHandler = function(e) {\n var target = $(e.target);\n var draggableElement = target.closest(SELECTORS.DRAGGABLE);\n\n if (!draggableElement.length) {\n return;\n }\n\n var eventElement = draggableElement.find('[data-event-id]');\n var eventId = eventElement.attr('data-event-id');\n var minTimestart = draggableElement.attr('data-min-day-timestamp');\n var maxTimestart = draggableElement.attr('data-max-day-timestamp');\n var minError = draggableElement.attr('data-min-day-error');\n var maxError = draggableElement.attr('data-max-day-error');\n var eventsSelector = SELECTORS.ROOT + ' [data-event-id=\"' + eventId + '\"]';\n var duration = $(eventsSelector).length;\n\n DataStore.setEventId(eventId);\n DataStore.setDurationDays(duration);\n\n if (minTimestart) {\n DataStore.setMinTimestart(minTimestart);\n }\n\n if (maxTimestart) {\n DataStore.setMaxTimestart(maxTimestart);\n }\n\n if (minError) {\n DataStore.setMinError(minError);\n }\n\n if (maxError) {\n DataStore.setMaxError(maxError);\n }\n\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.dropEffect = \"move\";\n // Firefox requires a value to be set here or the drag won't\n // work and the dragover handler won't fire.\n e.dataTransfer.setData('text/plain', eventId);\n e.dropEffect = \"move\";\n\n updateAllDropZonesState();\n };\n\n /**\n * Update the hover state of the target day element when\n * the user is dragging an event over it.\n *\n * This will add a visual indicator to the calendar UI to\n * indicate which day(s) the event will be moved to.\n *\n * @param {event} e The dragstart event\n */\n var dragoverHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n e.preventDefault();\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n return;\n }\n\n updateHoverState(dropZone, true);\n };\n\n /**\n * Update the hover state of the target day element that was\n * previously dragged over but has is no longer a drag target.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dragleaveHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n return;\n }\n\n updateHoverState(dropZone, false);\n e.preventDefault();\n };\n\n /**\n * Determines the event element, origin day, and destination day\n * once the user drops the calendar event. These three bits of data\n * are provided as the payload to the \"moveEvent\" calendar javascript\n * event that is fired.\n *\n * This will remove the visual indicator from the calendar UI\n * that was added by the dragoverHandler.\n *\n * @param {event} e The dragstart event\n */\n var dropHandler = function(e) {\n // Ignore dragging of non calendar events.\n if (!DataStore.hasEventId()) {\n return;\n }\n\n var dropZone = getDropZoneFromEvent(e);\n\n if (!dropZone) {\n DataStore.clearAll();\n clearAllDropZonesState();\n return;\n }\n\n if (isValidDropZone(dropZone)) {\n var eventId = DataStore.getEventId();\n var eventElementSelector = SELECTORS.ROOT + ' [data-event-id=\"' + eventId + '\"]';\n var eventElement = $(eventElementSelector);\n var origin = null;\n\n if (eventElement.length) {\n origin = eventElement.closest(SELECTORS.DROP_ZONE);\n }\n\n $('body').trigger(CalendarEvents.moveEvent, [eventId, origin, dropZone]);\n } else {\n // If the drop zone is not valid then there is not need for us to\n // try to process it. Instead we can just show an error to the user.\n var message = getDropZoneError(dropZone);\n Str.get_string('errorinvaliddate', 'calendar').then(function(string) {\n Notification.exception({\n name: string,\n message: message || string\n });\n });\n }\n\n DataStore.clearAll();\n clearAllDropZonesState();\n\n e.preventDefault();\n };\n\n /**\n * Clear the data store and remove the drag indicators from the UI\n * when the drag event has finished.\n */\n var dragendHandler = function() {\n DataStore.clearAll();\n clearAllDropZonesState();\n };\n\n /**\n * Re-render the drop zones in the new month to highlight\n * which areas are or aren't acceptable to drop the calendar\n * event.\n */\n var calendarMonthChangedHandler = function() {\n updateAllDropZonesState();\n };\n\n return {\n /**\n * Initialise the event handlers for the drag events.\n */\n init: function() {\n if (!registered) {\n // These handlers are only added the first time the module\n // is loaded because we don't want to have a new listener\n // added each time the \"init\" function is called otherwise we'll\n // end up with lots of stale handlers.\n document.addEventListener('dragstart', dragstartHandler, false);\n document.addEventListener('dragover', dragoverHandler, false);\n document.addEventListener('dragleave', dragleaveHandler, false);\n document.addEventListener('drop', dropHandler, false);\n document.addEventListener('dragend', dragendHandler, false);\n $('body').on(CalendarEvents.monthChanged, calendarMonthChangedHandler);\n registered = true;\n }\n },\n };\n});\n"],"file":"month_view_drag_drop.min.js"} \ No newline at end of file diff --git a/calendar/amd/src/month_navigation_drag_drop.js b/calendar/amd/src/month_navigation_drag_drop.js index 00db7ad2bdf69..f7eb5858394b9 100644 --- a/calendar/amd/src/month_navigation_drag_drop.js +++ b/calendar/amd/src/month_navigation_drag_drop.js @@ -97,6 +97,8 @@ define([ /** * This will add a visual indicator to the calendar UI to * indicate which nav link is a valid drop zone. + * + * @param {Event} e */ var dragstartHandler = function(e) { // Make sure the drag event is for a calendar event. diff --git a/calendar/amd/src/month_view_drag_drop.js b/calendar/amd/src/month_view_drag_drop.js index fc09c10d6c7af..0fe9a2adc8d6e 100644 --- a/calendar/amd/src/month_view_drag_drop.js +++ b/calendar/amd/src/month_view_drag_drop.js @@ -137,9 +137,9 @@ define([ * The current drag target and the 2 days following it (including * wrapping to the next week if necessary). * - * @param {string|object} target The drag target element + * @param {string|object} dropZone The drag target element * @param {bool} hovered If the target is hovered or not - * @param {int} count How many days to highlight (default to duration) + * @param {Number} count How many days to highlight (default to duration) */ var updateHoverState = function(dropZone, hovered, count) { if (typeof count === 'undefined') { diff --git a/contentbank/amd/build/sort.min.js.map b/contentbank/amd/build/sort.min.js.map index 3150414a2bfe6..aee0682f43470 100644 --- a/contentbank/amd/build/sort.min.js.map +++ b/contentbank/amd/build/sort.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/sort.js"],"names":["init","contentBank","document","querySelector","selectors","regions","contentbank","Prefetch","prefetchStrings","registerListenerEvents","addEventListener","e","viewList","actions","viewlist","viewGrid","viewgrid","target","closest","classList","remove","add","setViewListPreference","fileArea","filearea","shownItems","querySelectorAll","elements","listitem","sortByName","sortname","ascending","updateSortButtons","updateSortOrder","sortByUses","sortuses","sortByDate","sortdate","sortBySize","sortsize","sortByType","sorttype","sortByAuthor","sortauthor","request","methodname","args","preferences","type","value","Ajax","call","catch","Notification","exception","sortButton","sortButtons","sortbutton","forEach","button","updateButtonTitle","contains","sortString","dataset","string","then","columnName","sortByString","setAttribute","itemList","attribute","sortList","slice","sort","a","b","aa","getAttribute","bb","isNaN","parseInt","listItem","appendChild"],"mappings":"uNAuBA,OAEA,OACA,OACA,O,mDAOO,GAAMA,CAAAA,CAAI,CAAG,UAAM,CACtB,GAAMC,CAAAA,CAAW,CAAGC,QAAQ,CAACC,aAAT,CAAuBC,UAAUC,OAAV,CAAkBC,WAAzC,CAApB,CACAC,UAASC,eAAT,CAAyB,aAAzB,CAAwC,CAAC,aAAD,CAAgB,MAAhB,CAAwB,cAAxB,CAAwC,MAAxC,CAAgD,MAAhD,CAAwD,QAAxD,CAAxC,EACAD,UAASC,eAAT,CAAyB,QAAzB,CAAmC,CAAC,SAAD,CAAY,gBAAZ,CAAnC,EACAC,CAAsB,CAACR,CAAD,CACzB,CALM,C,YAaDQ,CAAAA,CAAsB,CAAG,SAACR,CAAD,CAAiB,CAE5CA,CAAW,CAACS,gBAAZ,CAA6B,OAA7B,CAAsC,SAAAC,CAAC,CAAI,IACjCC,CAAAA,CAAQ,CAAGX,CAAW,CAACE,aAAZ,CAA0BC,UAAUS,OAAV,CAAkBC,QAA5C,CADsB,CAEjCC,CAAQ,CAAGd,CAAW,CAACE,aAAZ,CAA0BC,UAAUS,OAAV,CAAkBG,QAA5C,CAFsB,CAKvC,GAAIL,CAAC,CAACM,MAAF,CAASC,OAAT,CAAiBd,UAAUS,OAAV,CAAkBG,QAAnC,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AeP,CAAf,CAFgD,CAGrDQ,CAAE,CAAGH,CAAC,CAACE,YAAF,CAAeP,CAAf,CAHgD,CAIzD,GAAI,CAACS,KAAK,CAACH,CAAD,CAAV,CAAgB,CACbA,CAAE,CAAGI,QAAQ,CAACJ,CAAD,CAAb,CACAE,CAAE,CAAGE,QAAQ,CAACF,CAAD,CACf,CAED,GAAI/C,CAAJ,CAAe,CACX,MAAO6C,CAAAA,CAAE,CAAGE,CAAL,CAAU,CAAV,CAAc,CAAC,CACzB,CAFD,IAEO,CACH,MAAOF,CAAAA,CAAE,CAAGE,CAAL,CAAU,CAAV,CAAc,CAAC,CACzB,CACJ,CAdgB,CAAjB,CAeAP,CAAQ,CAACb,OAAT,CAAiB,SAAAuB,CAAQ,QAAI1D,CAAAA,CAAQ,CAAC2D,WAAT,CAAqBD,CAArB,CAAJ,CAAzB,CACH,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Content bank UI actions.\n *\n * @module core_contentbank/sort\n * @copyright 2020 Bas Brands \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport selectors from './selectors';\nimport {get_string as getString} from 'core/str';\nimport Prefetch from 'core/prefetch';\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\n\n/**\n * Set up the contentbank views.\n *\n * @method init\n */\nexport const init = () => {\n const contentBank = document.querySelector(selectors.regions.contentbank);\n Prefetch.prefetchStrings('contentbank', ['contentname', 'uses', 'lastmodified', 'size', 'type', 'author']);\n Prefetch.prefetchStrings('moodle', ['sortbyx', 'sortbyxreverse']);\n registerListenerEvents(contentBank);\n};\n\n/**\n * Register contentbank related event listeners.\n *\n * @method registerListenerEvents\n * @param {HTMLElement} contentBank The DOM node of the content bank\n */\nconst registerListenerEvents = (contentBank) => {\n\n contentBank.addEventListener('click', e => {\n const viewList = contentBank.querySelector(selectors.actions.viewlist);\n const viewGrid = contentBank.querySelector(selectors.actions.viewgrid);\n\n // View as Grid button.\n if (e.target.closest(selectors.actions.viewgrid)) {\n contentBank.classList.remove('view-list');\n contentBank.classList.add('view-grid');\n viewGrid.classList.add('active');\n viewList.classList.remove('active');\n setViewListPreference(false);\n\n return;\n }\n\n // View as List button.\n if (e.target.closest(selectors.actions.viewlist)) {\n contentBank.classList.remove('view-grid');\n contentBank.classList.add('view-list');\n viewList.classList.add('active');\n viewGrid.classList.remove('active');\n setViewListPreference(true);\n\n return;\n }\n\n // TODO: This should _not_ use `document`. Every query should be constrained to the content bank container.\n const fileArea = document.querySelector(selectors.regions.filearea);\n const shownItems = fileArea.querySelectorAll(selectors.elements.listitem);\n\n if (fileArea && shownItems) {\n\n // Sort by file name alphabetical\n const sortByName = e.target.closest(selectors.actions.sortname);\n if (sortByName) {\n const ascending = updateSortButtons(contentBank, sortByName);\n updateSortOrder(fileArea, shownItems, 'data-file', ascending);\n return;\n }\n\n // Sort by uses.\n const sortByUses = e.target.closest(selectors.actions.sortuses);\n if (sortByUses) {\n const ascending = updateSortButtons(contentBank, sortByUses);\n updateSortOrder(fileArea, shownItems, 'data-uses', ascending);\n return;\n }\n\n // Sort by date.\n const sortByDate = e.target.closest(selectors.actions.sortdate);\n if (sortByDate) {\n const ascending = updateSortButtons(contentBank, sortByDate);\n updateSortOrder(fileArea, shownItems, 'data-timemodified', ascending);\n return;\n }\n\n // Sort by size.\n const sortBySize = e.target.closest(selectors.actions.sortsize);\n if (sortBySize) {\n const ascending = updateSortButtons(contentBank, sortBySize);\n updateSortOrder(fileArea, shownItems, 'data-bytes', ascending);\n return;\n }\n\n // Sort by type.\n const sortByType = e.target.closest(selectors.actions.sorttype);\n if (sortByType) {\n const ascending = updateSortButtons(contentBank, sortByType);\n updateSortOrder(fileArea, shownItems, 'data-type', ascending);\n return;\n }\n\n // Sort by author.\n const sortByAuthor = e.target.closest(selectors.actions.sortauthor);\n if (sortByAuthor) {\n const ascending = updateSortButtons(contentBank, sortByAuthor);\n updateSortOrder(fileArea, shownItems, 'data-author', ascending);\n }\n return;\n }\n });\n};\n\n\n/**\n * Set the contentbank user preference in list view\n *\n * @param {Bool} viewList view ContentBank as list.\n * @return {Promise} Repository promise.\n */\nconst setViewListPreference = function(viewList) {\n\n // If the given status is not hidden, the preference has to be deleted with a null value.\n if (viewList === false) {\n viewList = null;\n }\n\n const request = {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [\n {\n type: 'core_contentbank_view_list',\n value: viewList\n }\n ]\n }\n };\n\n return Ajax.call([request])[0].catch(Notification.exception);\n};\n\n/**\n * Update the sort button view.\n *\n * @method updateSortButtons\n * @param {HTMLElement} contentBank The DOM node of the contentbank button\n * @param {HTMLElement} sortButton The DOM node of the sort button\n * @return {Bool} sort ascending\n */\nconst updateSortButtons = (contentBank, sortButton) => {\n const sortButtons = contentBank.querySelectorAll(selectors.elements.sortbutton);\n\n sortButtons.forEach((button) => {\n if (button !== sortButton) {\n button.classList.remove('dir-asc');\n button.classList.remove('dir-desc');\n button.classList.add('dir-none');\n\n updateButtonTitle(button, false);\n }\n });\n\n let ascending = true;\n\n if (sortButton.classList.contains('dir-none')) {\n sortButton.classList.remove('dir-none');\n sortButton.classList.add('dir-asc');\n } else if (sortButton.classList.contains('dir-asc')) {\n sortButton.classList.remove('dir-asc');\n sortButton.classList.add('dir-desc');\n ascending = false;\n } else if (sortButton.classList.contains('dir-desc')) {\n sortButton.classList.remove('dir-desc');\n sortButton.classList.add('dir-asc');\n }\n\n updateButtonTitle(sortButton, ascending);\n\n return ascending;\n};\n\n/**\n * Update the button title.\n *\n * @method updateButtonTitle\n * @param {HTMLElement} button Button to update\n * @param {Bool} ascending Sort direction\n * @return {Promise} string promise\n */\nconst updateButtonTitle = (button, ascending) => {\n\n const sortString = (ascending ? 'sortbyxreverse' : 'sortbyx');\n\n return getString(button.dataset.string, 'contentbank')\n .then(columnName => {\n return getString(sortString, 'core', columnName);\n })\n .then(sortByString => {\n button.setAttribute('title', sortByString);\n return sortByString;\n })\n .catch();\n};\n\n/**\n * Update the sort order of the itemlist and update the DOM\n *\n * @method updateSortOrder\n * @param {HTMLElement} fileArea the Dom container for the itemlist\n * @param {Array} itemList Nodelist of Dom elements\n * @param {String} attribute, the attribut to sort on\n * @param {Bool} ascending, Sort Ascending\n */\nconst updateSortOrder = (fileArea, itemList, attribute, ascending) => {\n const sortList = [].slice.call(itemList).sort(function(a, b) {\n\n let aa = a.getAttribute(attribute);\n let bb = b.getAttribute(attribute);\n if (!isNaN(aa)) {\n aa = parseInt(aa);\n bb = parseInt(bb);\n }\n\n if (ascending) {\n return aa > bb ? 1 : -1;\n } else {\n return aa < bb ? 1 : -1;\n }\n });\n sortList.forEach(listItem => fileArea.appendChild(listItem));\n};\n"],"file":"sort.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/sort.js"],"names":["init","contentBank","document","querySelector","selectors","regions","contentbank","Prefetch","prefetchStrings","registerListenerEvents","addEventListener","e","viewList","actions","viewlist","viewGrid","viewgrid","target","closest","classList","remove","add","setViewListPreference","fileArea","filearea","shownItems","querySelectorAll","elements","listitem","sortByName","sortname","ascending","updateSortButtons","updateSortOrder","sortByUses","sortuses","sortByDate","sortdate","sortBySize","sortsize","sortByType","sorttype","sortByAuthor","sortauthor","request","methodname","args","preferences","type","value","Ajax","call","catch","Notification","exception","sortButton","sortButtons","sortbutton","forEach","button","updateButtonTitle","contains","sortString","dataset","string","then","columnName","sortByString","setAttribute","itemList","attribute","sortList","slice","sort","a","b","aa","getAttribute","bb","isNaN","parseInt","listItem","appendChild"],"mappings":"uNAuBA,OAEA,OACA,OACA,O,mDAOO,GAAMA,CAA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2D,WAAT,CAAqBD,CAArB,CAAJ,CAAzB,CACH,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Content bank UI actions.\n *\n * @module core_contentbank/sort\n * @copyright 2020 Bas Brands \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport selectors from './selectors';\nimport {get_string as getString} from 'core/str';\nimport Prefetch from 'core/prefetch';\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\n\n/**\n * Set up the contentbank views.\n *\n * @method init\n */\nexport const init = () => {\n const contentBank = document.querySelector(selectors.regions.contentbank);\n Prefetch.prefetchStrings('contentbank', ['contentname', 'uses', 'lastmodified', 'size', 'type', 'author']);\n Prefetch.prefetchStrings('moodle', ['sortbyx', 'sortbyxreverse']);\n registerListenerEvents(contentBank);\n};\n\n/**\n * Register contentbank related event listeners.\n *\n * @method registerListenerEvents\n * @param {HTMLElement} contentBank The DOM node of the content bank\n */\nconst registerListenerEvents = (contentBank) => {\n\n contentBank.addEventListener('click', e => {\n const viewList = contentBank.querySelector(selectors.actions.viewlist);\n const viewGrid = contentBank.querySelector(selectors.actions.viewgrid);\n\n // View as Grid button.\n if (e.target.closest(selectors.actions.viewgrid)) {\n contentBank.classList.remove('view-list');\n contentBank.classList.add('view-grid');\n viewGrid.classList.add('active');\n viewList.classList.remove('active');\n setViewListPreference(false);\n\n return;\n }\n\n // View as List button.\n if (e.target.closest(selectors.actions.viewlist)) {\n contentBank.classList.remove('view-grid');\n contentBank.classList.add('view-list');\n viewList.classList.add('active');\n viewGrid.classList.remove('active');\n setViewListPreference(true);\n\n return;\n }\n\n // TODO: This should _not_ use `document`. Every query should be constrained to the content bank container.\n const fileArea = document.querySelector(selectors.regions.filearea);\n const shownItems = fileArea.querySelectorAll(selectors.elements.listitem);\n\n if (fileArea && shownItems) {\n\n // Sort by file name alphabetical\n const sortByName = e.target.closest(selectors.actions.sortname);\n if (sortByName) {\n const ascending = updateSortButtons(contentBank, sortByName);\n updateSortOrder(fileArea, shownItems, 'data-file', ascending);\n return;\n }\n\n // Sort by uses.\n const sortByUses = e.target.closest(selectors.actions.sortuses);\n if (sortByUses) {\n const ascending = updateSortButtons(contentBank, sortByUses);\n updateSortOrder(fileArea, shownItems, 'data-uses', ascending);\n return;\n }\n\n // Sort by date.\n const sortByDate = e.target.closest(selectors.actions.sortdate);\n if (sortByDate) {\n const ascending = updateSortButtons(contentBank, sortByDate);\n updateSortOrder(fileArea, shownItems, 'data-timemodified', ascending);\n return;\n }\n\n // Sort by size.\n const sortBySize = e.target.closest(selectors.actions.sortsize);\n if (sortBySize) {\n const ascending = updateSortButtons(contentBank, sortBySize);\n updateSortOrder(fileArea, shownItems, 'data-bytes', ascending);\n return;\n }\n\n // Sort by type.\n const sortByType = e.target.closest(selectors.actions.sorttype);\n if (sortByType) {\n const ascending = updateSortButtons(contentBank, sortByType);\n updateSortOrder(fileArea, shownItems, 'data-type', ascending);\n return;\n }\n\n // Sort by author.\n const sortByAuthor = e.target.closest(selectors.actions.sortauthor);\n if (sortByAuthor) {\n const ascending = updateSortButtons(contentBank, sortByAuthor);\n updateSortOrder(fileArea, shownItems, 'data-author', ascending);\n }\n return;\n }\n });\n};\n\n\n/**\n * Set the contentbank user preference in list view\n *\n * @param {Bool} viewList view ContentBank as list.\n * @return {Promise} Repository promise.\n */\nconst setViewListPreference = function(viewList) {\n\n // If the given status is not hidden, the preference has to be deleted with a null value.\n if (viewList === false) {\n viewList = null;\n }\n\n const request = {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [\n {\n type: 'core_contentbank_view_list',\n value: viewList\n }\n ]\n }\n };\n\n return Ajax.call([request])[0].catch(Notification.exception);\n};\n\n/**\n * Update the sort button view.\n *\n * @method updateSortButtons\n * @param {HTMLElement} contentBank The DOM node of the contentbank button\n * @param {HTMLElement} sortButton The DOM node of the sort button\n * @return {Bool} sort ascending\n */\nconst updateSortButtons = (contentBank, sortButton) => {\n const sortButtons = contentBank.querySelectorAll(selectors.elements.sortbutton);\n\n sortButtons.forEach((button) => {\n if (button !== sortButton) {\n button.classList.remove('dir-asc');\n button.classList.remove('dir-desc');\n button.classList.add('dir-none');\n\n updateButtonTitle(button, false);\n }\n });\n\n let ascending = true;\n\n if (sortButton.classList.contains('dir-none')) {\n sortButton.classList.remove('dir-none');\n sortButton.classList.add('dir-asc');\n } else if (sortButton.classList.contains('dir-asc')) {\n sortButton.classList.remove('dir-asc');\n sortButton.classList.add('dir-desc');\n ascending = false;\n } else if (sortButton.classList.contains('dir-desc')) {\n sortButton.classList.remove('dir-desc');\n sortButton.classList.add('dir-asc');\n }\n\n updateButtonTitle(sortButton, ascending);\n\n return ascending;\n};\n\n/**\n * Update the button title.\n *\n * @method updateButtonTitle\n * @param {HTMLElement} button Button to update\n * @param {Bool} ascending Sort direction\n * @return {Promise} string promise\n */\nconst updateButtonTitle = (button, ascending) => {\n\n const sortString = (ascending ? 'sortbyxreverse' : 'sortbyx');\n\n return getString(button.dataset.string, 'contentbank')\n .then(columnName => {\n return getString(sortString, 'core', columnName);\n })\n .then(sortByString => {\n button.setAttribute('title', sortByString);\n return sortByString;\n })\n .catch();\n};\n\n/**\n * Update the sort order of the itemlist and update the DOM\n *\n * @method updateSortOrder\n * @param {HTMLElement} fileArea the Dom container for the itemlist\n * @param {Array} itemList Nodelist of Dom elements\n * @param {String} attribute the attribut to sort on\n * @param {Bool} ascending Sort Ascending\n */\nconst updateSortOrder = (fileArea, itemList, attribute, ascending) => {\n const sortList = [].slice.call(itemList).sort(function(a, b) {\n\n let aa = a.getAttribute(attribute);\n let bb = b.getAttribute(attribute);\n if (!isNaN(aa)) {\n aa = parseInt(aa);\n bb = parseInt(bb);\n }\n\n if (ascending) {\n return aa > bb ? 1 : -1;\n } else {\n return aa < bb ? 1 : -1;\n }\n });\n sortList.forEach(listItem => fileArea.appendChild(listItem));\n};\n"],"file":"sort.min.js"} \ No newline at end of file diff --git a/contentbank/amd/src/sort.js b/contentbank/amd/src/sort.js index 2eb929a638f9a..be349971593b7 100644 --- a/contentbank/amd/src/sort.js +++ b/contentbank/amd/src/sort.js @@ -228,8 +228,8 @@ const updateButtonTitle = (button, ascending) => { * @method updateSortOrder * @param {HTMLElement} fileArea the Dom container for the itemlist * @param {Array} itemList Nodelist of Dom elements - * @param {String} attribute, the attribut to sort on - * @param {Bool} ascending, Sort Ascending + * @param {String} attribute the attribut to sort on + * @param {Bool} ascending Sort Ascending */ const updateSortOrder = (fileArea, itemList, attribute, ascending) => { const sortList = [].slice.call(itemList).sort(function(a, b) { diff --git a/course/format/amd/build/courseeditor.min.js.map b/course/format/amd/build/courseeditor.min.js.map index 8ad88346fcd56..b45f9a03e8d60 100644 --- a/course/format/amd/build/courseeditor.min.js.map +++ b/course/format/amd/build/courseeditor.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/courseeditor.js"],"names":["courseEditorMap","Map","dispatchStateChangedEvent","detail","target","document","dispatchEvent","CustomEvent","events","stateChanged","bubbles","setViewFormat","courseId","setup","editor","getCourseEditor","parseInt","has","set","CourseEditor","name","eventName","eventDispatch","mutations","DefaultMutations","get","loadCourse","getCurrentCourseEditor","M","cfg"],"mappings":"iUAuBA,OACA,OACA,O,mDAGA,GAAMA,CAAAA,CAAe,CAAG,GAAIC,CAAAA,GAA5B,CAYA,QAASC,CAAAA,CAAT,CAAmCC,CAAnC,CAA2CC,CAA3C,CAAmD,CAC/C,GAAIA,CAAM,SAAV,CAA0B,CACtBA,CAAM,CAAGC,QACZ,CACDD,CAAM,CAACE,aAAP,CAAqB,GAAIC,CAAAA,WAAJ,CAAgBC,UAAOC,YAAvB,CAAqC,CACtDC,OAAO,GAD+C,CAEtDP,MAAM,CAAEA,CAF8C,CAArC,CAArB,CAIH,C,gBAU4B,QAAhBQ,CAAAA,aAAgB,CAACC,CAAD,CAAWC,CAAX,CAAqB,CAC9C,GAAMC,CAAAA,CAAM,CAAGC,CAAe,CAACH,CAAD,CAA9B,CACAE,CAAM,CAACH,aAAP,CAAqBE,CAArB,CACH,C,CAQM,GAAME,CAAAA,CAAe,CAAG,SAACH,CAAD,CAAc,CACzCA,CAAQ,CAAGI,QAAQ,CAACJ,CAAD,CAAnB,CAEA,GAAI,CAACZ,CAAe,CAACiB,GAAhB,CAAoBL,CAApB,CAAL,CAAoC,CAChCZ,CAAe,CAACkB,GAAhB,CACIN,CADJ,CAEI,GAAIO,UAAJ,CAAiB,CACbC,IAAI,uBAAiBR,CAAjB,CADS,CAEbS,SAAS,CAAEb,UAAOC,YAFL,CAGba,aAAa,CAAEpB,CAHF,CAMbqB,SAAS,CAAE,GAAIC,UANF,CAAjB,CAFJ,EAWAxB,CAAe,CAACyB,GAAhB,CAAoBb,CAApB,EAA8Bc,UAA9B,CAAyCd,CAAzC,CACH,CACD,MAAOZ,CAAAA,CAAe,CAACyB,GAAhB,CAAoBb,CAApB,CACV,CAlBM,C,6CAyB+B,QAAzBe,CAAAA,sBAAyB,SAAMZ,CAAAA,CAAe,CAACa,CAAC,CAACC,GAAF,CAAMjB,QAAP,CAArB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Generic reactive module used in the course editor.\n *\n * @module core_courseformat/courseeditor\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DefaultMutations from 'core_courseformat/local/courseeditor/mutations';\nimport CourseEditor from 'core_courseformat/local/courseeditor/courseeditor';\nimport events from 'core_course/events';\n\n// A map with all the course editor instances.\nconst courseEditorMap = new Map();\n\n/**\n * Trigger a state changed event.\n *\n * This function will be moved to core_course/events module\n * when the file is migrated to the new JS events structure proposed in MDL-70990.\n *\n * @method dispatchStateChangedEvent\n * @param {object} detail the full state\n * @param {object} target the custom event target (document if none provided)\n */\nfunction dispatchStateChangedEvent(detail, target) {\n if (target === undefined) {\n target = document;\n }\n target.dispatchEvent(new CustomEvent(events.stateChanged, {\n bubbles: true,\n detail: detail,\n }));\n}\n\n/**\n * Setup the current view settings\n *\n * @param {number} courseId the course id\n * @param {setup} setup format, page and course settings\n * @property {boolean} setup.editing if the page is in edit mode\n * @property {boolean} setup.supportscomponents if the format supports components for content\n */\nexport const setViewFormat = (courseId, setup) => {\n const editor = getCourseEditor(courseId);\n editor.setViewFormat(setup);\n};\n\n/**\n * Get a specific course editor reactive instance.\n *\n * @param {number} courseId the course id\n * @returns {CourseEditor}\n */\nexport const getCourseEditor = (courseId) => {\n courseId = parseInt(courseId);\n\n if (!courseEditorMap.has(courseId)) {\n courseEditorMap.set(\n courseId,\n new CourseEditor({\n name: `CourseEditor${courseId}`,\n eventName: events.stateChanged,\n eventDispatch: dispatchStateChangedEvent,\n // Mutations can be overridden by the format plugin using setMutations\n // but we need the default one at least.\n mutations: new DefaultMutations(),\n })\n );\n courseEditorMap.get(courseId).loadCourse(courseId);\n }\n return courseEditorMap.get(courseId);\n};\n\n/**\n * Get the current course reactive instance.\n *\n * @returns {CourseEditor}\n */\nexport const getCurrentCourseEditor = () => getCourseEditor(M.cfg.courseId);\n"],"file":"courseeditor.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/courseeditor.js"],"names":["courseEditorMap","Map","dispatchStateChangedEvent","detail","target","document","dispatchEvent","CustomEvent","events","stateChanged","bubbles","setViewFormat","courseId","setup","editor","getCourseEditor","parseInt","has","set","CourseEditor","name","eventName","eventDispatch","mutations","DefaultMutations","get","loadCourse","getCurrentCourseEditor","M","cfg"],"mappings":"iUAuBA,OACA,OACA,O,mDAGA,GAAMA,CAAAA,CAAe,CAAG,GAAIC,CAAAA,GAA5B,CAYA,QAASC,CAAAA,CAAT,CAAmCC,CAAnC,CAA2CC,CAA3C,CAAmD,CAC/C,GAAIA,CAAM,SAAV,CAA0B,CACtBA,CAAM,CAAGC,QACZ,CACDD,CAAM,CAACE,aAAP,CAAqB,GAAIC,CAAAA,WAAJ,CAAgBC,UAAOC,YAAvB,CAAqC,CACtDC,OAAO,GAD+C,CAEtDP,MAAM,CAAEA,CAF8C,CAArC,CAArB,CAIH,C,gBAU4B,QAAhBQ,CAAAA,aAAgB,CAACC,CAAD,CAAWC,CAAX,CAAqB,CAC9C,GAAMC,CAAAA,CAAM,CAAGC,CAAe,CAACH,CAAD,CAA9B,CACAE,CAAM,CAACH,aAAP,CAAqBE,CAArB,CACH,C,CAQM,GAAME,CAAAA,CAAe,CAAG,SAACH,CAAD,CAAc,CACzCA,CAAQ,CAAGI,QAAQ,CAACJ,CAAD,CAAnB,CAEA,GAAI,CAACZ,CAAe,CAACiB,GAAhB,CAAoBL,CAApB,CAAL,CAAoC,CAChCZ,CAAe,CAACkB,GAAhB,CACIN,CADJ,CAEI,GAAIO,UAAJ,CAAiB,CACbC,IAAI,uBAAiBR,CAAjB,CADS,CAEbS,SAAS,CAAEb,UAAOC,YAFL,CAGba,aAAa,CAAEpB,CAHF,CAMbqB,SAAS,CAAE,GAAIC,UANF,CAAjB,CAFJ,EAWAxB,CAAe,CAACyB,GAAhB,CAAoBb,CAApB,EAA8Bc,UAA9B,CAAyCd,CAAzC,CACH,CACD,MAAOZ,CAAAA,CAAe,CAACyB,GAAhB,CAAoBb,CAApB,CACV,CAlBM,C,6CAyB+B,QAAzBe,CAAAA,sBAAyB,SAAMZ,CAAAA,CAAe,CAACa,CAAC,CAACC,GAAF,CAAMjB,QAAP,CAArB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Generic reactive module used in the course editor.\n *\n * @module core_courseformat/courseeditor\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DefaultMutations from 'core_courseformat/local/courseeditor/mutations';\nimport CourseEditor from 'core_courseformat/local/courseeditor/courseeditor';\nimport events from 'core_course/events';\n\n// A map with all the course editor instances.\nconst courseEditorMap = new Map();\n\n/**\n * Trigger a state changed event.\n *\n * This function will be moved to core_course/events module\n * when the file is migrated to the new JS events structure proposed in MDL-70990.\n *\n * @method dispatchStateChangedEvent\n * @param {object} detail the full state\n * @param {object} target the custom event target (document if none provided)\n */\nfunction dispatchStateChangedEvent(detail, target) {\n if (target === undefined) {\n target = document;\n }\n target.dispatchEvent(new CustomEvent(events.stateChanged, {\n bubbles: true,\n detail: detail,\n }));\n}\n\n/**\n * Setup the current view settings\n *\n * @param {number} courseId the course id\n * @param {setup} setup format, page and course settings\n * @param {boolean} setup.editing if the page is in edit mode\n * @param {boolean} setup.supportscomponents if the format supports components for content\n */\nexport const setViewFormat = (courseId, setup) => {\n const editor = getCourseEditor(courseId);\n editor.setViewFormat(setup);\n};\n\n/**\n * Get a specific course editor reactive instance.\n *\n * @param {number} courseId the course id\n * @returns {CourseEditor}\n */\nexport const getCourseEditor = (courseId) => {\n courseId = parseInt(courseId);\n\n if (!courseEditorMap.has(courseId)) {\n courseEditorMap.set(\n courseId,\n new CourseEditor({\n name: `CourseEditor${courseId}`,\n eventName: events.stateChanged,\n eventDispatch: dispatchStateChangedEvent,\n // Mutations can be overridden by the format plugin using setMutations\n // but we need the default one at least.\n mutations: new DefaultMutations(),\n })\n );\n courseEditorMap.get(courseId).loadCourse(courseId);\n }\n return courseEditorMap.get(courseId);\n};\n\n/**\n * Get the current course reactive instance.\n *\n * @returns {CourseEditor}\n */\nexport const getCurrentCourseEditor = () => getCourseEditor(M.cfg.courseId);\n"],"file":"courseeditor.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/content.min.js.map b/course/format/amd/build/local/content.min.js.map index 60ee067d0b800..0eaf3faf5509d 100644 --- a/course/format/amd/build/local/content.min.js.map +++ b/course/format/amd/build/local/content.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/local/content.js"],"names":["Component","name","selectors","SECTION","SECTION_ITEM","SECTION_CMLIST","COURSE_SECTIONLIST","CM","TOGGLER","COLLAPSE","classes","COLLAPSED","ACTIVITYTAG","ACTIVITY","STATEDREADY","dettachedCms","dettachedSections","sections","cms","_indexContents","addEventListener","element","_sectionTogglers","event","sectionlink","target","closest","isChevron","section","toggler","querySelector","isCollapsed","classList","contains","sectionId","getAttribute","reactive","dispatch","contentexpanded","supportComponents","isEditing","DispatchActions","add","watch","handler","_reloadCm","_refreshSectionNumber","_refreshSectionCollapsed","_startProcessing","_refreshCourseSectionlist","_refreshSectionCmlist","cmitem","getElement","id","courseActions","refreshModule","Error","click","number","dataset","sectionid","inplace","inplaceeditable","getInplaceEditable","currentvalue","getValue","currentitemid","getItemId","rawtitle","setValue","cmlist","listparent","createCm","_createCmItem","bind","_fixOrder","sectionlist","createSection","_scanIndex","item","Section","CmItem","selector","index","creationhandler","items","getElements","forEach","unregister","indexed","promise","then","catch","container","cmid","newItem","document","createElement","for","append","get","neworder","dettachedelements","createMethod","length","innerHTML","remove","itemid","currentitem","children","insert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Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index main component.\n *\n * @module core_courseformat/local/content\n * @class core_courseformat/local/content\n * @copyright 2020 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent} from 'core/reactive';\nimport {getCurrentCourseEditor} from 'core_courseformat/courseeditor';\nimport inplaceeditable from 'core/inplace_editable';\nimport Section from 'core_courseformat/local/content/section';\nimport CmItem from 'core_courseformat/local/content/section/cmitem';\n// Course actions is needed for actions that are not migrated to components.\nimport courseActions from 'core_course/actions';\nimport DispatchActions from 'core_courseformat/local/content/actions';\n\nexport default class Component extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'course_format';\n // Default query selectors.\n this.selectors = {\n SECTION: `[data-for='section']`,\n SECTION_ITEM: `[data-for='section_title']`,\n SECTION_CMLIST: `[data-for='cmlist']`,\n COURSE_SECTIONLIST: `[data-for='course_sectionlist']`,\n CM: `[data-for='cmitem']`,\n TOGGLER: `[data-action=\"togglecoursecontentsection\"]`,\n COLLAPSE: `[data-toggle=\"collapse\"]`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n COLLAPSED: `collapsed`,\n // Formats can override the activity tag but a default one is needed to create new elements.\n ACTIVITYTAG: 'li',\n\n // Course content classes.\n ACTIVITY: `activity`,\n STATEDREADY: `stateready`,\n };\n // Array to save dettached elements during element resorting.\n this.dettachedCms = {};\n this.dettachedSections = {};\n // Index of sections and cms components.\n this.sections = {};\n this.cms = {};\n }\n\n /**\n * Static method to create a component instance form the mustahce template.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n reactive: getCurrentCourseEditor(),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this._indexContents();\n // Activate section togglers.\n this.addEventListener(this.element, 'click', this._sectionTogglers);\n }\n\n /**\n * Setup sections toggler.\n *\n * Toggler click is delegated to the main course content element because new sections can\n * appear at any moment and this way we prevent accidental double bindings.\n *\n * @param {Event} event the triggered event\n */\n _sectionTogglers(event) {\n const sectionlink = event.target.closest(this.selectors.TOGGLER);\n const isChevron = event.target.closest(this.selectors.COLLAPSE);\n\n if (sectionlink || isChevron) {\n\n const section = event.target.closest(this.selectors.SECTION);\n const toggler = section.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (isChevron || isCollapsed) {\n // Update the state.\n const sectionId = section.getAttribute('data-id');\n this.reactive.dispatch(\n 'sectionPreferences',\n [sectionId],\n {\n contentexpanded: isCollapsed,\n },\n );\n }\n }\n }\n\n /**\n *\n * Course content elements could not provide JS Components because the elements HTML is applied\n * directly from the course actions. To keep internal components updated this module keeps\n * a list of the active components and mark them as \"indexed\". This way when any action replace\n * the HTML this component will recreate the components an add any necessary event listener.\n *\n * Format plugins can override this method to provide extra logic to the course frontend.\n *\n */\n stateReady() {\n this._indexContents();\n\n if (this.reactive.supportComponents) {\n // Actions are only available in edit mode.\n if (this.reactive.isEditing) {\n new DispatchActions(this);\n }\n\n // Mark content as state ready.\n this.element.classList.add(this.classes.STATEDREADY);\n }\n }\n\n /**\n * Return the component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n // Check if the course format is compatible with reactive components.\n if (!this.reactive.supportComponents) {\n return [];\n }\n return [\n // State changes that require to reload some course modules.\n {watch: `cm.visible:updated`, handler: this._reloadCm},\n // Update section number and title.\n {watch: `section.number:updated`, handler: this._refreshSectionNumber},\n // Collapse and expand sections.\n {watch: `section.contentexpanded:updated`, handler: this._refreshSectionCollapsed},\n // Sections and cm sorting.\n {watch: `transaction:start`, handler: this._startProcessing},\n {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist},\n {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist},\n // Reindex sections and cms.\n {watch: `state:updated`, handler: this._indexContents},\n // State changes thaty require to reload course modules.\n {watch: `cm.visible:updated`, handler: this._reloadCm},\n {watch: `cm.sectionid:updated`, handler: this._reloadCm},\n ];\n }\n\n /**\n * Reload a course module.\n *\n * Most course module HTML is still strongly backend dependant.\n * Some changes require to get a new version af the module.\n *\n * @param {Object} update the state update data\n */\n _reloadCm({element}) {\n const cmitem = this.getElement(this.selectors.CM, element.id);\n if (cmitem) {\n courseActions.refreshModule(cmitem, element.id);\n }\n }\n\n /**\n * Update section collapsed.\n *\n * @param {Object} details the update details.\n */\n _refreshSectionCollapsed({element}) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n throw new Error(`Unknown section with ID ${element.id}`);\n }\n // Check if it is already done.\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (element.contentexpanded === isCollapsed) {\n toggler.click();\n }\n }\n\n /**\n * Setup the component to start a transaction.\n *\n * Some of the course actions replaces the current DOM element with a new one before updating the\n * course state. This means the component cannot preload any index properly until the transaction starts.\n *\n */\n _startProcessing() {\n // During a section or cm sorting, some elements could be dettached from the DOM and we\n // need to store somewhare in case they are needed later.\n this.dettachedCms = {};\n this.dettachedSections = {};\n }\n\n /**\n * Update a course section when the section number changes.\n *\n * The courseActions module used for most course section tools still depends on css classes and\n * section numbers (not id). To prevent inconsistencies when a section is moved, we need to refresh\n * the\n *\n * Course formats can override the section title rendering so the frontend depends heavily on backend\n * rendering. Luckily in edit mode we can trigger a title update using the inplace_editable module.\n *\n * @param {Object} details the update details.\n */\n _refreshSectionNumber({element}) {\n // Find the element.\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n // Job done. Nothing to refresh.\n return;\n }\n // Update section numbers in all data, css and YUI attributes.\n target.id = `section-${element.number}`;\n // YUI uses section number as section id in data-sectionid, in principle if a format use components\n // don't need this sectionid attribute anymore, but we keep the compatibility in case some plugin\n // use it for legacy purposes.\n target.dataset.sectionid = element.number;\n // The data-number is the attribute used by components to store the section number.\n target.dataset.number = element.number;\n\n // Update title and title inplace editable, if any.\n const inplace = inplaceeditable.getInplaceEditable(target.querySelector(this.selectors.SECTION_ITEM));\n if (inplace) {\n // The course content HTML can be modified at any moment, so the function need to do some checkings\n // to make sure the inplace editable still represents the same itemid.\n const currentvalue = inplace.getValue();\n const currentitemid = inplace.getItemId();\n // Unnamed sections must be recalculated.\n if (inplace.getValue() === '') {\n // The value to send can be an empty value if it is a default name.\n if (currentitemid == element.id && (currentvalue != element.rawtitle || element.rawtitle == '')) {\n inplace.setValue(element.rawtitle);\n }\n }\n }\n }\n\n /**\n * Refresh a section cm list.\n *\n * @param {details} details the update details\n * @property {object} details.element the state object\n */\n _refreshSectionCmlist({element}) {\n const cmlist = element.cmlist ?? [];\n const section = this.getElement(this.selectors.SECTION, element.id);\n const listparent = section?.querySelector(this.selectors.SECTION_CMLIST);\n // A method to create a fake element to be replaced when the item is ready.\n const createCm = this._createCmItem.bind(this);\n if (listparent) {\n this._fixOrder(listparent, cmlist, this.selectors.CM, this.dettachedCms, createCm);\n }\n }\n\n /**\n * Refresh the section list.\n *\n * @param {Object} details the update details.\n */\n _refreshCourseSectionlist({element}) {\n const sectionlist = element.sectionlist ?? [];\n const listparent = this.getElement(this.selectors.COURSE_SECTIONLIST);\n // For now section cannot be created at a frontend level.\n const createSection = () => undefined;\n if (listparent) {\n this._fixOrder(listparent, sectionlist, this.selectors.SECTION, this.dettachedSections, createSection);\n }\n }\n\n /**\n * Regenerate content indexes.\n *\n * This method is used when a legacy action refresh some content element.\n */\n _indexContents() {\n // Find unindexed sections.\n this._scanIndex(\n this.selectors.SECTION,\n this.sections,\n (item) => {\n return new Section(item);\n }\n );\n\n // Find unindexed cms.\n this._scanIndex(\n this.selectors.CM,\n this.cms,\n (item) => {\n return new CmItem(item);\n }\n );\n }\n\n /**\n * Reindex a content (section or cm) of the course content.\n *\n * This method is used internally by _indexContents.\n *\n * @param {string} selector the DOM selector to scan\n * @param {*} index the index attribute to update\n * @param {*} creationhandler method to create a new indexed element\n */\n _scanIndex(selector, index, creationhandler) {\n const items = this.getElements(`${selector}:not([data-indexed])`);\n items.forEach((item) => {\n if (!item?.dataset?.id) {\n return;\n }\n // Delete previous item component.\n if (index[item.dataset.id] !== undefined) {\n index[item.dataset.id].unregister();\n }\n // Create the new component.\n index[item.dataset.id] = creationhandler({\n ...this,\n element: item,\n });\n // Mark as indexed.\n item.dataset.indexed = true;\n });\n }\n\n /**\n * Reload a course module contents.\n *\n * Most course module HTML is still strongly backend dependant.\n * Some changes require to get a new version of the module.\n *\n * @param {details} param0 the watcher details\n * @property {object} param0.element the state object\n */\n _reloadCm({element}) {\n const cmitem = this.getElement(this.selectors.CM, element.id);\n if (cmitem) {\n const promise = courseActions.refreshModule(cmitem, element.id);\n promise.then(() => {\n this._indexContents();\n return;\n }).catch();\n }\n }\n\n /**\n * Create a new course module item in a section.\n *\n * Thos method will append a fake item in the container and trigger an ajax request to\n * replace the fake element by the real content.\n *\n * @param {Element} container the container element (section)\n * @param {Number} cmid the course-module ID\n * @returns {Element} the created element\n */\n _createCmItem(container, cmid) {\n const newItem = document.createElement(this.selectors.ACTIVITYTAG);\n newItem.dataset.for = 'cmitem';\n newItem.dataset.id = cmid;\n // The legacy actions.js requires a specific ID and class to refresh the CM.\n newItem.id = `module-${cmid}`;\n newItem.classList.add(this.classes.ACTIVITY);\n container.append(newItem);\n this._reloadCm({\n element: this.reactive.get('cm', cmid),\n });\n return newItem;\n }\n\n /**\n * Fix/reorder the section or cms order.\n *\n * @param {Element} container the HTML element to reorder.\n * @param {Array} neworder an array with the ids order\n * @param {string} selector the element selector\n * @param {Object} dettachedelements a list of dettached elements\n * @param {function} createMethod method to create missing elements\n */\n async _fixOrder(container, neworder, selector, dettachedelements, createMethod) {\n if (container === undefined) {\n return;\n }\n\n // Empty lists should not be visible.\n if (!neworder.length) {\n container.classList.add('hidden');\n container.innerHTML = '';\n return;\n }\n\n // Grant the list is visible (in case it was empty).\n container.classList.remove('hidden');\n\n // Move the elements in order at the beginning of the list.\n neworder.forEach((itemid, index) => {\n let item = this.getElement(selector, itemid) ?? dettachedelements[itemid] ?? createMethod(container, itemid);\n if (item === undefined) {\n // Missing elements cannot be sorted.\n return;\n }\n // Get the current elemnt at that position.\n const currentitem = container.children[index];\n if (currentitem === undefined) {\n container.append(item);\n return;\n }\n if (currentitem !== item) {\n container.insertBefore(item, currentitem);\n }\n });\n\n // Dndupload add a fake element we need to keep.\n let dndFakeActivity;\n\n // Remove the remaining elements.\n while (container.children.length > neworder.length) {\n const lastchild = container.lastChild;\n if (lastchild?.classList?.contains('dndupload-preview')) {\n dndFakeActivity = lastchild;\n } else {\n dettachedelements[lastchild?.dataset?.id ?? 0] = lastchild;\n }\n container.removeChild(lastchild);\n }\n // Restore dndupload fake element.\n if (dndFakeActivity) {\n container.append(dndFakeActivity);\n }\n }\n}\n"],"file":"content.min.js"} \ No newline at end of file +{"version":3,"sources":["../../src/local/content.js"],"names":["Component","name","selectors","SECTION","SECTION_ITEM","SECTION_CMLIST","COURSE_SECTIONLIST","CM","TOGGLER","COLLAPSE","classes","COLLAPSED","ACTIVITYTAG","ACTIVITY","STATEDREADY","dettachedCms","dettachedSections","sections","cms","_indexContents","addEventListener","element","_sectionTogglers","event","sectionlink","target","closest","isChevron","section","toggler","querySelector","isCollapsed","classList","contains","sectionId","getAttribute","reactive","dispatch","contentexpanded","supportComponents","isEditing","DispatchActions","add","watch","handler","_reloadCm","_refreshSectionNumber","_refreshSectionCollapsed","_startProcessing","_refreshCourseSectionlist","_refreshSectionCmlist","cmitem","getElement","id","courseActions","refreshModule","Error","click","number","dataset","sectionid","inplace","inplaceeditable","getInplaceEditable","currentvalue","getValue","currentitemid","getItemId","rawtitle","setValue","cmlist","listparent","createCm","_createCmItem","bind","_fixOrder","sectionlist","createSection","_scanIndex","item","Section","CmItem","selector","index","creationhandler","items","getElements","forEach","unregister","indexed","promise","then","catch","container","cmid","newItem","document","createElement","for","append","get","neworder","dettachedelements","createMethod","length","innerHTML","remove","itemid","currentitem","children","insertBefore","lastchild","lastChild","dndFakeActivity","removeChild","getElementById","BaseComponent"],"mappings":"mYA0BA,OACA,OACA,OAEA,OACA,O,4rFAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,eAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,OAAO,uBADM,CAEbC,YAAY,6BAFC,CAGbC,cAAc,sBAHD,CAIbC,kBAAkB,kCAJL,CAKbC,EAAE,sBALW,CAMbC,OAAO,+CANM,CAObC,QAAQ,6BAPK,CAAjB,CAUA,KAAKC,OAAL,CAAe,CACXC,SAAS,YADE,CAGXC,WAAW,CAAE,IAHF,CAMXC,QAAQ,WANG,CAOXC,WAAW,aAPA,CAAf,CAUA,KAAKC,YAAL,CAAoB,EAApB,CACA,KAAKC,iBAAL,CAAyB,EAAzB,CAEA,KAAKC,QAAL,CAAgB,EAAhB,CACA,KAAKC,GAAL,CAAW,EACd,C,+CAoBY,CACT,KAAKC,cAAL,GAEA,KAAKC,gBAAL,CAAsB,KAAKC,OAA3B,CAAoC,OAApC,CAA6C,KAAKC,gBAAlD,CACH,C,0DAUgBC,C,CAAO,IACdC,CAAAA,CAAW,CAAGD,CAAK,CAACE,MAAN,CAAaC,OAAb,CAAqB,KAAKxB,SAAL,CAAeM,OAApC,CADA,CAEdmB,CAAS,CAAGJ,CAAK,CAACE,MAAN,CAAaC,OAAb,CAAqB,KAAKxB,SAAL,CAAeO,QAApC,CAFE,CAIpB,GAAIe,CAAW,EAAIG,CAAnB,C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IE,CAAJ,CAAqB,CACjBpB,CAAS,CAACM,MAAV,CAAiBc,CAAjB,CACH,C,8IAnYOxF,C,CAAQvB,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBqB,OAAO,CAAE2E,QAAQ,CAACmB,cAAT,CAAwB1F,CAAxB,CADQ,CAEjBW,QAAQ,CAAE,8BAFO,CAGjBlC,SAAS,CAATA,CAHiB,CAAd,CAKV,C,cAjDkCkH,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index main component.\n *\n * @module core_courseformat/local/content\n * @class core_courseformat/local/content\n * @copyright 2020 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent} from 'core/reactive';\nimport {getCurrentCourseEditor} from 'core_courseformat/courseeditor';\nimport inplaceeditable from 'core/inplace_editable';\nimport Section from 'core_courseformat/local/content/section';\nimport CmItem from 'core_courseformat/local/content/section/cmitem';\n// Course actions is needed for actions that are not migrated to components.\nimport courseActions from 'core_course/actions';\nimport DispatchActions from 'core_courseformat/local/content/actions';\n\nexport default class Component extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'course_format';\n // Default query selectors.\n this.selectors = {\n SECTION: `[data-for='section']`,\n SECTION_ITEM: `[data-for='section_title']`,\n SECTION_CMLIST: `[data-for='cmlist']`,\n COURSE_SECTIONLIST: `[data-for='course_sectionlist']`,\n CM: `[data-for='cmitem']`,\n TOGGLER: `[data-action=\"togglecoursecontentsection\"]`,\n COLLAPSE: `[data-toggle=\"collapse\"]`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n COLLAPSED: `collapsed`,\n // Formats can override the activity tag but a default one is needed to create new elements.\n ACTIVITYTAG: 'li',\n\n // Course content classes.\n ACTIVITY: `activity`,\n STATEDREADY: `stateready`,\n };\n // Array to save dettached elements during element resorting.\n this.dettachedCms = {};\n this.dettachedSections = {};\n // Index of sections and cms components.\n this.sections = {};\n this.cms = {};\n }\n\n /**\n * Static method to create a component instance form the mustahce template.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n reactive: getCurrentCourseEditor(),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this._indexContents();\n // Activate section togglers.\n this.addEventListener(this.element, 'click', this._sectionTogglers);\n }\n\n /**\n * Setup sections toggler.\n *\n * Toggler click is delegated to the main course content element because new sections can\n * appear at any moment and this way we prevent accidental double bindings.\n *\n * @param {Event} event the triggered event\n */\n _sectionTogglers(event) {\n const sectionlink = event.target.closest(this.selectors.TOGGLER);\n const isChevron = event.target.closest(this.selectors.COLLAPSE);\n\n if (sectionlink || isChevron) {\n\n const section = event.target.closest(this.selectors.SECTION);\n const toggler = section.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (isChevron || isCollapsed) {\n // Update the state.\n const sectionId = section.getAttribute('data-id');\n this.reactive.dispatch(\n 'sectionPreferences',\n [sectionId],\n {\n contentexpanded: isCollapsed,\n },\n );\n }\n }\n }\n\n /**\n *\n * Course content elements could not provide JS Components because the elements HTML is applied\n * directly from the course actions. To keep internal components updated this module keeps\n * a list of the active components and mark them as \"indexed\". This way when any action replace\n * the HTML this component will recreate the components an add any necessary event listener.\n *\n * Format plugins can override this method to provide extra logic to the course frontend.\n *\n */\n stateReady() {\n this._indexContents();\n\n if (this.reactive.supportComponents) {\n // Actions are only available in edit mode.\n if (this.reactive.isEditing) {\n new DispatchActions(this);\n }\n\n // Mark content as state ready.\n this.element.classList.add(this.classes.STATEDREADY);\n }\n }\n\n /**\n * Return the component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n // Check if the course format is compatible with reactive components.\n if (!this.reactive.supportComponents) {\n return [];\n }\n return [\n // State changes that require to reload some course modules.\n {watch: `cm.visible:updated`, handler: this._reloadCm},\n // Update section number and title.\n {watch: `section.number:updated`, handler: this._refreshSectionNumber},\n // Collapse and expand sections.\n {watch: `section.contentexpanded:updated`, handler: this._refreshSectionCollapsed},\n // Sections and cm sorting.\n {watch: `transaction:start`, handler: this._startProcessing},\n {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist},\n {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist},\n // Reindex sections and cms.\n {watch: `state:updated`, handler: this._indexContents},\n // State changes thaty require to reload course modules.\n {watch: `cm.visible:updated`, handler: this._reloadCm},\n {watch: `cm.sectionid:updated`, handler: this._reloadCm},\n ];\n }\n\n /**\n * Reload a course module.\n *\n * Most course module HTML is still strongly backend dependant.\n * Some changes require to get a new version af the module.\n *\n * @param {Object} param\n * @param {Object} param.element update the state update data\n */\n _reloadCm({element}) {\n const cmitem = this.getElement(this.selectors.CM, element.id);\n if (cmitem) {\n courseActions.refreshModule(cmitem, element.id);\n }\n }\n\n /**\n * Update section collapsed.\n *\n * @param {object} args\n * @param {Object} args.element The element to update\n */\n _refreshSectionCollapsed({element}) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n throw new Error(`Unknown section with ID ${element.id}`);\n }\n // Check if it is already done.\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (element.contentexpanded === isCollapsed) {\n toggler.click();\n }\n }\n\n /**\n * Setup the component to start a transaction.\n *\n * Some of the course actions replaces the current DOM element with a new one before updating the\n * course state. This means the component cannot preload any index properly until the transaction starts.\n *\n */\n _startProcessing() {\n // During a section or cm sorting, some elements could be dettached from the DOM and we\n // need to store somewhare in case they are needed later.\n this.dettachedCms = {};\n this.dettachedSections = {};\n }\n\n /**\n * Update a course section when the section number changes.\n *\n * The courseActions module used for most course section tools still depends on css classes and\n * section numbers (not id). To prevent inconsistencies when a section is moved, we need to refresh\n * the\n *\n * Course formats can override the section title rendering so the frontend depends heavily on backend\n * rendering. Luckily in edit mode we can trigger a title update using the inplace_editable module.\n *\n * @param {Object} param\n * @param {Object} param.element details the update details.\n */\n _refreshSectionNumber({element}) {\n // Find the element.\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n // Job done. Nothing to refresh.\n return;\n }\n // Update section numbers in all data, css and YUI attributes.\n target.id = `section-${element.number}`;\n // YUI uses section number as section id in data-sectionid, in principle if a format use components\n // don't need this sectionid attribute anymore, but we keep the compatibility in case some plugin\n // use it for legacy purposes.\n target.dataset.sectionid = element.number;\n // The data-number is the attribute used by components to store the section number.\n target.dataset.number = element.number;\n\n // Update title and title inplace editable, if any.\n const inplace = inplaceeditable.getInplaceEditable(target.querySelector(this.selectors.SECTION_ITEM));\n if (inplace) {\n // The course content HTML can be modified at any moment, so the function need to do some checkings\n // to make sure the inplace editable still represents the same itemid.\n const currentvalue = inplace.getValue();\n const currentitemid = inplace.getItemId();\n // Unnamed sections must be recalculated.\n if (inplace.getValue() === '') {\n // The value to send can be an empty value if it is a default name.\n if (currentitemid == element.id && (currentvalue != element.rawtitle || element.rawtitle == '')) {\n inplace.setValue(element.rawtitle);\n }\n }\n }\n }\n\n /**\n * Refresh a section cm list.\n *\n * @param {Object} param\n * @param {Object} param.element details the update details.\n */\n _refreshSectionCmlist({element}) {\n const cmlist = element.cmlist ?? [];\n const section = this.getElement(this.selectors.SECTION, element.id);\n const listparent = section?.querySelector(this.selectors.SECTION_CMLIST);\n // A method to create a fake element to be replaced when the item is ready.\n const createCm = this._createCmItem.bind(this);\n if (listparent) {\n this._fixOrder(listparent, cmlist, this.selectors.CM, this.dettachedCms, createCm);\n }\n }\n\n /**\n * Refresh the section list.\n *\n * @param {Object} param\n * @param {Object} param.element details the update details.\n */\n _refreshCourseSectionlist({element}) {\n const sectionlist = element.sectionlist ?? [];\n const listparent = this.getElement(this.selectors.COURSE_SECTIONLIST);\n // For now section cannot be created at a frontend level.\n const createSection = () => undefined;\n if (listparent) {\n this._fixOrder(listparent, sectionlist, this.selectors.SECTION, this.dettachedSections, createSection);\n }\n }\n\n /**\n * Regenerate content indexes.\n *\n * This method is used when a legacy action refresh some content element.\n */\n _indexContents() {\n // Find unindexed sections.\n this._scanIndex(\n this.selectors.SECTION,\n this.sections,\n (item) => {\n return new Section(item);\n }\n );\n\n // Find unindexed cms.\n this._scanIndex(\n this.selectors.CM,\n this.cms,\n (item) => {\n return new CmItem(item);\n }\n );\n }\n\n /**\n * Reindex a content (section or cm) of the course content.\n *\n * This method is used internally by _indexContents.\n *\n * @param {string} selector the DOM selector to scan\n * @param {*} index the index attribute to update\n * @param {*} creationhandler method to create a new indexed element\n */\n _scanIndex(selector, index, creationhandler) {\n const items = this.getElements(`${selector}:not([data-indexed])`);\n items.forEach((item) => {\n if (!item?.dataset?.id) {\n return;\n }\n // Delete previous item component.\n if (index[item.dataset.id] !== undefined) {\n index[item.dataset.id].unregister();\n }\n // Create the new component.\n index[item.dataset.id] = creationhandler({\n ...this,\n element: item,\n });\n // Mark as indexed.\n item.dataset.indexed = true;\n });\n }\n\n /**\n * Reload a course module contents.\n *\n * Most course module HTML is still strongly backend dependant.\n * Some changes require to get a new version of the module.\n *\n * @param {object} param0 the watcher details\n * @param {object} param0.element the state object\n */\n _reloadCm({element}) {\n const cmitem = this.getElement(this.selectors.CM, element.id);\n if (cmitem) {\n const promise = courseActions.refreshModule(cmitem, element.id);\n promise.then(() => {\n this._indexContents();\n return;\n }).catch();\n }\n }\n\n /**\n * Create a new course module item in a section.\n *\n * Thos method will append a fake item in the container and trigger an ajax request to\n * replace the fake element by the real content.\n *\n * @param {Element} container the container element (section)\n * @param {Number} cmid the course-module ID\n * @returns {Element} the created element\n */\n _createCmItem(container, cmid) {\n const newItem = document.createElement(this.selectors.ACTIVITYTAG);\n newItem.dataset.for = 'cmitem';\n newItem.dataset.id = cmid;\n // The legacy actions.js requires a specific ID and class to refresh the CM.\n newItem.id = `module-${cmid}`;\n newItem.classList.add(this.classes.ACTIVITY);\n container.append(newItem);\n this._reloadCm({\n element: this.reactive.get('cm', cmid),\n });\n return newItem;\n }\n\n /**\n * Fix/reorder the section or cms order.\n *\n * @param {Element} container the HTML element to reorder.\n * @param {Array} neworder an array with the ids order\n * @param {string} selector the element selector\n * @param {Object} dettachedelements a list of dettached elements\n * @param {function} createMethod method to create missing elements\n */\n async _fixOrder(container, neworder, selector, dettachedelements, createMethod) {\n if (container === undefined) {\n return;\n }\n\n // Empty lists should not be visible.\n if (!neworder.length) {\n container.classList.add('hidden');\n container.innerHTML = '';\n return;\n }\n\n // Grant the list is visible (in case it was empty).\n container.classList.remove('hidden');\n\n // Move the elements in order at the beginning of the list.\n neworder.forEach((itemid, index) => {\n let item = this.getElement(selector, itemid) ?? dettachedelements[itemid] ?? createMethod(container, itemid);\n if (item === undefined) {\n // Missing elements cannot be sorted.\n return;\n }\n // Get the current elemnt at that position.\n const currentitem = container.children[index];\n if (currentitem === undefined) {\n container.append(item);\n return;\n }\n if (currentitem !== item) {\n container.insertBefore(item, currentitem);\n }\n });\n\n // Dndupload add a fake element we need to keep.\n let dndFakeActivity;\n\n // Remove the remaining elements.\n while (container.children.length > neworder.length) {\n const lastchild = container.lastChild;\n if (lastchild?.classList?.contains('dndupload-preview')) {\n dndFakeActivity = lastchild;\n } else {\n dettachedelements[lastchild?.dataset?.id ?? 0] = lastchild;\n }\n container.removeChild(lastchild);\n }\n // Restore dndupload fake element.\n if (dndFakeActivity) {\n container.append(dndFakeActivity);\n }\n }\n}\n"],"file":"content.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/content/section.min.js.map b/course/format/amd/build/local/content/section.min.js.map index fa7bf532c917c..4094148bf52f3 100644 --- a/course/format/amd/build/local/content/section.min.js.map +++ b/course/format/amd/build/local/content/section.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/content/section.js"],"names":["name","selectors","SECTION_ITEM","CM","classes","LOCKED","id","element","dataset","state","configState","reactive","isEditing","supportComponents","sectionItem","getElement","headerComponent","Header","fullregion","configDragDrop","watch","handler","_refreshSection","cms","getElements","length","classList","toggle","DRAGGING","dragging","locked","DndSection"],"mappings":"gQAwBA,OACA,O,8/EAOa,CAEL,KAAKA,IAAL,CAAY,iBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,YAAY,6BADC,CAEbC,EAAE,wBAFW,CAAjB,CAKA,KAAKC,OAAL,CAAe,CACXC,MAAM,CAAE,gBADG,CAAf,CAKA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,8CAOUG,C,CAAO,CACd,KAAKC,WAAL,CAAiBD,CAAjB,EAEA,GAAI,KAAKE,QAAL,CAAcC,SAAd,EAA2B,KAAKD,QAAL,CAAcE,iBAA7C,CAAgE,CAE5D,GAAMC,CAAAA,CAAW,CAAG,KAAKC,UAAL,CAAgB,KAAKd,SAAL,CAAeC,YAA/B,CAApB,CACA,GAAIY,CAAJ,CAAiB,CAEb,GAAME,CAAAA,CAAe,CAAG,GAAIC,UAAJ,MACjB,IADiB,EAEpBV,OAAO,CAAEO,CAFW,CAGpBI,UAAU,CAAE,KAAKX,OAHG,GAAxB,CAKA,KAAKY,cAAL,CAAoBH,CAApB,CACH,CACJ,CACJ,C,iDAOa,CACV,MAAO,CACH,CAACI,KAAK,mBAAa,KAAKd,EAAlB,aAAN,CAAuCe,OAAO,CAAE,KAAKC,eAArD,CADG,CAGV,C,6CAOW,CACR,GAAMC,CAAAA,CAAG,CAAG,KAAKC,WAAL,CAAiB,KAAKvB,SAAL,CAAeE,EAAhC,CAAZ,CAEA,GAAI,CAACoB,CAAD,EAAuB,CAAf,GAAAA,CAAG,CAACE,MAAhB,CAA8B,CAC1B,MAAO,KACV,CACD,MAAOF,CAAAA,CAAG,CAACA,CAAG,CAACE,MAAJ,CAAa,CAAd,CACb,C,0DAO0B,SAAVlB,CAAU,GAAVA,OAAU,CAEvB,KAAKA,OAAL,CAAamB,SAAb,CAAuBC,MAAvB,CAA8B,KAAKvB,OAAL,CAAawB,QAA3C,WAAqDrB,CAAO,CAACsB,QAA7D,oBACA,KAAKtB,OAAL,CAAamB,SAAb,CAAuBC,MAAvB,CAA8B,KAAKvB,OAAL,CAAaC,MAA3C,WAAmDE,CAAO,CAACuB,MAA3D,oBACA,KAAKA,MAAL,CAAcvB,CAAO,CAACuB,MACzB,C,cAhFwBC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course section format component.\n *\n * @module core_courseformat/local/content/section\n * @class core_courseformat/local/content/section\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Header from 'core_courseformat/local/content/section/header';\nimport DndSection from 'core_courseformat/local/courseeditor/dndsection';\n\nexport default class extends DndSection {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'content_section';\n // Default query selectors.\n this.selectors = {\n SECTION_ITEM: `[data-for='section_title']`,\n CM: `[data-for=\"cmitem\"]`,\n };\n // Most classes will be loaded later by DndCmItem.\n this.classes = {\n LOCKED: 'editinprogress',\n };\n\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Initial state ready method.\n *\n * @param {Object} state the initial state\n */\n stateReady(state) {\n this.configState(state);\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Section zero and other formats sections may not have a title to drag.\n const sectionItem = this.getElement(this.selectors.SECTION_ITEM);\n if (sectionItem) {\n // Init the inner dragable element.\n const headerComponent = new Header({\n ...this,\n element: sectionItem,\n fullregion: this.element,\n });\n this.configDragDrop(headerComponent);\n }\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `section[${this.id}]:updated`, handler: this._refreshSection},\n ];\n }\n\n /**\n * Get the last CM element of that section.\n *\n * @returns {element|null}\n */\n getLastCm() {\n const cms = this.getElements(this.selectors.CM);\n // DndUpload may add extra elements so :last-child selector cannot be used.\n if (!cms || cms.length === 0) {\n return null;\n }\n return cms[cms.length - 1];\n }\n\n /**\n * Update a course index section using the state information.\n *\n * @param {Object} details the update details.\n */\n _refreshSection({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n}\n"],"file":"section.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/content/section.js"],"names":["name","selectors","SECTION_ITEM","CM","classes","LOCKED","id","element","dataset","state","configState","reactive","isEditing","supportComponents","sectionItem","getElement","headerComponent","Header","fullregion","configDragDrop","watch","handler","_refreshSection","cms","getElements","length","classList","toggle","DRAGGING","dragging","locked","DndSection"],"mappings":"gQAwBA,OACA,O,8/EAOa,CAEL,KAAKA,IAAL,CAAY,iBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,YAAY,6BADC,CAEbC,EAAE,wBAFW,CAAjB,CAKA,KAAKC,OAAL,CAAe,CACXC,MAAM,CAAE,gBADG,CAAf,CAKA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,8CAOUG,C,CAAO,CACd,KAAKC,WAAL,CAAiBD,CAAjB,EAEA,GAAI,KAAKE,QAAL,CAAcC,SAAd,EAA2B,KAAKD,QAAL,CAAcE,iBAA7C,CAAgE,CAE5D,GAAMC,CAAAA,CAAW,CAAG,KAAKC,UAAL,CAAgB,KAAKd,SAAL,CAAeC,YAA/B,CAApB,CACA,GAAIY,CAAJ,CAAiB,CAEb,GAAME,CAAAA,CAAe,CAAG,GAAIC,UAAJ,MACjB,IADiB,EAEpBV,OAAO,CAAEO,CAFW,CAGpBI,UAAU,CAAE,KAAKX,OAHG,GAAxB,CAKA,KAAKY,cAAL,CAAoBH,CAApB,CACH,CACJ,CACJ,C,iDAOa,CACV,MAAO,CACH,CAACI,KAAK,mBAAa,KAAKd,EAAlB,aAAN,CAAuCe,OAAO,CAAE,KAAKC,eAArD,CADG,CAGV,C,6CAOW,CACR,GAAMC,CAAAA,CAAG,CAAG,KAAKC,WAAL,CAAiB,KAAKvB,SAAL,CAAeE,EAAhC,CAAZ,CAEA,GAAI,CAACoB,CAAD,EAAuB,CAAf,GAAAA,CAAG,CAACE,MAAhB,CAA8B,CAC1B,MAAO,KACV,CACD,MAAOF,CAAAA,CAAG,CAACA,CAAG,CAACE,MAAJ,CAAa,CAAd,CACb,C,0DAQ0B,SAAVlB,CAAU,GAAVA,OAAU,CAEvB,KAAKA,OAAL,CAAamB,SAAb,CAAuBC,MAAvB,CAA8B,KAAKvB,OAAL,CAAawB,QAA3C,WAAqDrB,CAAO,CAACsB,QAA7D,oBACA,KAAKtB,OAAL,CAAamB,SAAb,CAAuBC,MAAvB,CAA8B,KAAKvB,OAAL,CAAaC,MAA3C,WAAmDE,CAAO,CAACuB,MAA3D,oBACA,KAAKA,MAAL,CAAcvB,CAAO,CAACuB,MACzB,C,cAjFwBC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course section format component.\n *\n * @module core_courseformat/local/content/section\n * @class core_courseformat/local/content/section\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Header from 'core_courseformat/local/content/section/header';\nimport DndSection from 'core_courseformat/local/courseeditor/dndsection';\n\nexport default class extends DndSection {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'content_section';\n // Default query selectors.\n this.selectors = {\n SECTION_ITEM: `[data-for='section_title']`,\n CM: `[data-for=\"cmitem\"]`,\n };\n // Most classes will be loaded later by DndCmItem.\n this.classes = {\n LOCKED: 'editinprogress',\n };\n\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Initial state ready method.\n *\n * @param {Object} state the initial state\n */\n stateReady(state) {\n this.configState(state);\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Section zero and other formats sections may not have a title to drag.\n const sectionItem = this.getElement(this.selectors.SECTION_ITEM);\n if (sectionItem) {\n // Init the inner dragable element.\n const headerComponent = new Header({\n ...this,\n element: sectionItem,\n fullregion: this.element,\n });\n this.configDragDrop(headerComponent);\n }\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `section[${this.id}]:updated`, handler: this._refreshSection},\n ];\n }\n\n /**\n * Get the last CM element of that section.\n *\n * @returns {element|null}\n */\n getLastCm() {\n const cms = this.getElements(this.selectors.CM);\n // DndUpload may add extra elements so :last-child selector cannot be used.\n if (!cms || cms.length === 0) {\n return null;\n }\n return cms[cms.length - 1];\n }\n\n /**\n * Update a course index section using the state information.\n *\n * @param {object} param\n * @param {Object} param.element details the update details.\n */\n _refreshSection({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n}\n"],"file":"section.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/content/section/cmitem.min.js.map b/course/format/amd/build/local/content/section/cmitem.min.js.map index 026116a6bfafc..75da382d623c6 100644 --- a/course/format/amd/build/local/content/section/cmitem.min.js.map +++ b/course/format/amd/build/local/content/section/cmitem.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/local/content/section/cmitem.js"],"names":["name","selectors","DRAGICON","classes","LOCKED","id","element","dataset","configDragDrop","getElement","classList","add","watch","handler","unregister","_refreshCm","toggle","DRAGGING","dragging","locked","DndCmItem"],"mappings":"mNA0BA,uD,gwDAOa,CAEL,KAAKA,IAAL,CAAY,wBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,QAAQ,gBADK,CAAjB,CAIA,KAAKC,OAAL,CAAe,CACXC,MAAM,CAAE,gBADG,CAAf,CAIA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,+CAKY,OACT,KAAKG,cAAL,CAAoB,KAAKH,EAAzB,EACA,eAAKI,UAAL,CAAgB,KAAKR,SAAL,CAAeC,QAA/B,wBAA0CQ,SAA1C,CAAoDC,GAApD,CAAwD,KAAKR,OAAL,CAAaD,QAArE,CACH,C,iDAOa,CACV,MAAO,CACH,CAACU,KAAK,cAAQ,KAAKP,EAAb,aAAN,CAAkCQ,OAAO,CAAE,KAAKC,UAAhD,CADG,CAEH,CAACF,KAAK,cAAQ,KAAKP,EAAb,aAAN,CAAkCQ,OAAO,CAAE,KAAKE,UAAhD,CAFG,CAIV,C,gDAOqB,SAAVT,CAAU,GAAVA,OAAU,CAElB,KAAKA,OAAL,CAAaI,SAAb,CAAuBM,MAAvB,CAA8B,KAAKb,OAAL,CAAac,QAA3C,WAAqDX,CAAO,CAACY,QAA7D,oBACA,KAAKZ,OAAL,CAAaI,SAAb,CAAuBM,MAAvB,CAA8B,KAAKb,OAAL,CAAaC,MAA3C,WAAmDE,CAAO,CAACa,MAA3D,oBACA,KAAKA,MAAL,CAAcb,CAAO,CAACa,MACzB,C,cAlDwBC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course course module item component.\n *\n * This component is used to control specific course modules interactions like drag and drop.\n *\n * @module core_courseformat/local/content/section/cmitem\n * @class core_courseformat/local/content/section/cmitem\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DndCmItem from 'core_courseformat/local/courseeditor/dndcmitem';\n\nexport default class extends DndCmItem {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'content_section_cmitem';\n // Default query selectors.\n this.selectors = {\n DRAGICON: `.editing_move`,\n };\n // Most classes will be loaded later by DndCmItem.\n this.classes = {\n LOCKED: 'editinprogress',\n };\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this.configDragDrop(this.id);\n this.getElement(this.selectors.DRAGICON)?.classList.add(this.classes.DRAGICON);\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `cm[${this.id}]:deleted`, handler: this.unregister},\n {watch: `cm[${this.id}]:updated`, handler: this._refreshCm},\n ];\n }\n\n /**\n * Update a course index cm using the state information.\n *\n * @param {Object} details the update details.\n */\n _refreshCm({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n}"],"file":"cmitem.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../../src/local/content/section/cmitem.js"],"names":["name","selectors","DRAGICON","classes","LOCKED","id","element","dataset","configDragDrop","getElement","classList","add","watch","handler","unregister","_refreshCm","toggle","DRAGGING","dragging","locked","DndCmItem"],"mappings":"mNA0BA,uD,gwDAOa,CAEL,KAAKA,IAAL,CAAY,wBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,QAAQ,gBADK,CAAjB,CAIA,KAAKC,OAAL,CAAe,CACXC,MAAM,CAAE,gBADG,CAAf,CAIA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,+CAKY,OACT,KAAKG,cAAL,CAAoB,KAAKH,EAAzB,EACA,eAAKI,UAAL,CAAgB,KAAKR,SAAL,CAAeC,QAA/B,wBAA0CQ,SAA1C,CAAoDC,GAApD,CAAwD,KAAKR,OAAL,CAAaD,QAArE,CACH,C,iDAOa,CACV,MAAO,CACH,CAACU,KAAK,cAAQ,KAAKP,EAAb,aAAN,CAAkCQ,OAAO,CAAE,KAAKC,UAAhD,CADG,CAEH,CAACF,KAAK,cAAQ,KAAKP,EAAb,aAAN,CAAkCQ,OAAO,CAAE,KAAKE,UAAhD,CAFG,CAIV,C,gDAQqB,SAAVT,CAAU,GAAVA,OAAU,CAElB,KAAKA,OAAL,CAAaI,SAAb,CAAuBM,MAAvB,CAA8B,KAAKb,OAAL,CAAac,QAA3C,WAAqDX,CAAO,CAACY,QAA7D,oBACA,KAAKZ,OAAL,CAAaI,SAAb,CAAuBM,MAAvB,CAA8B,KAAKb,OAAL,CAAaC,MAA3C,WAAmDE,CAAO,CAACa,MAA3D,oBACA,KAAKA,MAAL,CAAcb,CAAO,CAACa,MACzB,C,cAnDwBC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course course module item component.\n *\n * This component is used to control specific course modules interactions like drag and drop.\n *\n * @module core_courseformat/local/content/section/cmitem\n * @class core_courseformat/local/content/section/cmitem\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DndCmItem from 'core_courseformat/local/courseeditor/dndcmitem';\n\nexport default class extends DndCmItem {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'content_section_cmitem';\n // Default query selectors.\n this.selectors = {\n DRAGICON: `.editing_move`,\n };\n // Most classes will be loaded later by DndCmItem.\n this.classes = {\n LOCKED: 'editinprogress',\n };\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this.configDragDrop(this.id);\n this.getElement(this.selectors.DRAGICON)?.classList.add(this.classes.DRAGICON);\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `cm[${this.id}]:deleted`, handler: this.unregister},\n {watch: `cm[${this.id}]:updated`, handler: this._refreshCm},\n ];\n }\n\n /**\n * Update a course index cm using the state information.\n *\n * @param {object} param\n * @param {Object} param.element details the update details.\n */\n _refreshCm({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n}\n"],"file":"cmitem.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseeditor/courseeditor.min.js.map b/course/format/amd/build/local/courseeditor/courseeditor.min.js.map index 555754129a670..a7ee4821e0af6 100644 --- a/course/format/amd/build/local/courseeditor/courseeditor.min.js.map +++ b/course/format/amd/build/local/courseeditor/courseeditor.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseeditor/courseeditor.js"],"names":["courseId","Error","_editing","_supportscomponents","getServerCourseState","stateData","log","error","setInitialState","isEditing","stateKey","newState","JSON","stringify","previousState","Storage","get","set","Date","now","setup","editing","supportscomponents","ajax","call","methodname","args","courseid","courseState","parse","course","section","cm","Exporter","key","dataJson","data","value","notification","exception","Reactive"],"mappings":"gTAgBA,OACA,OACA,OACA,OACA,O,muHA0Be,C,8FASMA,C,iGAET,KAAKA,Q,sBACC,IAAIC,CAAAA,KAAJ,uBAAyBD,CAAzB,4CAAoE,KAAKA,QAAzE,E,QAIV,KAAKE,QAAL,IACA,KAAKC,mBAAL,IAEA,KAAKH,QAAL,CAAgBA,CAAhB,C,wBAKsB,MAAKI,oBAAL,E,QAAlBC,C,6DAEAC,UAAIC,KAAJ,CAAU,2CAAV,EACAD,UAAIC,KAAJ,O,kCAIJ,KAAKC,eAAL,CAAqBH,CAArB,EAGA,GAAI,KAAKI,SAAT,CAAoB,CAChB,KAAKC,QAAL,CAAgB,IACnB,CAFD,IAEO,CAEGC,CAFH,CAEcC,IAAI,CAACC,SAAL,CAAeR,CAAf,CAFd,CAGGS,CAHH,CAGmBC,CAAO,CAACC,GAAR,kBAAsBhB,CAAtB,iBAHnB,CAIH,GAAIc,CAAa,GAAKH,CAAtB,CAAgC,CAC5BI,CAAO,CAACE,GAAR,kBAAsBjB,CAAtB,iBAA8CW,CAA9C,EACAI,CAAO,CAACE,GAAR,kBAAsBjB,CAAtB,cAA2CkB,IAAI,CAACC,GAAL,EAA3C,CACH,CACD,KAAKT,QA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AsB,KAAKjB,QAA3B,aAAuCkC,CAAvC,EAA8CtB,IAAI,CAACC,SAAL,CAAeuB,CAAf,CAA9C,CACV,C,iNAYiBV,C,uBAAAA,C,yFAEcA,C,6DAGxBY,UAAaC,SAAb,OAEA,4CAAe,WAAf,E,2JAzFQ,OACZ,iBAAO,KAAKrC,QAAZ,kBACH,C,6CAgBuB,OACpB,iBAAO,KAAKC,mBAAZ,kBACH,C,cA3HwBqC,U","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\nimport {Reactive} from 'core/reactive';\nimport notification from 'core/notification';\nimport Exporter from 'core_courseformat/local/courseeditor/exporter';\nimport log from 'core/log';\nimport ajax from 'core/ajax';\nimport * as Storage from 'core/sessionstorage';\n\n/**\n * Main course editor module.\n *\n * All formats can register new components on this object to create new reactive\n * UI components that watch the current course state.\n *\n * @module core_courseformat/local/courseeditor/courseeditor\n * @class core_courseformat/local/courseeditor/courseeditor\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nexport default class extends Reactive {\n\n /**\n * The current state cache key\n *\n * The state cache is considered dirty if the state changes from the last page or\n * if the page has editing mode on.\n *\n * @attribute stateKey\n * @type number|null\n * @default 1\n * @package\n */\n stateKey = 1;\n\n /**\n * Set up the course editor when the page is ready.\n *\n * The course can only be loaded once per instance. Otherwise an error is thrown.\n *\n * @param {number} courseId course id\n */\n async loadCourse(courseId) {\n\n if (this.courseId) {\n throw new Error(`Cannot load ${courseId}, course already loaded with id ${this.courseId}`);\n }\n\n // Default view format setup.\n this._editing = false;\n this._supportscomponents = false;\n\n this.courseId = courseId;\n\n let stateData;\n\n try {\n stateData = await this.getServerCourseState();\n } catch (error) {\n log.error(\"EXCEPTION RAISED WHILE INIT COURSE EDITOR\");\n log.error(error);\n return;\n }\n\n this.setInitialState(stateData);\n\n // In editing mode, the session cache is considered dirty always.\n if (this.isEditing) {\n this.stateKey = null;\n } else {\n // Check if the last state is the same as the cached one.\n const newState = JSON.stringify(stateData);\n const previousState = Storage.get(`course/${courseId}/staticState`);\n if (previousState !== newState) {\n Storage.set(`course/${courseId}/staticState`, newState);\n Storage.set(`course/${courseId}/stateKey`, Date.now());\n }\n this.stateKey = Storage.get(`course/${courseId}/stateKey`);\n }\n }\n\n /**\n * Setup the current view settings\n *\n * @param {Object} setup format, page and course settings\n * @property {boolean} setup.editing if the page is in edit mode\n * @property {boolean} setup.supportscomponents if the format supports components for content\n */\n setViewFormat(setup) {\n this._editing = setup.editing ?? false;\n this._supportscomponents = setup.supportscomponents ?? false;\n }\n\n /**\n * Load the current course state from the server.\n *\n * @returns {Object} the current course state\n */\n async getServerCourseState() {\n const courseState = await ajax.call([{\n methodname: 'core_courseformat_get_state',\n args: {\n courseid: this.courseId,\n }\n }])[0];\n\n const stateData = JSON.parse(courseState);\n\n return {\n course: {},\n section: [],\n cm: [],\n ...stateData,\n };\n }\n\n /**\n * Return the current edit mode.\n *\n * Components should use this method to check if edit mode is active.\n *\n * @return {boolean} if edit is enabled\n */\n get isEditing() {\n return this._editing ?? false;\n }\n\n /**\n * Return a data exporter to transform state part into mustache contexts.\n *\n * @return {Exporter} the exporter class\n */\n getExporter() {\n return new Exporter(this);\n }\n\n /**\n * Return if the current course support components to refresh the content.\n *\n * @returns {boolean} if the current content support components\n */\n get supportComponents() {\n return this._supportscomponents ?? false;\n }\n\n /**\n * Get a value from the course editor static storage if any.\n *\n * The course editor static storage uses the sessionStorage to store values from the\n * components. This is used to prevent unnecesary template loadings on every page. However,\n * the storage does not work if no sessionStorage can be used (in debug mode for example),\n * if the page is in editing mode or if the initial state change from the last page.\n *\n * @param {string} key the key to get\n * @return {boolean|string} the storage value or false if cannot be loaded\n */\n getStorageValue(key) {\n if (this.isEditing || !this.stateKey) {\n return false;\n }\n const dataJson = Storage.get(`course/${this.courseId}/${key}`);\n if (!dataJson) {\n return false;\n }\n // Check the stateKey.\n try {\n const data = JSON.parse(dataJson);\n if (data?.stateKey !== this.stateKey) {\n return false;\n }\n return data.value;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Stores a value into the course editor static storage if available\n *\n * @param {String} key the key to store\n * @param {*} value the value to store (must be compatible with JSON,stringify)\n * @returns {boolean} true if the value is stored\n */\n setStorageValue(key, value) {\n // Values cannot be stored on edit mode.\n if (this.isEditing) {\n return false;\n }\n const data = {\n stateKey: this.stateKey,\n value,\n };\n return Storage.set(`course/${this.courseId}/${key}`, JSON.stringify(data));\n }\n\n /**\n * Dispatch a change in the state.\n *\n * Usually reactive modules throw an error directly to the components when something\n * goes wrong. However, course editor can directly display a notification.\n *\n * @method dispatch\n * @param {string} actionName the action name (usually the mutation name)\n * @param {*} param any number of params the mutation needs.\n */\n async dispatch(...args) {\n try {\n await super.dispatch(...args);\n } catch (error) {\n // Display error modal.\n notification.exception(error);\n // Force unlock all elements.\n super.dispatch('unlockAll');\n }\n }\n}\n"],"file":"courseeditor.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseeditor/courseeditor.js"],"names":["courseId","Error","_editing","_supportscomponents","getServerCourseState","stateData","log","error","setInitialState","isEditing","stateKey","newState","JSON","stringify","previousState","Storage","get","set","Date","now","setup","editing","supportscomponents","ajax","call","methodname","args","courseid","courseState","parse","course","section","cm","Exporter","key","dataJson","data","value","notification","exception","Reactive"],"mappings":"gTAgBA,OACA,OACA,OACA,OACA,O,muHA0Be,C,8FASMA,C,iGAET,KAAKA,Q,sBACC,IAAIC,CAAAA,KAAJ,uBAAyBD,CAAzB,4CAAoE,KAAKA,QAAzE,E,QAIV,KAAKE,Q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Q,CAAGpB,CAAO,CAACC,GAAR,kBAAsB,KAAKhB,QAA3B,aAAuCkC,CAAvC,EAAjB,CACA,GAAI,CAACC,CAAL,CAAe,CACX,QACH,CAED,GAAI,CACA,GAAMC,CAAAA,CAAI,CAAGxB,IAAI,CAACiB,KAAL,CAAWM,CAAX,CAAb,CACA,GAAI,QAAAC,CAAI,WAAJA,SAAAA,CAAI,CAAE1B,QAAN,IAAmB,KAAKA,QAA5B,CAAsC,CAClC,QACH,CACD,MAAO0B,CAAAA,CAAI,CAACC,KACf,CAAC,MAAO9B,CAAP,CAAc,CACZ,QACH,CACJ,C,wDASe2B,C,CAAKG,C,CAAO,CAExB,GAAI,KAAK5B,SAAT,CAAoB,CAChB,QACH,CACD,GAAM2B,CAAAA,CAAI,CAAG,CACT1B,QAAQ,CAAE,KAAKA,QADN,CAET2B,KAAK,CAALA,CAFS,CAAb,CAIA,MAAOtB,CAAAA,CAAO,CAACE,GAAR,kBAAsB,KAAKjB,QAA3B,aAAuCkC,CAAvC,EAA8CtB,IAAI,CAACC,SAAL,CAAeuB,CAAf,CAA9C,CACV,C,iNAWiBV,C,uBAAAA,C,yFAEcA,C,6DAGxBY,UAAaC,SAAb,OAEA,4CAAe,WAAf,E,2JAxFQ,OACZ,iBAAO,KAAKrC,QAAZ,kBACH,C,6CAgBuB,OACpB,iBAAO,KAAKC,mBAAZ,kBACH,C,cA3HwBqC,U","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\nimport {Reactive} from 'core/reactive';\nimport notification from 'core/notification';\nimport Exporter from 'core_courseformat/local/courseeditor/exporter';\nimport log from 'core/log';\nimport ajax from 'core/ajax';\nimport * as Storage from 'core/sessionstorage';\n\n/**\n * Main course editor module.\n *\n * All formats can register new components on this object to create new reactive\n * UI components that watch the current course state.\n *\n * @module core_courseformat/local/courseeditor/courseeditor\n * @class core_courseformat/local/courseeditor/courseeditor\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nexport default class extends Reactive {\n\n /**\n * The current state cache key\n *\n * The state cache is considered dirty if the state changes from the last page or\n * if the page has editing mode on.\n *\n * @attribute stateKey\n * @type number|null\n * @default 1\n * @package\n */\n stateKey = 1;\n\n /**\n * Set up the course editor when the page is ready.\n *\n * The course can only be loaded once per instance. Otherwise an error is thrown.\n *\n * @param {number} courseId course id\n */\n async loadCourse(courseId) {\n\n if (this.courseId) {\n throw new Error(`Cannot load ${courseId}, course already loaded with id ${this.courseId}`);\n }\n\n // Default view format setup.\n this._editing = false;\n this._supportscomponents = false;\n\n this.courseId = courseId;\n\n let stateData;\n\n try {\n stateData = await this.getServerCourseState();\n } catch (error) {\n log.error(\"EXCEPTION RAISED WHILE INIT COURSE EDITOR\");\n log.error(error);\n return;\n }\n\n this.setInitialState(stateData);\n\n // In editing mode, the session cache is considered dirty always.\n if (this.isEditing) {\n this.stateKey = null;\n } else {\n // Check if the last state is the same as the cached one.\n const newState = JSON.stringify(stateData);\n const previousState = Storage.get(`course/${courseId}/staticState`);\n if (previousState !== newState) {\n Storage.set(`course/${courseId}/staticState`, newState);\n Storage.set(`course/${courseId}/stateKey`, Date.now());\n }\n this.stateKey = Storage.get(`course/${courseId}/stateKey`);\n }\n }\n\n /**\n * Setup the current view settings\n *\n * @param {Object} setup format, page and course settings\n * @param {boolean} setup.editing if the page is in edit mode\n * @param {boolean} setup.supportscomponents if the format supports components for content\n */\n setViewFormat(setup) {\n this._editing = setup.editing ?? false;\n this._supportscomponents = setup.supportscomponents ?? false;\n }\n\n /**\n * Load the current course state from the server.\n *\n * @returns {Object} the current course state\n */\n async getServerCourseState() {\n const courseState = await ajax.call([{\n methodname: 'core_courseformat_get_state',\n args: {\n courseid: this.courseId,\n }\n }])[0];\n\n const stateData = JSON.parse(courseState);\n\n return {\n course: {},\n section: [],\n cm: [],\n ...stateData,\n };\n }\n\n /**\n * Return the current edit mode.\n *\n * Components should use this method to check if edit mode is active.\n *\n * @return {boolean} if edit is enabled\n */\n get isEditing() {\n return this._editing ?? false;\n }\n\n /**\n * Return a data exporter to transform state part into mustache contexts.\n *\n * @return {Exporter} the exporter class\n */\n getExporter() {\n return new Exporter(this);\n }\n\n /**\n * Return if the current course support components to refresh the content.\n *\n * @returns {boolean} if the current content support components\n */\n get supportComponents() {\n return this._supportscomponents ?? false;\n }\n\n /**\n * Get a value from the course editor static storage if any.\n *\n * The course editor static storage uses the sessionStorage to store values from the\n * components. This is used to prevent unnecesary template loadings on every page. However,\n * the storage does not work if no sessionStorage can be used (in debug mode for example),\n * if the page is in editing mode or if the initial state change from the last page.\n *\n * @param {string} key the key to get\n * @return {boolean|string} the storage value or false if cannot be loaded\n */\n getStorageValue(key) {\n if (this.isEditing || !this.stateKey) {\n return false;\n }\n const dataJson = Storage.get(`course/${this.courseId}/${key}`);\n if (!dataJson) {\n return false;\n }\n // Check the stateKey.\n try {\n const data = JSON.parse(dataJson);\n if (data?.stateKey !== this.stateKey) {\n return false;\n }\n return data.value;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Stores a value into the course editor static storage if available\n *\n * @param {String} key the key to store\n * @param {*} value the value to store (must be compatible with JSON,stringify)\n * @returns {boolean} true if the value is stored\n */\n setStorageValue(key, value) {\n // Values cannot be stored on edit mode.\n if (this.isEditing) {\n return false;\n }\n const data = {\n stateKey: this.stateKey,\n value,\n };\n return Storage.set(`course/${this.courseId}/${key}`, JSON.stringify(data));\n }\n\n /**\n * Dispatch a change in the state.\n *\n * Usually reactive modules throw an error directly to the components when something\n * goes wrong. However, course editor can directly display a notification.\n *\n * @method dispatch\n * @param {mixed} args any number of params the mutation needs.\n */\n async dispatch(...args) {\n try {\n await super.dispatch(...args);\n } catch (error) {\n // Display error modal.\n notification.exception(error);\n // Force unlock all elements.\n super.dispatch('unlockAll');\n }\n }\n}\n"],"file":"courseeditor.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseeditor/dndsectionitem.min.js.map b/course/format/amd/build/local/courseeditor/dndsectionitem.min.js.map index f719a0bbc26ac..90bdda9d0005d 100644 --- a/course/format/amd/build/local/courseeditor/dndsectionitem.min.js.map +++ b/course/format/amd/build/local/courseeditor/dndsectionitem.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseeditor/dndsectionitem.js"],"names":["sectionid","state","fullregion","id","section","get","course","number","getDraggableData","_getDraggableData","reactive","isEditing","supportComponents","dragdrop","DragDrop","classes","getClasses","unregister","dropdata","dispatch","exporter","getExporter","sectionDraggableData","type","firstcmid","cmlist","element","classList","add","DROPZONE","remove","BaseComponent"],"mappings":"s8DAsCmBA,C,CAAWC,C,CAAOC,C,CAAY,CAEzC,KAAKC,EAAL,CAAUH,CAAV,CACA,GAAI,KAAKI,OAAL,SAAJ,CAAgC,CAC5B,KAAKA,OAAL,CAAeH,CAAK,CAACG,OAAN,CAAcC,GAAd,CAAkB,KAAKF,EAAvB,CAClB,CACD,GAAI,KAAKG,MAAL,SAAJ,CAA+B,CAC3B,KAAKA,MAAL,CAAcL,CAAK,CAACK,MACvB,CAGD,GAA0B,CAAtB,MAAKF,OAAL,CAAaG,MAAjB,CAA6B,CACzB,KAAKC,gBAAL,CAAwB,KAAKC,iBAChC,CAED,KAAKP,UAAL,CAAkBA,CAAlB,CAGA,GAAI,KAAKQ,QAAL,CAAcC,SAAd,EAA2B,KAAKD,QAAL,CAAcE,iBAA7C,CAAgE,CAE5D,KAAKC,QAAL,CAAgB,GAAIC,WAAJ,CAAa,IAAb,CAAhB,CAEA,KAAKC,OAAL,CAAe,KAAKF,QAAL,CAAcG,UAAd,EAClB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://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index section title draggable component.\n *\n * This component is used to control specific course section interactions like drag and drop\n * in both course index and course content.\n *\n * @module core_courseformat/local/courseeditor/dndsectionitem\n * @class core_courseformat/local/courseeditor/dndsectionitem\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent, DragDrop} from 'core/reactive';\n\nexport default class extends BaseComponent {\n\n /**\n * Initial state ready method.\n *\n * @param {number} sectionid the section id\n * @param {Object} state the initial state\n * @param {Element} fullregion the complete section region to mark as dragged\n */\n configDragDrop(sectionid, state, fullregion) {\n\n this.id = sectionid;\n if (this.section === undefined) {\n this.section = state.section.get(this.id);\n }\n if (this.course === undefined) {\n this.course = state.course;\n }\n\n // Prevent topic zero from being draggable.\n if (this.section.number > 0) {\n this.getDraggableData = this._getDraggableData;\n }\n\n this.fullregion = fullregion;\n\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Init the dropzone.\n this.dragdrop = new DragDrop(this);\n // Save dropzone classes.\n this.classes = this.dragdrop.getClasses();\n }\n }\n\n /**\n * Remove all subcomponents dependencies.\n */\n destroy() {\n if (this.dragdrop !== undefined) {\n this.dragdrop.unregister();\n }\n }\n\n // Drag and drop methods.\n\n /**\n * The element drop start hook.\n *\n * @param {Object} dropdata the dropdata\n */\n dragStart(dropdata) {\n this.reactive.dispatch('sectionDrag', [dropdata.id], true);\n }\n\n /**\n * The element end start hook.\n *\n * @param {Object} dropdata the dropdata\n */\n dragEnd(dropdata) {\n this.reactive.dispatch('sectionDrag', [dropdata.id], false);\n }\n\n /**\n * Get the draggable data of this component.\n *\n * @returns {Object} exported course module drop data\n */\n _getDraggableData() {\n const exporter = this.reactive.getExporter();\n return exporter.sectionDraggableData(this.reactive.state, this.id);\n }\n\n /**\n * Validate if the drop data can be dropped over the component.\n *\n * @param {Object} dropdata the exported drop data.\n * @returns {boolean}\n */\n validateDropData(dropdata) {\n // Course module validation.\n if (dropdata?.type === 'cm') {\n // The first section element is already there so we can ignore it.\n const firstcmid = this.section?.cmlist[0];\n return dropdata.id !== firstcmid;\n }\n return false;\n }\n\n /**\n * Display the component dropzone.\n *\n * @param {Object} dropdata the accepted drop data\n */\n showDropZone() {\n this.element.classList.add(this.classes.DROPZONE);\n }\n\n /**\n * Hide the component dropzone.\n */\n hideDropZone() {\n this.element.classList.remove(this.classes.DROPZONE);\n }\n\n /**\n * Drop event handler.\n *\n * @param {Object} dropdata the accepted drop data\n */\n drop(dropdata) {\n // Call the move mutation.\n if (dropdata.type == 'cm') {\n this.reactive.dispatch('cmMove', [dropdata.id], this.id, this.section?.cmlist[0]);\n }\n }\n}\n"],"file":"dndsectionitem.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseeditor/dndsectionitem.js"],"names":["sectionid","state","fullregion","id","section","get","course","number","getDraggableData","_getDraggableData","reactive","isEditing","supportComponents","dragdrop","DragDrop","classes","getClasses","unregister","dropdata","dispatch","exporter","getExporter","sectionDraggableData","type","firstcmid","cmlist","element","classList","add","DROPZONE","remove","BaseComponent"],"mappings":"s8DAsCmBA,C,CAAWC,C,CAAOC,C,CAAY,CAEzC,KAAKC,EAAL,CAAUH,CAAV,CACA,GAAI,KAAKI,OAAL,SAAJ,CAAgC,CAC5B,KAAKA,OAAL,CAAeH,CAAK,CAACG,OAAN,CAAcC,GAAd,CAAkB,KAAKF,EAAvB,CAClB,CACD,GAAI,KAAKG,MAAL,SAAJ,CAA+B,CAC3B,KAAKA,MAAL,CAAc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AAb,CAAuBG,MAAvB,CAA8B,KAAKf,OAAL,CAAac,QAA3C,CACH,C,kCAOIX,C,CAAU,CAEX,GAAqB,IAAjB,EAAAA,CAAQ,CAACK,IAAb,CAA2B,OACvB,KAAKb,QAAL,CAAcS,QAAd,CAAuB,QAAvB,CAAiC,CAACD,CAAQ,CAACf,EAAV,CAAjC,CAAgD,KAAKA,EAArD,WAAyD,KAAKC,OAA9D,qBAAyD,EAAcqB,MAAd,CAAqB,CAArB,CAAzD,CACH,CACJ,C,cAlHwBM,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index section title draggable component.\n *\n * This component is used to control specific course section interactions like drag and drop\n * in both course index and course content.\n *\n * @module core_courseformat/local/courseeditor/dndsectionitem\n * @class core_courseformat/local/courseeditor/dndsectionitem\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent, DragDrop} from 'core/reactive';\n\nexport default class extends BaseComponent {\n\n /**\n * Initial state ready method.\n *\n * @param {number} sectionid the section id\n * @param {Object} state the initial state\n * @param {Element} fullregion the complete section region to mark as dragged\n */\n configDragDrop(sectionid, state, fullregion) {\n\n this.id = sectionid;\n if (this.section === undefined) {\n this.section = state.section.get(this.id);\n }\n if (this.course === undefined) {\n this.course = state.course;\n }\n\n // Prevent topic zero from being draggable.\n if (this.section.number > 0) {\n this.getDraggableData = this._getDraggableData;\n }\n\n this.fullregion = fullregion;\n\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Init the dropzone.\n this.dragdrop = new DragDrop(this);\n // Save dropzone classes.\n this.classes = this.dragdrop.getClasses();\n }\n }\n\n /**\n * Remove all subcomponents dependencies.\n */\n destroy() {\n if (this.dragdrop !== undefined) {\n this.dragdrop.unregister();\n }\n }\n\n // Drag and drop methods.\n\n /**\n * The element drop start hook.\n *\n * @param {Object} dropdata the dropdata\n */\n dragStart(dropdata) {\n this.reactive.dispatch('sectionDrag', [dropdata.id], true);\n }\n\n /**\n * The element end start hook.\n *\n * @param {Object} dropdata the dropdata\n */\n dragEnd(dropdata) {\n this.reactive.dispatch('sectionDrag', [dropdata.id], false);\n }\n\n /**\n * Get the draggable data of this component.\n *\n * @returns {Object} exported course module drop data\n */\n _getDraggableData() {\n const exporter = this.reactive.getExporter();\n return exporter.sectionDraggableData(this.reactive.state, this.id);\n }\n\n /**\n * Validate if the drop data can be dropped over the component.\n *\n * @param {Object} dropdata the exported drop data.\n * @returns {boolean}\n */\n validateDropData(dropdata) {\n // Course module validation.\n if (dropdata?.type === 'cm') {\n // The first section element is already there so we can ignore it.\n const firstcmid = this.section?.cmlist[0];\n return dropdata.id !== firstcmid;\n }\n return false;\n }\n\n /**\n * Display the component dropzone.\n */\n showDropZone() {\n this.element.classList.add(this.classes.DROPZONE);\n }\n\n /**\n * Hide the component dropzone.\n */\n hideDropZone() {\n this.element.classList.remove(this.classes.DROPZONE);\n }\n\n /**\n * Drop event handler.\n *\n * @param {Object} dropdata the accepted drop data\n */\n drop(dropdata) {\n // Call the move mutation.\n if (dropdata.type == 'cm') {\n this.reactive.dispatch('cmMove', [dropdata.id], this.id, this.section?.cmlist[0]);\n }\n }\n}\n"],"file":"dndsectionitem.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseeditor/mutations.min.js.map b/course/format/amd/build/local/courseeditor/mutations.min.js.map index fb2b857db0a37..57b8ca438df3b 100644 --- a/course/format/amd/build/local/courseeditor/mutations.min.js.map +++ b/course/format/amd/build/local/courseeditor/mutations.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseeditor/mutations.js"],"names":["action","courseId","ids","targetSectionId","targetCmId","args","courseid","targetsectionid","targetcmid","ajax","call","methodname","ajaxresult","JSON","parse","stateManager","addUpdateTypes","prepareFields","_prepareFields","updateName","fields","locked","cmids","Error","course","get","cmLock","_callEditWebservice","id","updates","processUpdates","sectionIds","sectionLock","cmIds","dragValue","_setElementsValue","lockValue","name","fieldName","newValue","setReadOnly","forEach","element","state","section","cm","preferences","updatePreferences","sectionId","contentexpanded","isactive","prefKey","contentcollapsed","indexcollapsed","push","jsonString","stringify","M","util","set_user_preference"],"mappings":"8KAeA,uD,owBAwB8BA,C,CAAQC,C,CAAUC,C,CAAKC,C,CAAiBC,C,2FACxDC,C,CAAO,CACTL,MAAM,CAANA,CADS,CAETM,QAAQ,CAAEL,CAFD,CAGTC,GAAG,CAAHA,CAHS,C,CAKb,GAAIC,CAAJ,CAAqB,CACjBE,CAAI,CAACE,eAAL,CAAuBJ,CAC1B,CACD,GAAIC,CAAJ,CAAgB,CACZC,CAAI,CAACG,UAAL,CAAkBJ,CACrB,C,eACsBK,WAAKC,IAAL,CAAU,CAAC,CAC9BC,UAAU,CAAE,iCADkB,CAE9BN,IAAI,CAAJA,CAF8B,CAAD,CAAV,EAGnB,CAHmB,C,QAAnBO,C,iCAIGC,IAAI,CAACC,KAAL,CAAWF,CAAX,C,uJAWNG,C,CAAc,CAEfA,CAAY,CAACC,cAAb,CAA4B,CACxBC,aAAa,CAAE,KAAKC,cADI,CAA5B,CAGH,C,sDAYcH,C,CAAcI,C,CAAYC,C,CAAQ,CAE7CA,CAAM,CAACC,MAAP,IACA,MAAOD,CAAAA,CACV,C,4EAiBYL,C,CAAcO,C,CAAOnB,C,CAAiBC,C,gGAC3C,CAACD,CAAD,EAAoB,CAACC,C,uBACf,IAAImB,CAAAA,KAAJ,0D,QAEJC,C,CAAST,CAAY,CAACU,GAAb,CAAiB,QAAjB,C,CACf,KAA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CAAiB,QAAjB,C,gBACO,MAAKE,mBAAL,CAAyB,eAAzB,CAA0CH,CAAM,CAACI,EAAjD,CAAqDG,CAArD,C,QAAhBF,C,QACNd,CAAY,CAACe,cAAb,CAA4BD,CAA5B,EACA,KAAKG,WAAL,CAAiBjB,CAAjB,CAA+BgB,CAA/B,K,kMAQchB,C,2FACRS,C,CAAST,CAAY,CAACU,GAAb,CAAiB,QAAjB,C,gBACO,MAAKE,mBAAL,CAAyB,cAAzB,CAAyCH,CAAM,CAACI,EAAhD,C,QAAhBC,C,QACNd,CAAY,CAACe,cAAb,CAA4BD,CAA5B,E","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\nimport ajax from 'core/ajax';\n\n/**\n * Default mutation manager\n *\n * @module core_courseformat/local/courseeditor/mutations\n * @class core_courseformat/local/courseeditor/mutations\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nexport default class {\n\n // All course editor mutations for Moodle 4.0 will be located in this file.\n\n /**\n * Private method to call core_courseformat_update_course webservice.\n *\n * @method _callEditWebservice\n * @param {string} action\n * @param {number} courseId\n * @param {array} ids\n * @param {number} targetSectionId optional target section id (for moving actions)\n * @param {number} targetCmId optional target cm id (for moving actions)\n */\n async _callEditWebservice(action, courseId, ids, targetSectionId, targetCmId) {\n const args = {\n action,\n courseid: courseId,\n ids,\n };\n if (targetSectionId) {\n args.targetsectionid = targetSectionId;\n }\n if (targetCmId) {\n args.targetcmid = targetCmId;\n }\n let ajaxresult = await ajax.call([{\n methodname: 'core_courseformat_update_course',\n args,\n }])[0];\n return JSON.parse(ajaxresult);\n }\n\n\n /**\n * Mutation module initialize.\n *\n * The reactive instance will execute this method when addMutations or setMutation is invoked.\n *\n * @param {StateManager} stateManager the state manager\n */\n init(stateManager) {\n // Add a method to prepare the fields when some update is comming from the server.\n stateManager.addUpdateTypes({\n prepareFields: this._prepareFields,\n });\n }\n\n /**\n * Add default values to state elements.\n *\n * This method is called every time a webservice returns a update state message.\n *\n * @param {Object} stateManager the state manager\n * @param {String} updateName the state element to update\n * @param {Object} fields the new data\n * @returns {Object} final fields data\n */\n _prepareFields(stateManager, updateName, fields) {\n // Any update should unlock the element.\n fields.locked = false;\n return fields;\n }\n\n /**\n * Move course modules to specific course location.\n *\n * Note that one of targetSectionId or targetCmId should be provided in order to identify the\n * new location:\n * - targetCmId: the activities will be located avobe the target cm. The targetSectionId\n * value will be ignored in this case.\n * - targetSectionId: the activities will be appended to the section. In this case\n * targetSectionId should not be present.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmids the list of cm ids to move\n * @param {number} targetSectionId the target section id\n * @param {number} targetCmId the target course module id\n */\n async cmMove(stateManager, cmids, targetSectionId, targetCmId) {\n if (!targetSectionId && !targetCmId) {\n throw new Error(`Mutation cmMove requires targetSectionId or targetCmId`);\n }\n const course = stateManager.get('course');\n this.cmLock(stateManager, cmids, true);\n const updates = await this._callEditWebservice('cm_move', course.id, cmids, targetSectionId, targetCmId);\n stateManager.processUpdates(updates);\n this.cmLock(stateManager, cmids, false);\n }\n\n /**\n * Move course modules to specific course location.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids to move\n * @param {number} targetSectionId the target section id\n */\n async sectionMove(stateManager, sectionIds, targetSectionId) {\n if (!targetSectionId) {\n throw new Error(`Mutation sectionMove requires targetSectionId`);\n }\n const course = stateManager.get('course');\n this.sectionLock(stateManager, sectionIds, true);\n const updates = await this._callEditWebservice('section_move', course.id, sectionIds, targetSectionId);\n stateManager.processUpdates(updates);\n this.sectionLock(stateManager, sectionIds, false);\n }\n\n /**\n * Mark or unmark course modules as dragging.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmIds the list of course modules ids\n * @param {bool} dragValue the new dragging value\n */\n cmDrag(stateManager, cmIds, dragValue) {\n this._setElementsValue(stateManager, 'cm', cmIds, 'dragging', dragValue);\n }\n\n /**\n * Mark or unmark course sections as dragging.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids\n * @param {bool} dragValue the new dragging value\n */\n sectionDrag(stateManager, sectionIds, dragValue) {\n this._setElementsValue(stateManager, 'section', sectionIds, 'dragging', dragValue);\n }\n\n /**\n * Lock or unlock course modules.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmIds the list of course modules ids\n * @param {bool} lockValue the new locked value\n */\n cmLock(stateManager, cmIds, lockValue) {\n this._setElementsValue(stateManager, 'cm', cmIds, 'locked', lockValue);\n }\n\n /**\n * Lock or unlock course sections.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids\n * @param {bool} lockValue the new locked value\n */\n sectionLock(stateManager, sectionIds, lockValue) {\n this._setElementsValue(stateManager, 'section', sectionIds, 'locked', lockValue);\n }\n\n _setElementsValue(stateManager, name, ids, fieldName, newValue) {\n stateManager.setReadOnly(false);\n ids.forEach((id) => {\n const element = stateManager.get(name, id);\n if (element) {\n element[fieldName] = newValue;\n }\n });\n stateManager.setReadOnly(true);\n }\n\n /**\n * Unlock all course elements.\n *\n * @param {StateManager} stateManager the current state manager\n */\n unlockAll(stateManager) {\n const state = stateManager.state;\n stateManager.setReadOnly(false);\n state.section.forEach((section) => {\n section.locked = false;\n });\n state.cm.forEach((cm) => {\n cm.locked = false;\n });\n stateManager.setReadOnly(true);\n }\n\n /*\n * Get updated user preferences and state data related to some section ids.\n *\n * @param {StateManager} stateManager the current state\n * @param {array} sectionIds the list of section ids to update\n * @param {Object} preferences the new preferences values\n */\n async sectionPreferences(stateManager, sectionIds, preferences) {\n stateManager.setReadOnly(false);\n // Check if we need to update preferences.\n let updatePreferences = false;\n sectionIds.forEach(sectionId => {\n const section = stateManager.get('section', sectionId);\n if (section === undefined) {\n return;\n }\n let newValue = preferences.contentexpanded ?? section.contentexpanded;\n if (section.contentexpanded != newValue) {\n section.contentexpanded = newValue;\n updatePreferences = true;\n }\n newValue = preferences.isactive ?? section.isactive;\n if (section.isactive != newValue) {\n section.isactive = newValue;\n updatePreferences = true;\n }\n });\n stateManager.setReadOnly(true);\n\n if (updatePreferences) {\n // Build the preference structures.\n const course = stateManager.get('course');\n const state = stateManager.state;\n const prefKey = `coursesectionspreferences_${course.id}`;\n const preferences = {\n contentcollapsed: [],\n indexcollapsed: [],\n };\n state.section.forEach(section => {\n if (!section.contentexpanded) {\n preferences.contentcollapsed.push(section.id);\n }\n if (!section.isactive) {\n preferences.indexcollapsed.push(section.id);\n }\n });\n const jsonString = JSON.stringify(preferences);\n M.util.set_user_preference(prefKey, jsonString);\n }\n }\n\n /**\n * Get updated state data related to some cm ids.\n *\n * @method cmState\n * @param {StateManager} stateManager the current state\n * @param {array} cmids the list of cm ids to update\n */\n async cmState(stateManager, cmids) {\n this.cmLock(stateManager, cmids, true);\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('cm_state', course.id, cmids);\n stateManager.processUpdates(updates);\n this.cmLock(stateManager, cmids, false);\n }\n\n /**\n * Get updated state data related to some section ids.\n *\n * @method sectionState\n * @param {StateManager} stateManager the current state\n * @param {array} sectionIds the list of section ids to update\n */\n async sectionState(stateManager, sectionIds) {\n this.sectionLock(stateManager, sectionIds, true);\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('section_state', course.id, sectionIds);\n stateManager.processUpdates(updates);\n this.sectionLock(stateManager, sectionIds, false);\n }\n\n /**\n * Get the full updated state data of the course.\n *\n * @param {StateManager} stateManager the current state\n */\n async courseState(stateManager) {\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('course_state', course.id);\n stateManager.processUpdates(updates);\n }\n\n}\n"],"file":"mutations.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseeditor/mutations.js"],"names":["action","courseId","ids","targetSectionId","targetCmId","args","courseid","targetsectionid","targetcmid","ajax","call","methodname","ajaxresult","JSON","parse","stateManager","addUpdateTypes","prepareFields","_prepareFields","updateName","fields","locked","cmids","Error","course","get","cmLock","_callEditWebservice","id","updates","processUpdates","sectionIds","sectionLock","cmIds","dragValue","_setElementsValue","lockValue","name","fieldName","newValue","setReadOnly","forEach","element","state","section","cm","preferences","updatePreferences","sectionId","contentexpanded","isactive","prefKey","contentcollapsed","indexcollapsed","push","jsonString","stringify","M","util","set_user_preference"],"mappings":"8KAeA,uD,owBAwB8BA,C,CAAQC,C,CAAUC,C,CAAKC,C,CAAiBC,C,2FACxDC,C,CAAO,CACTL,MAAM,CAANA,CADS,CAETM,QAAQ,CAAEL,CAFD,CAGTC,GAAG,CAAHA,CAHS,C,CAKb,GAAIC,CAAJ,CAAqB,CACjBE,CAAI,CAACE,eAAL,CAAuBJ,CAC1B,CACD,GAAIC,CAAJ,CAAgB,CACZC,CAAI,CAACG,UAAL,CAAkBJ,CACrB,C,eACsBK,WAAKC,IAAL,CAAU,CAAC,CAC9BC,UAAU,CAAE,iCADkB,CAE9BN,IAAI,CAAJA,CAF8B,CAAD,CAAV,EAGnB,CAHmB,C,QAAnBO,C,iCAIGC,IAAI,CAACC,KAAL,CAAWF,CAAX,C,uJAWNG,C,CAAc,CAEfA,CAAY,CAACC,cAAb,CAA4B,CACxBC,aAAa,CAAE,KAAKC,cADI,CAA5B,CAGH,C,sDAYcH,C,CAAcI,C,CAAYC,C,CAAQ,CAE7CA,CAAM,CAACC,MAAP,IACA,MAAOD,CAAAA,CACV,C,4EAiBYL,C,CAAcO,C,CAAOnB,C,CAAiBC,C,gGAC3C,CAACD,CAAD,EAAoB,CAACC,C,uBACf,IAAImB,CAAAA,KAAJ,0D,QAEJC,C,CAAST,CAAY,CAACU,GAAb,CAAiB,Q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AAY,CAACU,GAAb,CAAiB,QAAjB,C,gBACO,MAAKE,mBAAL,CAAyB,eAAzB,CAA0CH,CAAM,CAACI,EAAjD,CAAqDG,CAArD,C,QAAhBF,C,QACNd,CAAY,CAACe,cAAb,CAA4BD,CAA5B,EACA,KAAKG,WAAL,CAAiBjB,CAAjB,CAA+BgB,CAA/B,K,kMAQchB,C,2FACRS,C,CAAST,CAAY,CAACU,GAAb,CAAiB,QAAjB,C,gBACO,MAAKE,mBAAL,CAAyB,cAAzB,CAAyCH,CAAM,CAACI,EAAhD,C,QAAhBC,C,QACNd,CAAY,CAACe,cAAb,CAA4BD,CAA5B,E","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\nimport ajax from 'core/ajax';\n\n/**\n * Default mutation manager\n *\n * @module core_courseformat/local/courseeditor/mutations\n * @class core_courseformat/local/courseeditor/mutations\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nexport default class {\n\n // All course editor mutations for Moodle 4.0 will be located in this file.\n\n /**\n * Private method to call core_courseformat_update_course webservice.\n *\n * @method _callEditWebservice\n * @param {string} action\n * @param {number} courseId\n * @param {array} ids\n * @param {number} targetSectionId optional target section id (for moving actions)\n * @param {number} targetCmId optional target cm id (for moving actions)\n */\n async _callEditWebservice(action, courseId, ids, targetSectionId, targetCmId) {\n const args = {\n action,\n courseid: courseId,\n ids,\n };\n if (targetSectionId) {\n args.targetsectionid = targetSectionId;\n }\n if (targetCmId) {\n args.targetcmid = targetCmId;\n }\n let ajaxresult = await ajax.call([{\n methodname: 'core_courseformat_update_course',\n args,\n }])[0];\n return JSON.parse(ajaxresult);\n }\n\n\n /**\n * Mutation module initialize.\n *\n * The reactive instance will execute this method when addMutations or setMutation is invoked.\n *\n * @param {StateManager} stateManager the state manager\n */\n init(stateManager) {\n // Add a method to prepare the fields when some update is comming from the server.\n stateManager.addUpdateTypes({\n prepareFields: this._prepareFields,\n });\n }\n\n /**\n * Add default values to state elements.\n *\n * This method is called every time a webservice returns a update state message.\n *\n * @param {Object} stateManager the state manager\n * @param {String} updateName the state element to update\n * @param {Object} fields the new data\n * @returns {Object} final fields data\n */\n _prepareFields(stateManager, updateName, fields) {\n // Any update should unlock the element.\n fields.locked = false;\n return fields;\n }\n\n /**\n * Move course modules to specific course location.\n *\n * Note that one of targetSectionId or targetCmId should be provided in order to identify the\n * new location:\n * - targetCmId: the activities will be located avobe the target cm. The targetSectionId\n * value will be ignored in this case.\n * - targetSectionId: the activities will be appended to the section. In this case\n * targetSectionId should not be present.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmids the list of cm ids to move\n * @param {number} targetSectionId the target section id\n * @param {number} targetCmId the target course module id\n */\n async cmMove(stateManager, cmids, targetSectionId, targetCmId) {\n if (!targetSectionId && !targetCmId) {\n throw new Error(`Mutation cmMove requires targetSectionId or targetCmId`);\n }\n const course = stateManager.get('course');\n this.cmLock(stateManager, cmids, true);\n const updates = await this._callEditWebservice('cm_move', course.id, cmids, targetSectionId, targetCmId);\n stateManager.processUpdates(updates);\n this.cmLock(stateManager, cmids, false);\n }\n\n /**\n * Move course modules to specific course location.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids to move\n * @param {number} targetSectionId the target section id\n */\n async sectionMove(stateManager, sectionIds, targetSectionId) {\n if (!targetSectionId) {\n throw new Error(`Mutation sectionMove requires targetSectionId`);\n }\n const course = stateManager.get('course');\n this.sectionLock(stateManager, sectionIds, true);\n const updates = await this._callEditWebservice('section_move', course.id, sectionIds, targetSectionId);\n stateManager.processUpdates(updates);\n this.sectionLock(stateManager, sectionIds, false);\n }\n\n /**\n * Mark or unmark course modules as dragging.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmIds the list of course modules ids\n * @param {bool} dragValue the new dragging value\n */\n cmDrag(stateManager, cmIds, dragValue) {\n this._setElementsValue(stateManager, 'cm', cmIds, 'dragging', dragValue);\n }\n\n /**\n * Mark or unmark course sections as dragging.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids\n * @param {bool} dragValue the new dragging value\n */\n sectionDrag(stateManager, sectionIds, dragValue) {\n this._setElementsValue(stateManager, 'section', sectionIds, 'dragging', dragValue);\n }\n\n /**\n * Lock or unlock course modules.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} cmIds the list of course modules ids\n * @param {bool} lockValue the new locked value\n */\n cmLock(stateManager, cmIds, lockValue) {\n this._setElementsValue(stateManager, 'cm', cmIds, 'locked', lockValue);\n }\n\n /**\n * Lock or unlock course sections.\n *\n * @param {StateManager} stateManager the current state manager\n * @param {array} sectionIds the list of section ids\n * @param {bool} lockValue the new locked value\n */\n sectionLock(stateManager, sectionIds, lockValue) {\n this._setElementsValue(stateManager, 'section', sectionIds, 'locked', lockValue);\n }\n\n _setElementsValue(stateManager, name, ids, fieldName, newValue) {\n stateManager.setReadOnly(false);\n ids.forEach((id) => {\n const element = stateManager.get(name, id);\n if (element) {\n element[fieldName] = newValue;\n }\n });\n stateManager.setReadOnly(true);\n }\n\n /**\n * Unlock all course elements.\n *\n * @param {StateManager} stateManager the current state manager\n */\n unlockAll(stateManager) {\n const state = stateManager.state;\n stateManager.setReadOnly(false);\n state.section.forEach((section) => {\n section.locked = false;\n });\n state.cm.forEach((cm) => {\n cm.locked = false;\n });\n stateManager.setReadOnly(true);\n }\n\n /*\n * Get updated user preferences and state data related to some section ids.\n *\n * @param {StateManager} stateManager the current state\n * @param {array} sectionIds the list of section ids to update\n * @param {Object} preferences the new preferences values\n */\n async sectionPreferences(stateManager, sectionIds, preferences) {\n stateManager.setReadOnly(false);\n // Check if we need to update preferences.\n let updatePreferences = false;\n sectionIds.forEach(sectionId => {\n const section = stateManager.get('section', sectionId);\n if (section === undefined) {\n return;\n }\n let newValue = preferences.contentexpanded ?? section.contentexpanded;\n if (section.contentexpanded != newValue) {\n section.contentexpanded = newValue;\n updatePreferences = true;\n }\n newValue = preferences.isactive ?? section.isactive;\n if (section.isactive != newValue) {\n section.isactive = newValue;\n updatePreferences = true;\n }\n });\n stateManager.setReadOnly(true);\n\n if (updatePreferences) {\n // Build the preference structures.\n const course = stateManager.get('course');\n const state = stateManager.state;\n const prefKey = `coursesectionspreferences_${course.id}`;\n const preferences = {\n contentcollapsed: [],\n indexcollapsed: [],\n };\n state.section.forEach(section => {\n if (!section.contentexpanded) {\n preferences.contentcollapsed.push(section.id);\n }\n if (!section.isactive) {\n preferences.indexcollapsed.push(section.id);\n }\n });\n const jsonString = JSON.stringify(preferences);\n M.util.set_user_preference(prefKey, jsonString);\n }\n }\n\n /**\n * Get updated state data related to some cm ids.\n *\n * @method cmState\n * @param {StateManager} stateManager the current state\n * @param {array} cmids the list of cm ids to update\n */\n async cmState(stateManager, cmids) {\n this.cmLock(stateManager, cmids, true);\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('cm_state', course.id, cmids);\n stateManager.processUpdates(updates);\n this.cmLock(stateManager, cmids, false);\n }\n\n /**\n * Get updated state data related to some section ids.\n *\n * @method sectionState\n * @param {StateManager} stateManager the current state\n * @param {array} sectionIds the list of section ids to update\n */\n async sectionState(stateManager, sectionIds) {\n this.sectionLock(stateManager, sectionIds, true);\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('section_state', course.id, sectionIds);\n stateManager.processUpdates(updates);\n this.sectionLock(stateManager, sectionIds, false);\n }\n\n /**\n * Get the full updated state data of the course.\n *\n * @param {StateManager} stateManager the current state\n */\n async courseState(stateManager) {\n const course = stateManager.get('course');\n const updates = await this._callEditWebservice('course_state', course.id);\n stateManager.processUpdates(updates);\n }\n\n}\n"],"file":"mutations.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseindex/cm.min.js.map b/course/format/amd/build/local/courseindex/cm.min.js.map index ab11bd03489a9..1699cf44e414f 100644 --- a/course/format/amd/build/local/courseindex/cm.min.js.map +++ b/course/format/amd/build/local/courseindex/cm.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseindex/cm.js"],"names":["Component","name","selectors","CM_NAME","classes","CMHIDDEN","LOCKED","id","element","dataset","configDragDrop","watch","handler","remove","_refreshCm","classList","toggle","visible","getElement","innerHTML","DRAGGING","dragging","locked","target","document","getElementById","DndCmItem"],"mappings":"2MA0BA,uD,+nDAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,gBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,OAAO,uBADM,CAAjB,CAIA,KAAKC,OAAL,CAAe,CACXC,QAAQ,CAAE,QADC,CAEXC,MAAM,CAAE,gBAFG,CAAf,CAKA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,+CAmBY,CACT,KAAKG,cAAL,CAAoB,KAAKH,EAAzB,CACH,C,iDAOa,CACV,MAAO,CACH,CAACI,KAAK,cAAQ,KAAKJ,EAAb,aAAN,CAAkCK,OAAO,CAAE,KAAKC,MAAhD,CADG,CAEH,CAACF,KAAK,cAAQ,KAAKJ,EAAb,aAAN,CAAkCK,OAAO,CAAE,KAAKE,UAAhD,CAFG,CAIV,C,gDAOqB,SAAVN,CAAU,GAAVA,OAAU,CAElB,KAAKA,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAaC,QAA3C,CAAqD,CAACG,CAAO,CAACS,OAA9D,EACA,KAAKC,UAAL,CAAgB,KAAKhB,SAAL,CAAeC,OAA/B,EAAwCgB,SAAxC,CAAoDX,CAAO,CAACP,IAA5D,CACA,KAAKO,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAagB,QAA3C,WAAqDZ,CAAO,CAACa,QAA7D,oBACA,KAAKb,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAaE,MAA3C,WAAmDE,CAAO,CAACc,MAA3D,oBACA,KAAKA,MAAL,CAAcd,CAAO,CAACc,MACzB,C,oCAtCWC,C,CAAQrB,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBQ,OAAO,CAAEgB,QAAQ,CAACC,cAAT,CAAwBF,CAAxB,CADQ,CAEjBrB,SAAS,CAATA,CAFiB,CAAd,CAIV,C,cAjCkCwB,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index cm component.\n *\n * This component is used to control specific course modules interactions like drag and drop.\n *\n * @module core_courseformat/local/courseindex/cm\n * @class core_courseformat/local/courseindex/cm\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DndCmItem from 'core_courseformat/local/courseeditor/dndcmitem';\n\nexport default class Component extends DndCmItem {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex_cm';\n // Default query selectors.\n this.selectors = {\n CM_NAME: `[data-for='cm_name']`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n CMHIDDEN: 'dimmed',\n LOCKED: 'editinprogress',\n };\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Static method to create a component instance form the mustache template.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this.configDragDrop(this.id);\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `cm[${this.id}]:deleted`, handler: this.remove},\n {watch: `cm[${this.id}]:updated`, handler: this._refreshCm},\n ];\n }\n\n /**\n * Update a course index cm using the state information.\n *\n * @param {Object} details the update details.\n */\n _refreshCm({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.CMHIDDEN, !element.visible);\n this.getElement(this.selectors.CM_NAME).innerHTML = element.name;\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n\n}\n"],"file":"cm.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseindex/cm.js"],"names":["Component","name","selectors","CM_NAME","classes","CMHIDDEN","LOCKED","id","element","dataset","configDragDrop","watch","handler","remove","_refreshCm","classList","toggle","visible","getElement","innerHTML","DRAGGING","dragging","locked","target","document","getElementById","DndCmItem"],"mappings":"2MA0BA,uD,+nDAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,gBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,OAAO,uBADM,CAAjB,CAIA,KAAKC,OAAL,CAAe,CACXC,QAAQ,CAAE,QADC,CAEXC,MAAM,CAAE,gBAFG,CAAf,CAKA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAAb,CAAqBF,EAClC,C,+CAmBY,CACT,KAAKG,cAAL,CAAoB,KAAKH,EAAzB,CACH,C,iDAOa,CACV,MAAO,CACH,CAACI,KAAK,cAAQ,KAAKJ,EAAb,aAAN,CAAkCK,OAAO,CAAE,KAAKC,MAAhD,CADG,CAEH,CAACF,KAAK,cAAQ,KAAKJ,EAAb,aAAN,CAAkCK,OAAO,CAAE,KAAKE,UAAhD,CAFG,CAIV,C,gDAQqB,SAAVN,CAAU,GAAVA,OAAU,CAElB,KAAKA,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAaC,QAA3C,CAAqD,CAACG,CAAO,CAACS,OAA9D,EACA,KAAKC,UAAL,CAAgB,KAAKhB,SAAL,CAAeC,OAA/B,EAAwCgB,SAAxC,CAAoDX,CAAO,CAACP,IAA5D,CACA,KAAKO,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAagB,QAA3C,WAAqDZ,CAAO,CAACa,QAA7D,oBACA,KAAKb,OAAL,CAAaO,SAAb,CAAuBC,MAAvB,CAA8B,KAAKZ,OAAL,CAAaE,MAA3C,WAAmDE,CAAO,CAACc,MAA3D,oBACA,KAAKA,MAAL,CAAcd,CAAO,CAACc,MACzB,C,oCAvCWC,C,CAAQrB,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBQ,OAAO,CAAEgB,QAAQ,CAACC,cAAT,CAAwBF,CAAxB,CADQ,CAEjBrB,SAAS,CAATA,CAFiB,CAAd,CAIV,C,cAjCkCwB,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index cm component.\n *\n * This component is used to control specific course modules interactions like drag and drop.\n *\n * @module core_courseformat/local/courseindex/cm\n * @class core_courseformat/local/courseindex/cm\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport DndCmItem from 'core_courseformat/local/courseeditor/dndcmitem';\n\nexport default class Component extends DndCmItem {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex_cm';\n // Default query selectors.\n this.selectors = {\n CM_NAME: `[data-for='cm_name']`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n CMHIDDEN: 'dimmed',\n LOCKED: 'editinprogress',\n };\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Static method to create a component instance form the mustache template.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n this.configDragDrop(this.id);\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `cm[${this.id}]:deleted`, handler: this.remove},\n {watch: `cm[${this.id}]:updated`, handler: this._refreshCm},\n ];\n }\n\n /**\n * Update a course index cm using the state information.\n *\n * @param {object} param\n * @param {Object} param.element details the update details.\n */\n _refreshCm({element}) {\n // Update classes.\n this.element.classList.toggle(this.classes.CMHIDDEN, !element.visible);\n this.getElement(this.selectors.CM_NAME).innerHTML = element.name;\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n }\n\n}\n"],"file":"cm.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseindex/courseindex.min.js.map b/course/format/amd/build/local/courseindex/courseindex.min.js.map index ea43b8b98c252..4a74dee1bb08b 100644 --- a/course/format/amd/build/local/courseindex/courseindex.min.js.map +++ b/course/format/amd/build/local/courseindex/courseindex.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseindex/courseindex.js"],"names":["Component","name","selectors","SECTION","SECTION_CMLIST","CM","TOGGLER","COLLAPSE","classes","SECTIONHIDDEN","CMHIDDEN","SECTIONCURRENT","COLLAPSED","sections","cms","addEventListener","element","_sectionTogglers","getElements","forEach","section","dataset","id","cm","watch","handler","_refreshSectionCollapsed","_createCm","_deleteCm","_refreshCourseSectionlist","_refreshSectionCmlist","event","sectionlink","target","closest","isChevron","toggler","querySelector","isCollapsed","classList","contains","sectionId","getAttribute","reactive","dispatch","isactive","getElement","Error","_expandSectionNode","forceValue","collapsibleId","replace","collapsible","document","getElementById","togglerValue","collapse","state","fakeelement","createElement","add","innerHTML","get","sectionid","exporter","getExporter","data","renderComponent","newcomponent","newelement","parentNode","replaceChild","cmlist","listparent","_fixOrder","sectionlist","container","neworder","allitems","length","remove","itemid","index","item","currentitem","children","append","insertBefore","removeChild","lastChild","BaseComponent"],"mappings":"iOA0BA,uD,87DAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,aAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,OAAO,uBADM,CAEbC,cAAc,sBAFD,CAGbC,EAAE,kBAHW,CAIbC,OAAO,6CAJM,CAKbC,QAAQ,6BALK,CAAjB,CAQA,KAAKC,OAAL,CAAe,CACXC,aAAa,CAAE,QADJ,CAEXC,QAAQ,CAAE,QAFC,CAGXC,cAAc,CAAE,SAHL,CAIXC,SAAS,YAJE,CAAf,CAOA,KAAKC,QAAL,CAAgB,EAAhB,CACA,KAAKC,GAAL,CAAW,EACd,C,+CAoBY,YAET,KAAKC,gBAAL,CAAsB,KAAKC,OAA3B,CAAoC,OAApC,CAA6C,KAAKC,gBAAlD,EAGA,GAAMJ,CAAAA,CAAQ,CAAG,KAAKK,WAAL,CAAiB,KAAKhB,SAAL,CAAeC,OAAhC,CAAjB,CACAU,CAAQ,CAACM,OAAT,CAAiB,SAACC,CAAD,CAAa,CAC1B,CAAI,CAACP,QAAL,CAAcO,CAAO,CAACC,OAAR,CAAgBC,EAA9B,EAAoC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AAAA,CAAJ,CAAc,CACjBgB,OAAO,CAAEqC,QAAQ,CAACC,cAAT,CAAwBrB,CAAxB,CADQ,CAEjBU,QAAQ,CAAE,8BAFO,CAGjBzC,SAAS,CAATA,CAHiB,CAAd,CAKV,C,cAzCkCwF,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index main component.\n *\n * @module core_courseformat/local/courseindex/courseindex\n * @class core_courseformat/local/courseindex/courseindex\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent} from 'core/reactive';\nimport {getCurrentCourseEditor} from 'core_courseformat/courseeditor';\nimport jQuery from 'jquery';\n\nexport default class Component extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex';\n // Default query selectors.\n this.selectors = {\n SECTION: `[data-for='section']`,\n SECTION_CMLIST: `[data-for='cmlist']`,\n CM: `[data-for='cm']`,\n TOGGLER: `[data-action=\"togglecourseindexsection\"]`,\n COLLAPSE: `[data-toggle=\"collapse\"]`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n SECTIONHIDDEN: 'dimmed',\n CMHIDDEN: 'dimmed',\n SECTIONCURRENT: 'current',\n COLLAPSED: `collapsed`,\n };\n // Arrays to keep cms and sections elements.\n this.sections = {};\n this.cms = {};\n }\n\n /**\n * Static method to create a component instance form the mustache template.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n reactive: getCurrentCourseEditor(),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n // Activate section togglers.\n this.addEventListener(this.element, 'click', this._sectionTogglers);\n\n // Get cms and sections elements.\n const sections = this.getElements(this.selectors.SECTION);\n sections.forEach((section) => {\n this.sections[section.dataset.id] = section;\n });\n const cms = this.getElements(this.selectors.CM);\n cms.forEach((cm) => {\n this.cms[cm.dataset.id] = cm;\n });\n }\n\n getWatchers() {\n return [\n {watch: `section.isactive:updated`, handler: this._refreshSectionCollapsed},\n {watch: `cm:created`, handler: this._createCm},\n {watch: `cm:deleted`, handler: this._deleteCm},\n // Sections and cm sorting.\n {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist},\n {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist},\n ];\n }\n\n /**\n * Setup sections toggler.\n *\n * Toggler click is delegated to the main course index element because new sections can\n * appear at any moment and this way we prevent accidental double bindings.\n *\n * @param {Event} event the triggered event\n */\n _sectionTogglers(event) {\n const sectionlink = event.target.closest(this.selectors.TOGGLER);\n const isChevron = event.target.closest(this.selectors.COLLAPSE);\n\n if (sectionlink || isChevron) {\n\n const section = event.target.closest(this.selectors.SECTION);\n const toggler = section.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (isChevron || isCollapsed) {\n // Update the state.\n const sectionId = section.getAttribute('data-id');\n this.reactive.dispatch(\n 'sectionPreferences',\n [sectionId],\n {\n isactive: isCollapsed,\n },\n );\n }\n }\n }\n\n /**\n * Update section collapsed.\n *\n * @param {Object} details the update details.\n */\n _refreshSectionCollapsed({element}) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n throw new Error(`Unkown section with ID ${element.id}`);\n }\n // Check if it is already done.\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (element.isactive === isCollapsed) {\n this._expandSectionNode(element);\n }\n }\n\n /**\n * Expand a section node.\n *\n * By default the method will use element.isactive to decide if the\n * section is opened or closed. However, using forceValue it is possible\n * to open or close a section independant from the isactive attribute.\n *\n * @param {Object} element the course module state element\n * @param {boolean} forceValue optional forced expanded value\n */\n _expandSectionNode(element, forceValue) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n let collapsibleId = toggler.dataset.target ?? toggler.getAttribute(\"href\");\n if (!collapsibleId) {\n return;\n }\n collapsibleId = collapsibleId.replace('#', '');\n const collapsible = document.getElementById(collapsibleId);\n if (!collapsible) {\n return;\n }\n\n if (forceValue === undefined) {\n forceValue = (element.isactive) ? true : false;\n }\n\n // Course index is based on Bootstrap 4 collapsibles. To collapse them we need jQuery to\n // interact with collapsibles methods. Hopefully, this will change in Bootstrap 5 because\n // it does not require jQuery anymore.\n const togglerValue = (forceValue) ? 'show' : 'hide';\n jQuery(collapsible).collapse(togglerValue);\n }\n\n /**\n * Create a newcm instance.\n *\n * @param {Object} details the update details.\n */\n async _createCm({state, element}) {\n // Create a fake node while the component is loading.\n const fakeelement = document.createElement('li');\n fakeelement.classList.add('bg-pulse-grey', 'w-100');\n fakeelement.innerHTML = ' ';\n this.cms[element.id] = fakeelement;\n // Place the fake node on the correct position.\n this._refreshSectionCmlist({\n state,\n element: state.section.get(element.sectionid),\n });\n // Collect render data.\n const exporter = this.reactive.getExporter();\n const data = exporter.cm(state, element);\n // Create the new content.\n const newcomponent = await this.renderComponent(fakeelement, 'core_courseformat/local/courseindex/cm', data);\n // Replace the fake node with the real content.\n const newelement = newcomponent.getElement();\n this.cms[element.id] = newelement;\n fakeelement.parentNode.replaceChild(newelement, fakeelement);\n }\n\n /**\n * Refresh a section cm list.\n *\n * @param {Object} details the update details.\n */\n _refreshSectionCmlist({element}) {\n const cmlist = element.cmlist ?? [];\n const listparent = this.getElement(this.selectors.SECTION_CMLIST, element.id);\n this._fixOrder(listparent, cmlist, this.cms);\n }\n\n /**\n * Refresh the section list.\n *\n * @param {Object} details the update details.\n */\n _refreshCourseSectionlist({element}) {\n const sectionlist = element.sectionlist ?? [];\n this._fixOrder(this.element, sectionlist, this.sections);\n }\n\n /**\n * Fix/reorder the section or cms order.\n *\n * @param {Element} container the HTML element to reorder.\n * @param {Array} neworder an array with the ids order\n * @param {Array} allitems the list of html elements that can be placed in the container\n */\n _fixOrder(container, neworder, allitems) {\n\n // Empty lists should not be visible.\n if (!neworder.length) {\n container.classList.add('hidden');\n container.innerHTML = '';\n return;\n }\n\n // Grant the list is visible (in case it was empty).\n container.classList.remove('hidden');\n\n // Move the elements in order at the beginning of the list.\n neworder.forEach((itemid, index) => {\n const item = allitems[itemid];\n // Get the current element at that position.\n const currentitem = container.children[index];\n if (currentitem === undefined) {\n container.append(item);\n return;\n }\n if (currentitem !== item) {\n container.insertBefore(item, currentitem);\n }\n });\n // Remove the remaining elements.\n while (container.children.length > neworder.length) {\n container.removeChild(container.lastChild);\n }\n }\n\n /**\n * Remove a cm from the list.\n *\n * The actual DOM element removal is delegated to the cm component.\n *\n * @param {Object} details the update details.\n */\n _deleteCm({element}) {\n delete this.cms[element.id];\n }\n}\n"],"file":"courseindex.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseindex/courseindex.js"],"names":["Component","name","selectors","SECTION","SECTION_CMLIST","CM","TOGGLER","COLLAPSE","classes","SECTIONHIDDEN","CMHIDDEN","SECTIONCURRENT","COLLAPSED","sections","cms","addEventListener","element","_sectionTogglers","getElements","forEach","section","dataset","id","cm","watch","handler","_refreshSectionCollapsed","_createCm","_deleteCm","_refreshCourseSectionlist","_refreshSectionCmlist","event","sectionlink","target","closest","isChevron","toggler","querySelector","isCollapsed","classList","contains","sectionId","getAttribute","reactive","dispatch","isactive","getElement","Error","_expandSectionNode","forceValue","collapsibleId","replace","collapsible","document","getElementById","togglerValue","collapse","state","fakeelement","createElement","add","innerHTML","get","sectionid","exporter","getExporter","data","renderComponent","newcomponent","newelement","parentNode","replaceChild","cmlist","listparent","_fixOrder","sectionlist","container","neworder","allitems","length","remove","itemid","index","item","currentitem","children","append","insertBefore","removeChild","lastChild","BaseComponent"],"mappings":"iOA0BA,uD,87DAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,aAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,OAAO,uBADM,CAEbC,cAAc,sBAFD,CAGbC,EAAE,kBAHW,CAIbC,OAAO,6CAJM,CAKbC,QAAQ,6BALK,CAAjB,CAQA,KAAKC,OAAL,CAAe,CACXC,aAAa,CAAE,QADJ,CAEXC,QAAQ,CAAE,QAFC,CAGXC,cAAc,CAAE,SAHL,CAIXC,SAAS,YAJE,CAAf,CAOA,KAAKC,QAAL,CAAgB,EAAhB,CACA,KAAKC,GAAL,CAAW,EACd,C,+CAoBY,YAET,KAAKC,gBAAL,CAAsB,KAAKC,OAA3B,CAAoC,OAApC,CAA6C,KAAKC,gBAAlD,EAGA,GAAMJ,CAAAA,CAAQ,CAAG,KAAKK,WAAL,CAAiB,KAAKhB,SAAL,CAAeC,OAAhC,CAAjB,CACAU,CAAQ,CAACM,OAAT,CAAiB,SAACC,CAAD,CAAa,CAC1B,CAAI,CAACP,QAAL,CAAcO,CAAO,CAACC,OAAR,CAAgBC,EAA9B,EAAoCF,CACvC,CAFD,EAGA,GAAMN,CAAAA,CAAG,CAAG,KAAKI,WAAL,CAAiB,KAAKhB,SAAL,CAAeG,EAAhC,CAAZ,CACAS,CAAG,CAACK,OAAJ,CAAY,SAACI,CAAD,CAAQ,CAChB,CAAI,CAACT,GAAL,CAASS,CAAE,CAACF,OAAH,CAAWC,EAApB,EAA0BC,CAC7B,CAFD,CAGH,C,iDAEa,CACV,MAAO,CACH,CAACC,KAAK,2BAAN,CAAoCC,OAAO,CAAE,KAAKC,wBAAlD,CADG,CAEH,CAACF,KAAK,aAAN,CAAsBC,OAAO,CAAE,KAAKE,SAApC,CAFG,CAGH,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AACrC,SAAV,CAAoBqB,GAApB,CAAwB,QAAxB,EACAgB,CAAS,CAACf,SAAV,CAAsB,EAAtB,CACA,MACH,CAGDe,CAAS,CAACrC,SAAV,CAAoByC,MAApB,CAA2B,QAA3B,EAGAH,CAAQ,CAAC1D,OAAT,CAAiB,SAAC8D,CAAD,CAASC,CAAT,CAAmB,IAC1BC,CAAAA,CAAI,CAAGL,CAAQ,CAACG,CAAD,CADW,CAG1BG,CAAW,CAAGR,CAAS,CAACS,QAAV,CAAmBH,CAAnB,CAHY,CAIhC,GAAIE,CAAW,SAAf,CAA+B,CAC3BR,CAAS,CAACU,MAAV,CAAiBH,CAAjB,EACA,MACH,CACD,GAAIC,CAAW,GAAKD,CAApB,CAA0B,CACtBP,CAAS,CAACW,YAAV,CAAuBJ,CAAvB,CAA6BC,CAA7B,CACH,CACJ,CAXD,EAaA,MAAOR,CAAS,CAACS,QAAV,CAAmBN,MAAnB,CAA4BF,CAAQ,CAACE,MAA5C,CAAoD,CAChDH,CAAS,CAACY,WAAV,CAAsBZ,CAAS,CAACa,SAAhC,CACH,CACJ,C,8CAUoB,IAAVzE,CAAAA,CAAU,GAAVA,OAAU,CACjB,MAAO,MAAKF,GAAL,CAASE,CAAO,CAACM,EAAjB,CACV,C,oCA/NWW,C,CAAQ/B,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBgB,OAAO,CAAEqC,QAAQ,CAACC,cAAT,CAAwBrB,CAAxB,CADQ,CAEjBU,QAAQ,CAAE,8BAFO,CAGjBzC,SAAS,CAATA,CAHiB,CAAd,CAKV,C,cAzCkCwF,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index main component.\n *\n * @module core_courseformat/local/courseindex/courseindex\n * @class core_courseformat/local/courseindex/courseindex\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent} from 'core/reactive';\nimport {getCurrentCourseEditor} from 'core_courseformat/courseeditor';\nimport jQuery from 'jquery';\n\nexport default class Component extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex';\n // Default query selectors.\n this.selectors = {\n SECTION: `[data-for='section']`,\n SECTION_CMLIST: `[data-for='cmlist']`,\n CM: `[data-for='cm']`,\n TOGGLER: `[data-action=\"togglecourseindexsection\"]`,\n COLLAPSE: `[data-toggle=\"collapse\"]`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n SECTIONHIDDEN: 'dimmed',\n CMHIDDEN: 'dimmed',\n SECTIONCURRENT: 'current',\n COLLAPSED: `collapsed`,\n };\n // Arrays to keep cms and sections elements.\n this.sections = {};\n this.cms = {};\n }\n\n /**\n * Static method to create a component instance form the mustache template.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n reactive: getCurrentCourseEditor(),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n */\n stateReady() {\n // Activate section togglers.\n this.addEventListener(this.element, 'click', this._sectionTogglers);\n\n // Get cms and sections elements.\n const sections = this.getElements(this.selectors.SECTION);\n sections.forEach((section) => {\n this.sections[section.dataset.id] = section;\n });\n const cms = this.getElements(this.selectors.CM);\n cms.forEach((cm) => {\n this.cms[cm.dataset.id] = cm;\n });\n }\n\n getWatchers() {\n return [\n {watch: `section.isactive:updated`, handler: this._refreshSectionCollapsed},\n {watch: `cm:created`, handler: this._createCm},\n {watch: `cm:deleted`, handler: this._deleteCm},\n // Sections and cm sorting.\n {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist},\n {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist},\n ];\n }\n\n /**\n * Setup sections toggler.\n *\n * Toggler click is delegated to the main course index element because new sections can\n * appear at any moment and this way we prevent accidental double bindings.\n *\n * @param {Event} event the triggered event\n */\n _sectionTogglers(event) {\n const sectionlink = event.target.closest(this.selectors.TOGGLER);\n const isChevron = event.target.closest(this.selectors.COLLAPSE);\n\n if (sectionlink || isChevron) {\n\n const section = event.target.closest(this.selectors.SECTION);\n const toggler = section.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (isChevron || isCollapsed) {\n // Update the state.\n const sectionId = section.getAttribute('data-id');\n this.reactive.dispatch(\n 'sectionPreferences',\n [sectionId],\n {\n isactive: isCollapsed,\n },\n );\n }\n }\n }\n\n /**\n * Update section collapsed.\n *\n * @param {object} args\n * @param {object} args.element The leement to be expanded\n */\n _refreshSectionCollapsed({element}) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n if (!target) {\n throw new Error(`Unkown section with ID ${element.id}`);\n }\n // Check if it is already done.\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;\n\n if (element.isactive === isCollapsed) {\n this._expandSectionNode(element);\n }\n }\n\n /**\n * Expand a section node.\n *\n * By default the method will use element.isactive to decide if the\n * section is opened or closed. However, using forceValue it is possible\n * to open or close a section independant from the isactive attribute.\n *\n * @param {Object} element the course module state element\n * @param {boolean} forceValue optional forced expanded value\n */\n _expandSectionNode(element, forceValue) {\n const target = this.getElement(this.selectors.SECTION, element.id);\n const toggler = target.querySelector(this.selectors.COLLAPSE);\n let collapsibleId = toggler.dataset.target ?? toggler.getAttribute(\"href\");\n if (!collapsibleId) {\n return;\n }\n collapsibleId = collapsibleId.replace('#', '');\n const collapsible = document.getElementById(collapsibleId);\n if (!collapsible) {\n return;\n }\n\n if (forceValue === undefined) {\n forceValue = (element.isactive) ? true : false;\n }\n\n // Course index is based on Bootstrap 4 collapsibles. To collapse them we need jQuery to\n // interact with collapsibles methods. Hopefully, this will change in Bootstrap 5 because\n // it does not require jQuery anymore.\n const togglerValue = (forceValue) ? 'show' : 'hide';\n jQuery(collapsible).collapse(togglerValue);\n }\n\n /**\n * Create a newcm instance.\n *\n * @param {object} param\n * @param {Object} param.state\n * @param {Object} param.element\n */\n async _createCm({state, element}) {\n // Create a fake node while the component is loading.\n const fakeelement = document.createElement('li');\n fakeelement.classList.add('bg-pulse-grey', 'w-100');\n fakeelement.innerHTML = ' ';\n this.cms[element.id] = fakeelement;\n // Place the fake node on the correct position.\n this._refreshSectionCmlist({\n state,\n element: state.section.get(element.sectionid),\n });\n // Collect render data.\n const exporter = this.reactive.getExporter();\n const data = exporter.cm(state, element);\n // Create the new content.\n const newcomponent = await this.renderComponent(fakeelement, 'core_courseformat/local/courseindex/cm', data);\n // Replace the fake node with the real content.\n const newelement = newcomponent.getElement();\n this.cms[element.id] = newelement;\n fakeelement.parentNode.replaceChild(newelement, fakeelement);\n }\n\n /**\n * Refresh a section cm list.\n *\n * @param {object} param\n * @param {Object} param.element\n */\n _refreshSectionCmlist({element}) {\n const cmlist = element.cmlist ?? [];\n const listparent = this.getElement(this.selectors.SECTION_CMLIST, element.id);\n this._fixOrder(listparent, cmlist, this.cms);\n }\n\n /**\n * Refresh the section list.\n *\n * @param {object} param\n * @param {Object} param.element\n */\n _refreshCourseSectionlist({element}) {\n const sectionlist = element.sectionlist ?? [];\n this._fixOrder(this.element, sectionlist, this.sections);\n }\n\n /**\n * Fix/reorder the section or cms order.\n *\n * @param {Element} container the HTML element to reorder.\n * @param {Array} neworder an array with the ids order\n * @param {Array} allitems the list of html elements that can be placed in the container\n */\n _fixOrder(container, neworder, allitems) {\n\n // Empty lists should not be visible.\n if (!neworder.length) {\n container.classList.add('hidden');\n container.innerHTML = '';\n return;\n }\n\n // Grant the list is visible (in case it was empty).\n container.classList.remove('hidden');\n\n // Move the elements in order at the beginning of the list.\n neworder.forEach((itemid, index) => {\n const item = allitems[itemid];\n // Get the current element at that position.\n const currentitem = container.children[index];\n if (currentitem === undefined) {\n container.append(item);\n return;\n }\n if (currentitem !== item) {\n container.insertBefore(item, currentitem);\n }\n });\n // Remove the remaining elements.\n while (container.children.length > neworder.length) {\n container.removeChild(container.lastChild);\n }\n }\n\n /**\n * Remove a cm from the list.\n *\n * The actual DOM element removal is delegated to the cm component.\n *\n * @param {object} param\n * @param {Object} param.element\n */\n _deleteCm({element}) {\n delete this.cms[element.id];\n }\n}\n"],"file":"courseindex.min.js"} \ No newline at end of file diff --git a/course/format/amd/build/local/courseindex/section.min.js.map b/course/format/amd/build/local/courseindex/section.min.js.map index c1b7513d5ebe7..31ecdc9e38af6 100644 --- a/course/format/amd/build/local/courseindex/section.min.js.map +++ b/course/format/amd/build/local/courseindex/section.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/courseindex/section.js"],"names":["Component","name","selectors","SECTION_ITEM","SECTION_TITLE","CM_LAST","classes","SECTIONHIDDEN","SECTIONCURRENT","LOCKED","id","element","dataset","state","configState","reactive","isEditing","supportComponents","titleitem","SectionTitle","getElement","fullregion","configDragDrop","watch","handler","_refreshSection","sectionitem","classList","toggle","visible","current","DRAGGING","dragging","locked","innerHTML","title","target","document","getElementById","DndSection"],"mappings":"sQA0BA,OACA,O,63EAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,qBAAZ,CAEA,KAAKC,SAAL,CAAiB,CACbC,YAAY,4BADC,CAEbC,aAAa,6BAFA,CAGbC,OAAO,+BAHM,CAAjB,CAMA,KAAKC,OAAL,CAAe,CACXC,aAAa,CAAE,QADJ,CAEXC,cAAc,CAAE,SAFL,CAGXC,MAAM,CAAE,gBAHG,CAAf,CAOA,KAAKC,EAAL,CAAU,KAAKC,OAAL,CAAaC,OAA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8B,SAA9C,CAA0DvB,CAAO,CAACwB,KACrE,C,oCA7DWC,C,CAAQlC,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBW,OAAO,CAAE0B,QAAQ,CAACC,cAAT,CAAwBF,CAAxB,CADQ,CAEjBlC,SAAS,CAATA,CAFiB,CAAd,CAIV,C,cArCkCqC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index section component.\n *\n * This component is used to control specific course section interactions like drag and drop.\n *\n * @module core_courseformat/local/courseindex/section\n * @class core_courseformat/local/courseindex/section\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport SectionTitle from 'core_courseformat/local/courseindex/sectiontitle';\nimport DndSection from 'core_courseformat/local/courseeditor/dndsection';\n\nexport default class Component extends DndSection {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex_section';\n // Default query selectors.\n this.selectors = {\n SECTION_ITEM: `[data-for='section_item']`,\n SECTION_TITLE: `[data-for='section_title']`,\n CM_LAST: `[data-for=\"cm\"]:last-child`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n SECTIONHIDDEN: 'dimmed',\n SECTIONCURRENT: 'current',\n LOCKED: 'editinprogress',\n };\n\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Static method to create a component instance form the mustahce template.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n *\n * @param {Object} state the initial state\n */\n stateReady(state) {\n this.configState(state);\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Init the inner dragable element passing the full section as affected region.\n const titleitem = new SectionTitle({\n ...this,\n element: this.getElement(this.selectors.SECTION_ITEM),\n fullregion: this.element,\n });\n this.configDragDrop(titleitem);\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `section[${this.id}]:updated`, handler: this._refreshSection},\n ];\n }\n\n /**\n * Get the last CM element of that section.\n *\n * @returns {element|null}\n */\n getLastCm() {\n return this.getElement(this.selectors.CM_LAST);\n }\n\n /**\n * Update a course index section using the state information.\n *\n * @param {Object} details the update details.\n */\n _refreshSection({element}) {\n // Update classes.\n const sectionitem = this.getElement(this.selectors.SECTION_ITEM);\n sectionitem.classList.toggle(this.classes.SECTIONHIDDEN, !element.visible);\n this.element.classList.toggle(this.classes.SECTIONCURRENT, element.current);\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n // Update title.\n this.getElement(this.selectors.SECTION_TITLE).innerHTML = element.title;\n }\n}\n"],"file":"section.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/courseindex/section.js"],"names":["Component","name","selectors","SECTION_ITEM","SECTION_TITLE","CM_LAST","classes","SECTIONHIDDEN","SECTIONCURRENT","LOCKED","id","element","dataset","state","configState","reactive","isEditing","supportComponents","titleitem","SectionTitle","getElement","fullregion","configDragDrop","watch","handler","_refreshSection","sectionitem","classList","toggle","visible","current","DRAGGING","dragging","locked","innerHTML","title","target","document","getElementById","DndSection"],"mappings":"sQA0BA,OACA,O,63EAEqBA,CAAAA,C,+HAKR,CAEL,KAAKC,IAAL,CAAY,qBAAZ,CAEA,KAAKC,SAAL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qB,QAA7D,oBACA,KAAKrB,OAAL,CAAagB,SAAb,CAAuBC,MAAvB,CAA8B,KAAKtB,OAAL,CAAaG,MAA3C,WAAmDE,CAAO,CAACsB,MAA3D,oBACA,KAAKA,MAAL,CAActB,CAAO,CAACsB,MAAtB,CAEA,KAAKb,UAAL,CAAgB,KAAKlB,SAAL,CAAeE,aAA/B,EAA8C8B,SAA9C,CAA0DvB,CAAO,CAACwB,KACrE,C,oCA9DWC,C,CAAQlC,C,CAAW,CAC3B,MAAO,IAAIF,CAAAA,CAAJ,CAAc,CACjBW,OAAO,CAAE0B,QAAQ,CAACC,cAAT,CAAwBF,CAAxB,CADQ,CAEjBlC,SAAS,CAATA,CAFiB,CAAd,CAIV,C,cArCkCqC,S","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Course index section component.\n *\n * This component is used to control specific course section interactions like drag and drop.\n *\n * @module core_courseformat/local/courseindex/section\n * @class core_courseformat/local/courseindex/section\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport SectionTitle from 'core_courseformat/local/courseindex/sectiontitle';\nimport DndSection from 'core_courseformat/local/courseeditor/dndsection';\n\nexport default class Component extends DndSection {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'courseindex_section';\n // Default query selectors.\n this.selectors = {\n SECTION_ITEM: `[data-for='section_item']`,\n SECTION_TITLE: `[data-for='section_title']`,\n CM_LAST: `[data-for=\"cm\"]:last-child`,\n };\n // Default classes to toggle on refresh.\n this.classes = {\n SECTIONHIDDEN: 'dimmed',\n SECTIONCURRENT: 'current',\n LOCKED: 'editinprogress',\n };\n\n // We need our id to watch specific events.\n this.id = this.element.dataset.id;\n }\n\n /**\n * Static method to create a component instance form the mustahce template.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new Component({\n element: document.getElementById(target),\n selectors,\n });\n }\n\n /**\n * Initial state ready method.\n *\n * @param {Object} state the initial state\n */\n stateReady(state) {\n this.configState(state);\n // Drag and drop is only available for components compatible course formats.\n if (this.reactive.isEditing && this.reactive.supportComponents) {\n // Init the inner dragable element passing the full section as affected region.\n const titleitem = new SectionTitle({\n ...this,\n element: this.getElement(this.selectors.SECTION_ITEM),\n fullregion: this.element,\n });\n this.configDragDrop(titleitem);\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `section[${this.id}]:updated`, handler: this._refreshSection},\n ];\n }\n\n /**\n * Get the last CM element of that section.\n *\n * @returns {element|null}\n */\n getLastCm() {\n return this.getElement(this.selectors.CM_LAST);\n }\n\n /**\n * Update a course index section using the state information.\n *\n * @param {Object} param details the update details.\n * @param {Object} param.element\n */\n _refreshSection({element}) {\n // Update classes.\n const sectionitem = this.getElement(this.selectors.SECTION_ITEM);\n sectionitem.classList.toggle(this.classes.SECTIONHIDDEN, !element.visible);\n this.element.classList.toggle(this.classes.SECTIONCURRENT, element.current);\n this.element.classList.toggle(this.classes.DRAGGING, element.dragging ?? false);\n this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false);\n this.locked = element.locked;\n // Update title.\n this.getElement(this.selectors.SECTION_TITLE).innerHTML = element.title;\n }\n}\n"],"file":"section.min.js"} \ No newline at end of file diff --git a/course/format/amd/src/courseeditor.js b/course/format/amd/src/courseeditor.js index 056434e0bb60a..fb92f2e987cd5 100644 --- a/course/format/amd/src/courseeditor.js +++ b/course/format/amd/src/courseeditor.js @@ -53,8 +53,8 @@ function dispatchStateChangedEvent(detail, target) { * * @param {number} courseId the course id * @param {setup} setup format, page and course settings - * @property {boolean} setup.editing if the page is in edit mode - * @property {boolean} setup.supportscomponents if the format supports components for content + * @param {boolean} setup.editing if the page is in edit mode + * @param {boolean} setup.supportscomponents if the format supports components for content */ export const setViewFormat = (courseId, setup) => { const editor = getCourseEditor(courseId); diff --git a/course/format/amd/src/local/content.js b/course/format/amd/src/local/content.js index f6341b91c8605..81a3ec04544ec 100644 --- a/course/format/amd/src/local/content.js +++ b/course/format/amd/src/local/content.js @@ -182,7 +182,8 @@ export default class Component extends BaseComponent { * Most course module HTML is still strongly backend dependant. * Some changes require to get a new version af the module. * - * @param {Object} update the state update data + * @param {Object} param + * @param {Object} param.element update the state update data */ _reloadCm({element}) { const cmitem = this.getElement(this.selectors.CM, element.id); @@ -194,7 +195,8 @@ export default class Component extends BaseComponent { /** * Update section collapsed. * - * @param {Object} details the update details. + * @param {object} args + * @param {Object} args.element The element to update */ _refreshSectionCollapsed({element}) { const target = this.getElement(this.selectors.SECTION, element.id); @@ -234,7 +236,8 @@ export default class Component extends BaseComponent { * Course formats can override the section title rendering so the frontend depends heavily on backend * rendering. Luckily in edit mode we can trigger a title update using the inplace_editable module. * - * @param {Object} details the update details. + * @param {Object} param + * @param {Object} param.element details the update details. */ _refreshSectionNumber({element}) { // Find the element. @@ -272,8 +275,8 @@ export default class Component extends BaseComponent { /** * Refresh a section cm list. * - * @param {details} details the update details - * @property {object} details.element the state object + * @param {Object} param + * @param {Object} param.element details the update details. */ _refreshSectionCmlist({element}) { const cmlist = element.cmlist ?? []; @@ -289,7 +292,8 @@ export default class Component extends BaseComponent { /** * Refresh the section list. * - * @param {Object} details the update details. + * @param {Object} param + * @param {Object} param.element details the update details. */ _refreshCourseSectionlist({element}) { const sectionlist = element.sectionlist ?? []; @@ -361,8 +365,8 @@ export default class Component extends BaseComponent { * Most course module HTML is still strongly backend dependant. * Some changes require to get a new version of the module. * - * @param {details} param0 the watcher details - * @property {object} param0.element the state object + * @param {object} param0 the watcher details + * @param {object} param0.element the state object */ _reloadCm({element}) { const cmitem = this.getElement(this.selectors.CM, element.id); diff --git a/course/format/amd/src/local/content/section.js b/course/format/amd/src/local/content/section.js index c449da5866741..d0d38700ede20 100644 --- a/course/format/amd/src/local/content/section.js +++ b/course/format/amd/src/local/content/section.js @@ -98,7 +98,8 @@ export default class extends DndSection { /** * Update a course index section using the state information. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element details the update details. */ _refreshSection({element}) { // Update classes. diff --git a/course/format/amd/src/local/content/section/cmitem.js b/course/format/amd/src/local/content/section/cmitem.js index 8b729d5b40c19..e129425914aa3 100644 --- a/course/format/amd/src/local/content/section/cmitem.js +++ b/course/format/amd/src/local/content/section/cmitem.js @@ -69,7 +69,8 @@ export default class extends DndCmItem { /** * Update a course index cm using the state information. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element details the update details. */ _refreshCm({element}) { // Update classes. @@ -77,4 +78,4 @@ export default class extends DndCmItem { this.element.classList.toggle(this.classes.LOCKED, element.locked ?? false); this.locked = element.locked; } -} \ No newline at end of file +} diff --git a/course/format/amd/src/local/courseeditor/courseeditor.js b/course/format/amd/src/local/courseeditor/courseeditor.js index a0a4db4c5d341..e14b99a325e0d 100644 --- a/course/format/amd/src/local/courseeditor/courseeditor.js +++ b/course/format/amd/src/local/courseeditor/courseeditor.js @@ -96,8 +96,8 @@ export default class extends Reactive { * Setup the current view settings * * @param {Object} setup format, page and course settings - * @property {boolean} setup.editing if the page is in edit mode - * @property {boolean} setup.supportscomponents if the format supports components for content + * @param {boolean} setup.editing if the page is in edit mode + * @param {boolean} setup.supportscomponents if the format supports components for content */ setViewFormat(setup) { this._editing = setup.editing ?? false; @@ -213,8 +213,7 @@ export default class extends Reactive { * goes wrong. However, course editor can directly display a notification. * * @method dispatch - * @param {string} actionName the action name (usually the mutation name) - * @param {*} param any number of params the mutation needs. + * @param {mixed} args any number of params the mutation needs. */ async dispatch(...args) { try { diff --git a/course/format/amd/src/local/courseeditor/dndsectionitem.js b/course/format/amd/src/local/courseeditor/dndsectionitem.js index 0f07c4609e9d2..ad3a80249fce5 100644 --- a/course/format/amd/src/local/courseeditor/dndsectionitem.js +++ b/course/format/amd/src/local/courseeditor/dndsectionitem.js @@ -119,8 +119,6 @@ export default class extends BaseComponent { /** * Display the component dropzone. - * - * @param {Object} dropdata the accepted drop data */ showDropZone() { this.element.classList.add(this.classes.DROPZONE); diff --git a/course/format/amd/src/local/courseeditor/mutations.js b/course/format/amd/src/local/courseeditor/mutations.js index 21988a32ac896..64bb5490a131f 100644 --- a/course/format/amd/src/local/courseeditor/mutations.js +++ b/course/format/amd/src/local/courseeditor/mutations.js @@ -285,10 +285,10 @@ export default class { } /** - * Get the full updated state data of the course. - * - * @param {StateManager} stateManager the current state - */ + * Get the full updated state data of the course. + * + * @param {StateManager} stateManager the current state + */ async courseState(stateManager) { const course = stateManager.get('course'); const updates = await this._callEditWebservice('course_state', course.id); diff --git a/course/format/amd/src/local/courseindex/cm.js b/course/format/amd/src/local/courseindex/cm.js index 07d81c71d978a..34b745a43069f 100644 --- a/course/format/amd/src/local/courseindex/cm.js +++ b/course/format/amd/src/local/courseindex/cm.js @@ -83,7 +83,8 @@ export default class Component extends DndCmItem { /** * Update a course index cm using the state information. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element details the update details. */ _refreshCm({element}) { // Update classes. diff --git a/course/format/amd/src/local/courseindex/courseindex.js b/course/format/amd/src/local/courseindex/courseindex.js index b2969f164e26c..e964b7a0f8e59 100644 --- a/course/format/amd/src/local/courseindex/courseindex.js +++ b/course/format/amd/src/local/courseindex/courseindex.js @@ -133,7 +133,8 @@ export default class Component extends BaseComponent { /** * Update section collapsed. * - * @param {Object} details the update details. + * @param {object} args + * @param {object} args.element The leement to be expanded */ _refreshSectionCollapsed({element}) { const target = this.getElement(this.selectors.SECTION, element.id); @@ -186,7 +187,9 @@ export default class Component extends BaseComponent { /** * Create a newcm instance. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.state + * @param {Object} param.element */ async _createCm({state, element}) { // Create a fake node while the component is loading. @@ -213,7 +216,8 @@ export default class Component extends BaseComponent { /** * Refresh a section cm list. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element */ _refreshSectionCmlist({element}) { const cmlist = element.cmlist ?? []; @@ -224,7 +228,8 @@ export default class Component extends BaseComponent { /** * Refresh the section list. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element */ _refreshCourseSectionlist({element}) { const sectionlist = element.sectionlist ?? []; @@ -274,7 +279,8 @@ export default class Component extends BaseComponent { * * The actual DOM element removal is delegated to the cm component. * - * @param {Object} details the update details. + * @param {object} param + * @param {Object} param.element */ _deleteCm({element}) { delete this.cms[element.id]; diff --git a/course/format/amd/src/local/courseindex/section.js b/course/format/amd/src/local/courseindex/section.js index 81b74bf390ae7..d76c56a830dde 100644 --- a/course/format/amd/src/local/courseindex/section.js +++ b/course/format/amd/src/local/courseindex/section.js @@ -108,7 +108,8 @@ export default class Component extends DndSection { /** * Update a course index section using the state information. * - * @param {Object} details the update details. + * @param {Object} param details the update details. + * @param {Object} param.element */ _refreshSection({element}) { // Update classes. diff --git a/grade/amd/build/grades/grader/gradingpanel/point.min.js.map b/grade/amd/build/grades/grader/gradingpanel/point.min.js.map index 8b38fb2f0c93a..b5728796d9576 100644 --- a/grade/amd/build/grades/grader/gradingpanel/point.min.js.map +++ b/grade/amd/build/grades/grader/gradingpanel/point.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/grades/grader/gradingpanel/point.js"],"names":["fetchCurrentGrade","storeCurrentGrade","component","context","itemname","userId","notifyUser","rootNode","form","querySelector","grade","checkValidity","value","trim","invalidResult","serialize"],"mappings":"8RA0BA,uD,mVAaiC,QAApBA,CAAAA,iBAAoB,SAAa,iBAAW,OAAX,yBAAb,C,CAc1B,GAAMC,CAAAA,CAAiB,4CAAG,WAAMC,CAAN,CAAiBC,CAAjB,CAA0BC,CAA1B,CAAoCC,CAApC,CAA4CC,CAA5C,CAAwDC,CAAxD,2FACvBC,CADuB,CAChBD,CAAQ,CAACE,aAAT,CAAuB,MAAvB,CADgB,CAEvBC,CAFuB,CAEfF,CAAI,CAACC,aAAL,CAAmB,uBAAnB,CAFe,MAIzB,CAACC,CAAK,CAACC,aAAN,EAAD,EAA0B,CAACD,CAAK,CAACE,KAAN,CAAYC,IAAZ,EAJF,2CAKlBC,eALkB,cAQzB,uBAAYN,CAAZ,CARyB,kCASZ,gBAAU,OAAV,EAAmBN,CAAnB,CAA8BC,CAA9B,CAAuCC,CAAvC,CAAiDC,CAAjD,CAAyDC,CAAzD,CAAqE,cAAOE,CAAP,EAAaO,SAAb,EAArE,CATY,0EAWlB,EAXkB,2CAAH,uDAAvB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Grading panel for simple direct grading.\n *\n * @module core_grades/grades/grader/gradingpanel/point\n * @copyright 2019 Andrew Nicols \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {saveGrade, fetchGrade} from './repository';\nimport {compareData} from 'core_grades/grades/grader/gradingpanel/comparison';\n// Note: We use jQuery.serializer here until we can rewrite Ajax to use XHR.send()\nimport jQuery from 'jquery';\nimport {invalidResult} from './normalise';\n\n/**\n * Fetch the current grade for a user.\n *\n * @param {String} component\n * @param {Number} context\n * @param {String} itemname\n * @param {Number} userId\n * @param {Element} rootNode\n * @return {Object}\n */\nexport const fetchCurrentGrade = (...args) => fetchGrade('point')(...args);\n\n/**\n * Store a new grade for a user.\n *\n * @param {String} component\n * @param {Number} context\n * @param {String} itemname\n * @param {Number} userId\n * @param {Boolean} notifyUser\n * @param {Element} rootNode\n *\n * @return {Object}\n */\nexport const storeCurrentGrade = async(component, context, itemname, userId, notifyUser, rootNode) => {\n const form = rootNode.querySelector('form');\n const grade = form.querySelector('input[name=\"grade\"]');\n\n if (!grade.checkValidity() || !grade.value.trim()) {\n return invalidResult;\n }\n\n if (compareData(form) === true) {\n return await saveGrade('point')(component, context, itemname, userId, notifyUser, jQuery(form).serialize());\n } else {\n return '';\n }\n};\n"],"file":"point.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../../src/grades/grader/gradingpanel/point.js"],"names":["fetchCurrentGrade","storeCurrentGrade","component","context","itemname","userId","notifyUser","rootNode","form","querySelector","grade","checkValidity","value","trim","invalidResult","serialize"],"mappings":"8RA0BA,uD,mVAciC,QAApBA,CAAAA,iBAAoB,SAAa,iBAAW,OAAX,yBAAb,C,CAa1B,GAAMC,CAAAA,CAAiB,4CAAG,WAAMC,CAAN,CAAiBC,CAAjB,CAA0BC,CAA1B,CAAoCC,CAApC,CAA4CC,CAA5C,CAAwDC,CAAxD,2FACvBC,CADuB,CAChBD,CAAQ,CAACE,aAAT,CAAuB,MAAvB,CADgB,CAEvBC,CAFuB,CAEfF,CAAI,CAACC,aAAL,CAAmB,uBAAnB,CAFe,MAIzB,CAACC,CAAK,CAACC,aAAN,EAAD,EAA0B,CAACD,CAAK,CAACE,KAAN,CAAYC,IAAZ,EAJF,2CAKlBC,eALkB,cAQzB,uBAAYN,CAAZ,CARyB,kCASZ,gBAAU,OAAV,EAAmBN,CAAnB,CAA8BC,CAA9B,CAAuCC,CAAvC,CAAiDC,CAAjD,CAAyDC,CAAzD,CAAqE,cAAOE,CAAP,EAAaO,SAAb,EAArE,CATY,0EAWlB,EAXkB,2CAAH,uDAAvB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Grading panel for simple direct grading.\n *\n * @module core_grades/grades/grader/gradingpanel/point\n * @copyright 2019 Andrew Nicols \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {saveGrade, fetchGrade} from './repository';\nimport {compareData} from 'core_grades/grades/grader/gradingpanel/comparison';\n// Note: We use jQuery.serializer here until we can rewrite Ajax to use XHR.send()\nimport jQuery from 'jquery';\nimport {invalidResult} from './normalise';\n\n/**\n * Fetch the current grade for a user.\n *\n * @param {object} args\n * @param {String} args.component\n * @param {Number} args.context\n * @param {String} args.itemname\n * @param {Number} args.userId\n * @param {Element} args.rootNode\n * @returns {Object}\n */\nexport const fetchCurrentGrade = (...args) => fetchGrade('point')(...args);\n\n/**\n * Store a new grade for a user.\n *\n * @param {String} component\n * @param {Number} context\n * @param {String} itemname\n * @param {Number} userId\n * @param {Boolean} notifyUser\n * @param {Element} rootNode\n * @returns {Object}\n */\nexport const storeCurrentGrade = async(component, context, itemname, userId, notifyUser, rootNode) => {\n const form = rootNode.querySelector('form');\n const grade = form.querySelector('input[name=\"grade\"]');\n\n if (!grade.checkValidity() || !grade.value.trim()) {\n return invalidResult;\n }\n\n if (compareData(form) === true) {\n return await saveGrade('point')(component, context, itemname, userId, notifyUser, jQuery(form).serialize());\n } else {\n return '';\n }\n};\n"],"file":"point.min.js"} \ No newline at end of file diff --git a/grade/amd/src/grades/grader/gradingpanel/point.js b/grade/amd/src/grades/grader/gradingpanel/point.js index e7bc14116d280..1c7c60bd4d893 100644 --- a/grade/amd/src/grades/grader/gradingpanel/point.js +++ b/grade/amd/src/grades/grader/gradingpanel/point.js @@ -30,12 +30,13 @@ import {invalidResult} from './normalise'; /** * Fetch the current grade for a user. * - * @param {String} component - * @param {Number} context - * @param {String} itemname - * @param {Number} userId - * @param {Element} rootNode - * @return {Object} + * @param {object} args + * @param {String} args.component + * @param {Number} args.context + * @param {String} args.itemname + * @param {Number} args.userId + * @param {Element} args.rootNode + * @returns {Object} */ export const fetchCurrentGrade = (...args) => fetchGrade('point')(...args); @@ -48,8 +49,7 @@ export const fetchCurrentGrade = (...args) => fetchGrade('point')(...args); * @param {Number} userId * @param {Boolean} notifyUser * @param {Element} rootNode - * - * @return {Object} + * @returns {Object} */ export const storeCurrentGrade = async(component, context, itemname, userId, notifyUser, rootNode) => { const form = rootNode.querySelector('form'); diff --git a/grade/grading/form/guide/amd/build/comment_chooser.min.js.map b/grade/grading/form/guide/amd/build/comment_chooser.min.js.map index e1fbbeaa29bee..fa3e6719a8aef 100644 --- a/grade/grading/form/guide/amd/build/comment_chooser.min.js.map +++ b/grade/grading/form/guide/amd/build/comment_chooser.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/comment_chooser.js"],"names":["define","$","templates","notification","initialise","criterionId","buttonId","remarkId","commentOptions","displayChooserDialog","compiledSource","comments","titleLabel","M","util","get_string","cancelButtonId","cancelButton","chooserDialog","core","dialogue","modal","headerContent","bodyContent","footerContent","focusAfterHide","id","click","hide","each","index","comment","commentOptionId","remarkTextArea","remarkText","val","trim","description","document","off","on","keyCode","event","which","after","e","prevVal","newVal","destroy","show","generateCommentsChooser","render","done","fail","exception","preventDefault"],"mappings":"AAsBAA,OAAM,qCAAC,CAAC,QAAD,CAAW,gBAAX,CAA6B,mBAA7B,CAAkD,UAAlD,CAAD,CAAgE,SAASC,CAAT,CAAYC,CAAZ,CAAuBC,CAAvB,CAAqC,CAIvG,MAA8D,CAa1DC,UAAU,CAAE,oBAASC,CAAT,CAAsBC,CAAtB,CAAgCC,CAAhC,CAA0CC,CAA1C,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AJ,CAAc,CAACE,GAAf,CAAmBD,CAAnB,EAEAhB,CAAa,CAACU,IAAd,EACH,CAbD,EAgBA3B,CAAC,CAACqC,QAAD,CAAD,CAAYC,GAAZ,CAAgB,UAAhB,CAA4BP,CAA5B,EAA6CQ,EAA7C,CAAgD,UAAhD,CAA4DR,CAA5D,CAA6E,UAAW,CACpF,GAAIS,CAAAA,CAAO,CAAGC,KAAK,CAACC,KAAN,EAAeD,KAAK,CAACD,OAAnC,CAGA,GAAe,EAAX,EAAAA,CAAO,EAAqB,EAAX,EAAAA,CAArB,CAAoC,CAEhCxC,CAAC,CAAC+B,CAAD,CAAD,CAAmBL,KAAnB,EACH,CACJ,CARD,CASH,CA7BD,EAiCAT,CAAa,CAAC0B,KAAd,CAAoB,eAApB,CAAqC,SAASC,CAAT,CAAY,CAE7C,GAAIA,CAAC,CAACC,OAAF,EAAa,CAACD,CAAC,CAACE,MAApB,CAA4B,CACxB,KAAKC,OAAL,EACH,CACJ,CALD,CAKG9B,CALH,EAQAA,CAAa,CAAC+B,IAAd,EACH,CAKD,QAASC,CAAAA,CAAT,EAAmC,CAQ/BhD,CAAS,CAACiD,MAAV,CAAiB,mCAAjB,CANc,CACV9C,WAAW,CAAEA,CADH,CAEVM,QAAQ,CAAEH,CAFA,CAMd,EACK4C,IADL,CACU,SAAS1C,CAAT,CAAyB,CAC3BD,CAAoB,CAACC,CAAD,CAAiBF,CAAjB,CACvB,CAHL,EAIK6C,IAJL,CAIUlD,CAAY,CAACmD,SAJvB,CAKH,CAGDrD,CAAC,CAAC,IAAMK,CAAP,CAAD,CAAkBqB,KAAlB,CAAwB,SAASkB,CAAT,CAAY,CAChCA,CAAC,CAACU,cAAF,GACAL,CAAuB,EAC1B,CAHD,CAIH,CA7GyD,CA+GjE,CAnHK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * AMD code for the frequently used comments chooser for the marking guide grading form.\n *\n * @module gradingform_guide/comment_chooser\n * @copyright 2015 Jun Pataleta \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/templates', 'core/notification', 'core/yui'], function($, templates, notification) {\n\n // Private variables and functions.\n\n return /** @alias module:gradingform_guide/comment_chooser */ {\n // Public variables and functions.\n /**\n * Initialises the module.\n *\n * Basically, it performs the binding and handling of the button click event for\n * the 'Insert frequently used comment' button.\n *\n * @param {Integer} criterionId The criterion ID.\n * @param {String} buttonId The element ID of the button which the handler will be bound to.\n * @param {String} remarkId The element ID of the remark text area where the text of the selected comment will be copied to.\n * @param {Array} commentOptions The array of frequently used comments to be used as options.\n */\n initialise: function(criterionId, buttonId, remarkId, commentOptions) {\n /**\n * Display the chooser dialog using the compiled HTML from the mustache template\n * and binds onclick events for the generated comment options.\n *\n * @param {String} compiledSource The compiled HTML from the mustache template\n * @param {Array} comments Array containing comments.\n */\n function displayChooserDialog(compiledSource, comments) {\n var titleLabel = '';\n var cancelButtonId = 'comment-chooser-' + criterionId + '-cancel';\n var cancelButton = '';\n\n // Set dialog's body content.\n var chooserDialog = new M.core.dialogue({\n modal: true,\n headerContent: titleLabel,\n bodyContent: compiledSource,\n footerContent: cancelButton,\n focusAfterHide: '#' + remarkId,\n id: \"comments-chooser-dialog-\" + criterionId\n });\n\n // Bind click event to the cancel button.\n $(\"#\" + cancelButtonId).click(function() {\n chooserDialog.hide();\n });\n\n // Loop over each comment item and bind click events.\n $.each(comments, function(index, comment) {\n var commentOptionId = '#comment-option-' + criterionId + '-' + comment.id;\n\n // Delegate click event for the generated option link.\n $(commentOptionId).click(function() {\n var remarkTextArea = $('#' + remarkId);\n var remarkText = remarkTextArea.val();\n\n // Add line break if the current value of the remark text is not empty.\n if (remarkText.trim() !== '') {\n remarkText += '\\n';\n }\n remarkText += comment.description;\n\n remarkTextArea.val(remarkText);\n\n chooserDialog.hide();\n });\n\n // Handle keypress on list items.\n $(document).off('keypress', commentOptionId).on('keypress', commentOptionId, function() {\n var keyCode = event.which || event.keyCode;\n\n // Enter or space key.\n if (keyCode == 13 || keyCode == 32) {\n // Trigger click event.\n $(commentOptionId).click();\n }\n });\n });\n\n // Destroy the dialog when it is hidden to allow the grading section to\n // be loaded as a fragment multiple times within the same page.\n chooserDialog.after('visibleChange', function(e) {\n // Going from visible to hidden.\n if (e.prevVal && !e.newVal) {\n this.destroy();\n }\n }, chooserDialog);\n\n // Show dialog.\n chooserDialog.show();\n }\n\n /**\n * Generates the comments chooser dialog from the grading_form/comment_chooser mustache template.\n */\n function generateCommentsChooser() {\n // Template context.\n var context = {\n criterionId: criterionId,\n comments: commentOptions\n };\n\n // Render the template and display the comment chooser dialog.\n templates.render('gradingform_guide/comment_chooser', context)\n .done(function(compiledSource) {\n displayChooserDialog(compiledSource, commentOptions);\n })\n .fail(notification.exception);\n }\n\n // Bind click event for the comments chooser button.\n $(\"#\" + buttonId).click(function(e) {\n e.preventDefault();\n generateCommentsChooser();\n });\n }\n };\n});\n"],"file":"comment_chooser.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/comment_chooser.js"],"names":["define","$","templates","notification","initialise","criterionId","buttonId","remarkId","commentOptions","displayChooserDialog","compiledSource","comments","titleLabel","M","util","get_string","cancelButtonId","cancelButton","chooserDialog","core","dialogue","modal","headerContent","bodyContent","footerContent","focusAfterHide","id","click","hide","each","index","comment","commentOptionId","remarkTextArea","remarkText","val","trim","description","document","off","on","keyCode","event","which","after","e","prevVal","newVal","destroy","show","generateCommentsChooser","render","done","fail","exception","preventDefault"],"mappings":"AAsBAA,OAAM,qCAAC,CAAC,QAAD,CAAW,g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AACU,cAAF,GACAL,CAAuB,EAC1B,CAHD,CAIH,CA7GyD,CA+GjE,CAnHK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * AMD code for the frequently used comments chooser for the marking guide grading form.\n *\n * @module gradingform_guide/comment_chooser\n * @copyright 2015 Jun Pataleta \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['jquery', 'core/templates', 'core/notification', 'core/yui'], function($, templates, notification) {\n\n // Private variables and functions.\n\n return /** @alias module:gradingform_guide/comment_chooser */ {\n // Public variables and functions.\n /**\n * Initialises the module.\n *\n * Basically, it performs the binding and handling of the button click event for\n * the 'Insert frequently used comment' button.\n *\n * @param {Integer} criterionId The criterion ID.\n * @param {String} buttonId The element ID of the button which the handler will be bound to.\n * @param {String} remarkId The element ID of the remark text area where the text of the selected comment will be copied to.\n * @param {Array} commentOptions The array of frequently used comments to be used as options.\n */\n initialise: function(criterionId, buttonId, remarkId, commentOptions) {\n /**\n * Display the chooser dialog using the compiled HTML from the mustache template\n * and binds onclick events for the generated comment options.\n *\n * @param {String} compiledSource The compiled HTML from the mustache template\n * @param {Array} comments Array containing comments.\n */\n function displayChooserDialog(compiledSource, comments) {\n var titleLabel = '';\n var cancelButtonId = 'comment-chooser-' + criterionId + '-cancel';\n var cancelButton = '';\n\n // Set dialog's body content.\n var chooserDialog = new M.core.dialogue({\n modal: true,\n headerContent: titleLabel,\n bodyContent: compiledSource,\n footerContent: cancelButton,\n focusAfterHide: '#' + remarkId,\n id: \"comments-chooser-dialog-\" + criterionId\n });\n\n // Bind click event to the cancel button.\n $(\"#\" + cancelButtonId).click(function() {\n chooserDialog.hide();\n });\n\n // Loop over each comment item and bind click events.\n $.each(comments, function(index, comment) {\n var commentOptionId = '#comment-option-' + criterionId + '-' + comment.id;\n\n // Delegate click event for the generated option link.\n $(commentOptionId).click(function() {\n var remarkTextArea = $('#' + remarkId);\n var remarkText = remarkTextArea.val();\n\n // Add line break if the current value of the remark text is not empty.\n if (remarkText.trim() !== '') {\n remarkText += '\\n';\n }\n remarkText += comment.description;\n\n remarkTextArea.val(remarkText);\n\n chooserDialog.hide();\n });\n\n // Handle keypress on list items.\n $(document).off('keypress', commentOptionId).on('keypress', commentOptionId, function() {\n var keyCode = event.which || event.keyCode;\n\n // Enter or space key.\n if (keyCode == 13 || keyCode == 32) {\n // Trigger click event.\n $(commentOptionId).click();\n }\n });\n });\n\n // Destroy the dialog when it is hidden to allow the grading section to\n // be loaded as a fragment multiple times within the same page.\n chooserDialog.after('visibleChange', function(e) {\n // Going from visible to hidden.\n if (e.prevVal && !e.newVal) {\n this.destroy();\n }\n }, chooserDialog);\n\n // Show dialog.\n chooserDialog.show();\n }\n\n /**\n * Generates the comments chooser dialog from the grading_form/comment_chooser mustache template.\n */\n function generateCommentsChooser() {\n // Template context.\n var context = {\n criterionId: criterionId,\n comments: commentOptions\n };\n\n // Render the template and display the comment chooser dialog.\n templates.render('gradingform_guide/comment_chooser', context)\n .done(function(compiledSource) {\n displayChooserDialog(compiledSource, commentOptions);\n })\n .fail(notification.exception);\n }\n\n // Bind click event for the comments chooser button.\n $(\"#\" + buttonId).click(function(e) {\n e.preventDefault();\n generateCommentsChooser();\n });\n }\n };\n});\n"],"file":"comment_chooser.min.js"} \ No newline at end of file diff --git a/grade/grading/form/guide/amd/src/comment_chooser.js b/grade/grading/form/guide/amd/src/comment_chooser.js index 48a3ebb3efba5..23a5ccc87571f 100644 --- a/grade/grading/form/guide/amd/src/comment_chooser.js +++ b/grade/grading/form/guide/amd/src/comment_chooser.js @@ -19,7 +19,7 @@ * @module gradingform_guide/comment_chooser * @copyright 2015 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ + */ define(['jquery', 'core/templates', 'core/notification', 'core/yui'], function($, templates, notification) { // Private variables and functions. diff --git a/lib/amd/build/addblockmodal.min.js.map b/lib/amd/build/addblockmodal.min.js.map index 9efb5cc079de6..5dc0165832765 100644 --- a/lib/amd/build/addblockmodal.min.js.map +++ b/lib/amd/build/addblockmodal.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/addblockmodal.js"],"names":["SELECTORS","ADD_BLOCK","addBlockModal","registerListenerEvents","pageType","pageLayout","addBlockUrl","document","addEventListener","e","target","closest","preventDefault","show","buildAddBlockModal","then","modal","modalBody","renderBlocks","setBody","catch","destroy","ModalFactory","create","type","types","CANCEL","title","getAddableBlocks","blocks","Templates","render","url","request","methodname","args","pagecontextid","M","cfg","contextid","pagetype","pagelayout","Ajax","call","init"],"mappings":"sMAuBA,OACA,OAEA,O,qXAEMA,CAAAA,CAAS,CAAG,CACdC,SAAS,CAAE,yBADG,C,CAIdC,CAAa,CAAG,I,CAUdC,CAAsB,CAAG,SAACC,CAAD,CAAWC,CAAX,CAAuBC,CAAvB,CAAuC,CAClEC,QAAQ,CAACC,gBAAT,CAA0B,OAA1B,CAAmC,SAAAC,CAAC,CAAI,CAEpC,GAAIA,CAAC,CAACC,MAAF,CAASC,OAAT,CAAiBX,CAAS,CAACC,SAA3B,CAAJ,CAA2C,CACvCQ,CAAC,CAACG,cAAF,GAEA,GAAIV,CAAJ,CAAmB,CAEfA,CAAa,CAACW,IAAd,EACH,CAHD,IAGO,CACHC,CAAkB,GACjBC,IADD,CACM,SAAAC,CAAK,CAAI,CACXd,CAAa,CAAGc,CAAhB,CACA,GAAMC,CAAAA,CAAS,CAAGC,CAAY,CAACZ,CAAD,CAAcF,CAAd,CAAwBC,CAAxB,CAA9B,CACAW,CAAK,CAACG,OAAN,CAAcF,CAAd,EACAD,CAAK,CAACH,IAAN,GAEA,MAAOI,CAAAA,CACV,CARD,EASCG,KATD,CASO,UAAM,CACTlB,CAAa,CAACmB,OAAd,GAEAnB,CAAa,CAAG,IACnB,CAbD,CAcH,CACJ,CACJ,CAzBD,CA0BH,C,CAQKY,CAAkB,CAAG,UAAM,CAC7B,MAAOQ,WAAaC,MAAb,CAAoB,CACvBC,IAAI,CAAEF,UAAaG,KAAb,CAAmBC,MADF,CAEvBC,KAAK,CAAE,iBAAU,UAAV,CAFgB,CAApB,CAIV,C,CAWKT,CAAY,4CAAG,WAAMZ,CAAN,CAAmBF,CAAnB,CAA6BC,CAA7B,wGAEIuB,CAAAA,CAAgB,CAACxB,CAAD,CAAWC,CAAX,CAFpB,QAEXwB,CAFW,iCAIVC,UAAUC,MAAV,CAAiB,qBAAjB,CAAwC,CAC3CF,MAAM,CAAEA,CADmC,CAE3CG,GAAG,CAAE1B,CAFsC,CAAxC,CAJU,0CAAH,uD,CAkBZsB,CAAgB,4CAAG,WAAMxB,CAAN,CAAgBC,CAAhB,yFACf4B,CADe,CACL,CACZC,UAAU,CAAE,iCADA,CAEZC,IAAI,CAAE,CACFC,aAAa,CAAEC,CAAC,CAACC,GAAF,CAAMC,SADnB,CAEFC,QAAQ,CAAEpC,CAFR,CAGFqC,UAAU,CAAEpC,CAHV,CAFM,CADK,0BAUdqC,UAAKC,IAAL,CAAU,CAACV,CAAD,CAAV,EAAqB,CAArB,CAVc,0CAAH,uD,QAqBF,QAAPW,CAAAA,IAAO,CAACxC,CAAD,CAAWC,CAAX,CAAuBC,CAAvB,CAAuC,CACvDH,CAAsB,CAACC,CAAD,CAAWC,CAAX,CAAuBC,CAAvB,CACzB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Show an add block modal instead of doing it on a separate page.\n *\n * @module core/addblockmodal\n * @copyright 2016 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport ModalFactory from 'core/modal_factory';\nimport Templates from 'core/templates';\nimport {get_string as getString} from 'core/str';\nimport Ajax from 'core/ajax';\n\nconst SELECTORS = {\n ADD_BLOCK: '[data-key=\"addblock\"]'\n};\n\nlet addBlockModal = null;\n\n/**\n * Register related event listeners.\n *\n * @method registerListenerEvents\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @param {String} addBlockUrl The add block URL\n */\nconst registerListenerEvents = (pageType, pageLayout, addBlockUrl) => {\n document.addEventListener('click', e => {\n\n if (e.target.closest(SELECTORS.ADD_BLOCK)) {\n e.preventDefault();\n\n if (addBlockModal) { // The 'add block' modal has been already created.\n // Display the 'add block' modal.\n addBlockModal.show();\n } else {\n buildAddBlockModal()\n .then(modal => {\n addBlockModal = modal;\n const modalBody = renderBlocks(addBlockUrl, pageType, pageLayout);\n modal.setBody(modalBody);\n modal.show();\n\n return modalBody;\n })\n .catch(() => {\n addBlockModal.destroy();\n // Unset the addBlockModal in case this is a transient error and it goes away on a relaunch.\n addBlockModal = null;\n });\n }\n }\n });\n};\n\n/**\n * Method that creates the 'add block' modal.\n *\n * @method buildAddBlockModal\n * @return {Promise} The modal promise (modal's body will be rendered later).\n */\nconst buildAddBlockModal = () => {\n return ModalFactory.create({\n type: ModalFactory.types.CANCEL,\n title: getString('addblock')\n });\n};\n\n/**\n * Method that renders the list of available blocks.\n *\n * @method renderBlocks\n * @param {String} addBlockUrl The add block URL\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @return {Promise}\n */\nconst renderBlocks = async(addBlockUrl, pageType, pageLayout) => {\n // Fetch all addable blocks in the given page.\n const blocks = await getAddableBlocks(pageType, pageLayout);\n\n return Templates.render('core/add_block_body', {\n blocks: blocks,\n url: addBlockUrl\n });\n};\n\n/**\n * Method that fetches all addable blocks in a given page.\n *\n * @method getAddableBlocks\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @return {Promise}\n */\nconst getAddableBlocks = async(pageType, pageLayout) => {\n const request = {\n methodname: 'core_block_fetch_addable_blocks',\n args: {\n pagecontextid: M.cfg.contextid,\n pagetype: pageType,\n pagelayout: pageLayout\n },\n };\n\n return Ajax.call([request])[0];\n};\n\n/**\n * Set up the actions.\n *\n * @method init\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @param {String} addBlockUrl The add block URL\n */\nexport const init = (pageType, pageLayout, addBlockUrl) => {\n registerListenerEvents(pageType, pageLayout, addBlockUrl);\n};\n"],"file":"addblockmodal.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/addblockmodal.js"],"names":["SELECTORS","ADD_BLOCK","addBlockModal","registerListenerEvents","pageType","pageLayout","addBlockUrl","document","addEventListener","e","target","closest","preventDefault","show","buildAddBlockModal","then","modal","modalBody","renderBlocks","setBody","catch","destroy","ModalFactory","create","type","types","CANCEL","title","getAddableBlocks","blocks","Templates","render","url","request","methodname","args","pagecontextid","M","cfg","contextid","pagetype","pagelayout","Ajax","call","init"],"mappings":"sMAuBA,OACA,OAEA,O,qXAEMA,CAAAA,CAAS,CAAG,CACdC,SAAS,CAAE,yBADG,C,CAIdC,CAAa,CAAG,I,CAUdC,CAAsB,CAAG,SAACC,CAAD,CAAWC,CAAX,CAAuBC,CAAvB,CAAuC,CAClEC,QAAQ,CAACC,gBAAT,CAA0B,OAA1B,CAAmC,SAAAC,CAAC,CAAI,CAEpC,GAAIA,CAAC,CAACC,MAAF,CAASC,OAAT,CAAiBX,CAAS,CAACC,SAA3B,CAAJ,CAA2C,CACvCQ,CAAC,CAACG,cAAF,GAEA,GAA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C,CAAvB,CAAuC,CACvDH,CAAsB,CAACC,CAAD,CAAWC,CAAX,CAAuBC,CAAvB,CACzB,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Show an add block modal instead of doing it on a separate page.\n *\n * @module core/addblockmodal\n * @copyright 2016 Damyon Wiese \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport ModalFactory from 'core/modal_factory';\nimport Templates from 'core/templates';\nimport {get_string as getString} from 'core/str';\nimport Ajax from 'core/ajax';\n\nconst SELECTORS = {\n ADD_BLOCK: '[data-key=\"addblock\"]'\n};\n\nlet addBlockModal = null;\n\n/**\n * Register related event listeners.\n *\n * @method registerListenerEvents\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @param {String} addBlockUrl The add block URL\n */\nconst registerListenerEvents = (pageType, pageLayout, addBlockUrl) => {\n document.addEventListener('click', e => {\n\n if (e.target.closest(SELECTORS.ADD_BLOCK)) {\n e.preventDefault();\n\n if (addBlockModal) { // The 'add block' modal has been already created.\n // Display the 'add block' modal.\n addBlockModal.show();\n } else {\n buildAddBlockModal()\n .then(modal => {\n addBlockModal = modal;\n const modalBody = renderBlocks(addBlockUrl, pageType, pageLayout);\n modal.setBody(modalBody);\n modal.show();\n\n return modalBody;\n })\n .catch(() => {\n addBlockModal.destroy();\n // Unset the addBlockModal in case this is a transient error and it goes away on a relaunch.\n addBlockModal = null;\n });\n }\n }\n });\n};\n\n/**\n * Method that creates the 'add block' modal.\n *\n * @method buildAddBlockModal\n * @returns {Promise} The modal promise (modal's body will be rendered later).\n */\nconst buildAddBlockModal = () => {\n return ModalFactory.create({\n type: ModalFactory.types.CANCEL,\n title: getString('addblock')\n });\n};\n\n/**\n * Method that renders the list of available blocks.\n *\n * @method renderBlocks\n * @param {String} addBlockUrl The add block URL\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @return {Promise}\n */\nconst renderBlocks = async(addBlockUrl, pageType, pageLayout) => {\n // Fetch all addable blocks in the given page.\n const blocks = await getAddableBlocks(pageType, pageLayout);\n\n return Templates.render('core/add_block_body', {\n blocks: blocks,\n url: addBlockUrl\n });\n};\n\n/**\n * Method that fetches all addable blocks in a given page.\n *\n * @method getAddableBlocks\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @return {Promise}\n */\nconst getAddableBlocks = async(pageType, pageLayout) => {\n const request = {\n methodname: 'core_block_fetch_addable_blocks',\n args: {\n pagecontextid: M.cfg.contextid,\n pagetype: pageType,\n pagelayout: pageLayout\n },\n };\n\n return Ajax.call([request])[0];\n};\n\n/**\n * Set up the actions.\n *\n * @method init\n * @param {String} pageType The type of the page\n * @param {String} pageLayout The layout of the page\n * @param {String} addBlockUrl The add block URL\n */\nexport const init = (pageType, pageLayout, addBlockUrl) => {\n registerListenerEvents(pageType, pageLayout, addBlockUrl);\n};\n"],"file":"addblockmodal.min.js"} \ No newline at end of file diff --git a/lib/amd/build/chart_output_chartjs.min.js.map b/lib/amd/build/chart_output_chartjs.min.js.map index ae0a6821c0c6b..6e35d82945ee2 100644 --- a/lib/amd/build/chart_output_chartjs.min.js.map +++ b/lib/amd/build/chart_output_chartjs.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/chart_output_chartjs.js"],"names":["define","$","Chartjs","Axis","Bar","Base","Line","Pie","Series","makeAxisId","xy","index","Output","prototype","constructor","apply","arguments","_canvas","_node","prop","append","_build","Object","create","_config","_chartjs","_makeConfig","_cleanData","data","Array","map","value","html","text","_getChartType","type","_chart","getType","TYPE","getHorizontal","getDoughnut","_makeAxisConfig","axis","scaleData","id","getPosition","POS_DEFAULT","position","getLabel","scaleLabel","display","labelString","getStepSize","ticks","stepSize","getMax","max","getMin","min","config","labels","getLabels","datasets","_makeDatasetsConfig","options","title","getTitle","legendOptions","getLegendOptions","legend","getXAxes","forEach","i","axisLabels","scales","xAxes","callback","stacked","_isStacked","bind","getYAxes","yAxes","parseInt","tooltips","callbacks","label","_makeTooltip","sets","getSeries","series","colors","hasColoredValues","getColors","getColor","dataset","getValues","fill","getFill","backgroundColor","borderColor","lineTension","_isSmooth","getXAxis","xAxisID","getYAxis","yAxisID","tooltipItem","datasetIndex","serieLabel","serieLabels","chartData","tooltipData","tooltip","xLabel","yLabel","chartLabels","push","smooth","getSmooth","TYPE_LINE","getStacked","update","extend"],"mappings":"AAsBAA,OAAM,6BAAC,CACH,QADG,CAEH,cAFG,CAGH,iBAHG,CAIH,gBAJG,CAKH,wBALG,CAMH,iBANG,CAOH,gBAPG,CAQH,mBARG,CAAD,CASH,SAASC,CAAT,CAAYC,CAAZ,CAAqBC,CAArB,CAA2BC,CAA3B,CAAgCC,CAAhC,CAAsCC,CAAtC,CAA4CC,CAA5C,CAAiDC,CAAjD,CAAyD,CASxD,GAAIC,CAAAA,CAAU,CAAG,SAASC,CAAT,CAAaC,CAAb,CAAoB,CACjC,MAAO,QAAUD,CAAV,CAAe,GAAf,CAAqBC,CAC/B,CAFD,CAUA,QAASC,CAAAA,CAAT,EAAkB,CACdP,CAAI,CAACQ,SAAL,CAAeC,WAAf,CAA2BC,KAA3B,CAAiC,IAAjC,CAAuCC,SAAvC,EAGA,KAAKC,OAAL,CAAe,KAAKC,KAApB,CACA,GAAoC,QAAhC,OAAKD,OAAL,CAAaE,IAAb,CAAkB,SAAlB,CAAJ,CAA8C,CAC1C,KAAKF,OAAL,CAAehB,CAAC,CAAC,UAAD,CAAhB,CACA,KAAKiB,KAAL,CAAWE,MAAX,CAAkB,KAAKH,OAAvB,CACH,CAED,KAAKI,M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AP,CAAiBwF,SAAjB,CAA6B,SAASZ,CAAT,CAAiB,CAC1C,GAAI4B,CAAAA,CAAM,GAAV,CACA,GAAI,KAAKjF,MAAL,CAAYC,OAAZ,KAA0B/B,CAAI,CAACO,SAAL,CAAeyB,IAA7C,CAAmD,CAC/C+E,CAAM,CAAG5B,CAAM,CAAC6B,SAAP,EAAT,CACA,GAAe,IAAX,GAAAD,CAAJ,CAAqB,CACjBA,CAAM,CAAG,KAAKjF,MAAL,CAAYkF,SAAZ,EACZ,CACJ,CALD,IAKO,IAAI7B,CAAM,CAACpD,OAAP,KAAqB7B,CAAM,CAACK,SAAP,CAAiB0G,SAA1C,CAAqD,CACxDF,CAAM,CAAG5B,CAAM,CAAC6B,SAAP,EACZ,CAED,MAAOD,CAAAA,CACV,CAZD,CAoBAzG,CAAM,CAACC,SAAP,CAAiBiE,UAAjB,CAA8B,UAAW,CACrC,GAAID,CAAAA,CAAO,GAAX,CAGA,GAAI,KAAKzC,MAAL,CAAYC,OAAZ,KAA0BjC,CAAG,CAACS,SAAJ,CAAcyB,IAA5C,CAAkD,CAC9CuC,CAAO,CAAG,KAAKzC,MAAL,CAAYoF,UAAZ,EACb,CAED,MAAO3C,CAAAA,CACV,CATD,CAYAjE,CAAM,CAACC,SAAP,CAAiB4G,MAAjB,CAA0B,UAAW,CACjCxH,CAAC,CAACyH,MAAF,IAAe,KAAKlG,OAApB,CAA6B,KAAKE,WAAL,EAA7B,EACA,KAAKD,QAAL,CAAcgG,MAAd,EACH,CAHD,CAKA,MAAO7G,CAAAA,CAEV,CApVK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Chart output for chart.js.\n *\n * @copyright 2016 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @module core/chart_output_chartjs\n */\ndefine([\n 'jquery',\n 'core/chartjs',\n 'core/chart_axis',\n 'core/chart_bar',\n 'core/chart_output_base',\n 'core/chart_line',\n 'core/chart_pie',\n 'core/chart_series'\n], function($, Chartjs, Axis, Bar, Base, Line, Pie, Series) {\n\n /**\n * Makes an axis ID.\n *\n * @param {String} xy Accepts 'x' and 'y'.\n * @param {Number} index The axis index.\n * @return {String}\n */\n var makeAxisId = function(xy, index) {\n return 'axis-' + xy + '-' + index;\n };\n\n /**\n * Chart output for Chart.js.\n *\n * @class\n * @extends {module:core/chart_output_base}\n */\n function Output() {\n Base.prototype.constructor.apply(this, arguments);\n\n // Make sure that we've got a canvas tag.\n this._canvas = this._node;\n if (this._canvas.prop('tagName') != 'CANVAS') {\n this._canvas = $('');\n this._node.append(this._canvas);\n }\n\n this._build();\n }\n Output.prototype = Object.create(Base.prototype);\n\n /**\n * Reference to the chart config object.\n *\n * @type {Object}\n * @protected\n */\n Output.prototype._config = null;\n\n /**\n * Reference to the instance of chart.js.\n *\n * @type {Object}\n * @protected\n */\n Output.prototype._chartjs = null;\n\n /**\n * Reference to the canvas node.\n *\n * @type {Jquery}\n * @protected\n */\n Output.prototype._canvas = null;\n\n /**\n * Builds the config and the chart.\n *\n * @protected\n */\n Output.prototype._build = function() {\n this._config = this._makeConfig();\n this._chartjs = new Chartjs(this._canvas[0], this._config);\n };\n\n /**\n * Clean data.\n *\n * @param {(String|String[])} data A single string or an array of strings.\n * @returns {(String|String[])}\n * @protected\n */\n Output.prototype._cleanData = function(data) {\n if (data instanceof Array) {\n return data.map(function(value) {\n return $('').html(value).text();\n });\n } else {\n return $('').html(data).text();\n }\n };\n\n /**\n * Get the chart type and handles the Chart.js specific chart types.\n *\n * By default returns the current chart TYPE value. Also does the handling of specific chart types, for example\n * check if the bar chart should be horizontal and the pie chart should be displayed as a doughnut.\n *\n * @method getChartType\n * @returns {String} the chart type.\n * @protected\n */\n Output.prototype._getChartType = function() {\n var type = this._chart.getType();\n\n // Bars can be displayed vertically and horizontally, defining horizontalBar type.\n if (this._chart.getType() === Bar.prototype.TYPE && this._chart.getHorizontal() === true) {\n type = 'horizontalBar';\n } else if (this._chart.getType() === Pie.prototype.TYPE && this._chart.getDoughnut() === true) {\n // Pie chart can be displayed as doughnut.\n type = 'doughnut';\n }\n\n return type;\n };\n\n /**\n * Make the axis config.\n *\n * @protected\n * @param {module:core/chart_axis} axis The axis.\n * @param {String} xy Accepts 'x' or 'y'.\n * @param {Number} index The axis index.\n * @return {Object} The axis config.\n */\n Output.prototype._makeAxisConfig = function(axis, xy, index) {\n var scaleData = {\n id: makeAxisId(xy, index)\n };\n\n if (axis.getPosition() !== Axis.prototype.POS_DEFAULT) {\n scaleData.position = axis.getPosition();\n }\n\n if (axis.getLabel() !== null) {\n scaleData.scaleLabel = {\n display: true,\n labelString: this._cleanData(axis.getLabel())\n };\n }\n\n if (axis.getStepSize() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.stepSize = axis.getStepSize();\n }\n\n if (axis.getMax() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.max = axis.getMax();\n }\n\n if (axis.getMin() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.min = axis.getMin();\n }\n\n return scaleData;\n };\n\n /**\n * Make the config config.\n *\n * @protected\n * @param {module:core/chart_axis} axis The axis.\n * @return {Object} The axis config.\n */\n Output.prototype._makeConfig = function() {\n var config = {\n type: this._getChartType(),\n data: {\n labels: this._cleanData(this._chart.getLabels()),\n datasets: this._makeDatasetsConfig()\n },\n options: {\n title: {\n display: this._chart.getTitle() !== null,\n text: this._cleanData(this._chart.getTitle())\n }\n }\n };\n var legendOptions = this._chart.getLegendOptions();\n if (legendOptions) {\n config.options.legend = legendOptions;\n }\n\n\n this._chart.getXAxes().forEach(function(axis, i) {\n var axisLabels = axis.getLabels();\n\n config.options.scales = config.options.scales || {};\n config.options.scales.xAxes = config.options.scales.xAxes || [];\n config.options.scales.xAxes[i] = this._makeAxisConfig(axis, 'x', i);\n\n if (axisLabels !== null) {\n config.options.scales.xAxes[i].ticks.callback = function(value, index) {\n return axisLabels[index] || '';\n };\n }\n config.options.scales.xAxes[i].stacked = this._isStacked();\n }.bind(this));\n\n this._chart.getYAxes().forEach(function(axis, i) {\n var axisLabels = axis.getLabels();\n\n config.options.scales = config.options.scales || {};\n config.options.scales.yAxes = config.options.scales.yAxes || [];\n config.options.scales.yAxes[i] = this._makeAxisConfig(axis, 'y', i);\n\n if (axisLabels !== null) {\n config.options.scales.yAxes[i].ticks.callback = function(value) {\n return axisLabels[parseInt(value, 10)] || '';\n };\n }\n config.options.scales.yAxes[i].stacked = this._isStacked();\n }.bind(this));\n\n config.options.tooltips = {\n callbacks: {\n label: this._makeTooltip.bind(this)\n }\n };\n\n return config;\n };\n\n /**\n * Get the datasets configurations.\n *\n * @protected\n * @return {Object[]}\n */\n Output.prototype._makeDatasetsConfig = function() {\n var sets = this._chart.getSeries().map(function(series) {\n var colors = series.hasColoredValues() ? series.getColors() : series.getColor();\n var dataset = {\n label: this._cleanData(series.getLabel()),\n data: series.getValues(),\n type: series.getType(),\n fill: series.getFill(),\n backgroundColor: colors,\n // Pie charts look better without borders.\n borderColor: this._chart.getType() == Pie.prototype.TYPE ? '#fff' : colors,\n lineTension: this._isSmooth(series) ? 0.3 : 0\n };\n\n if (series.getXAxis() !== null) {\n dataset.xAxisID = makeAxisId('x', series.getXAxis());\n }\n if (series.getYAxis() !== null) {\n dataset.yAxisID = makeAxisId('y', series.getYAxis());\n }\n\n return dataset;\n }.bind(this));\n return sets;\n };\n\n /**\n * Get the chart data, add labels and rebuild the tooltip.\n *\n * @param {Object[]} tooltipItem The tooltip item data.\n * @param {Object[]} data The chart data.\n * @returns {String}\n * @protected\n */\n Output.prototype._makeTooltip = function(tooltipItem, data) {\n\n // Get series and chart data to rebuild the tooltip and add labels.\n var series = this._chart.getSeries()[tooltipItem.datasetIndex];\n var serieLabel = series.getLabel();\n var serieLabels = series.getLabels();\n var chartData = data.datasets[tooltipItem.datasetIndex].data;\n var tooltipData = chartData[tooltipItem.index];\n\n // Build default tooltip.\n var tooltip = [];\n\n // Pie and doughnut charts does not have axis.\n if (tooltipItem.xLabel == '' && tooltipItem.yLabel == '') {\n var chartLabels = this._cleanData(this._chart.getLabels());\n tooltip.push(chartLabels[tooltipItem.index]);\n }\n\n // Add series labels to the tooltip if any.\n if (serieLabels !== null) {\n tooltip.push(this._cleanData(serieLabels[tooltipItem.index]));\n } else {\n tooltip.push(this._cleanData(serieLabel) + ': ' + tooltipData);\n }\n\n return tooltip;\n };\n\n /**\n * Verify if the chart line is smooth or not.\n *\n * @protected\n * @param {module:core/chart_series} series The series.\n * @returns {Bool}\n */\n Output.prototype._isSmooth = function(series) {\n var smooth = false;\n if (this._chart.getType() === Line.prototype.TYPE) {\n smooth = series.getSmooth();\n if (smooth === null) {\n smooth = this._chart.getSmooth();\n }\n } else if (series.getType() === Series.prototype.TYPE_LINE) {\n smooth = series.getSmooth();\n }\n\n return smooth;\n };\n\n /**\n * Verify if the bar chart is stacked or not.\n *\n * @protected\n * @returns {Bool}\n */\n Output.prototype._isStacked = function() {\n var stacked = false;\n\n // Stacking is (currently) only supported for bar charts.\n if (this._chart.getType() === Bar.prototype.TYPE) {\n stacked = this._chart.getStacked();\n }\n\n return stacked;\n };\n\n /** @override */\n Output.prototype.update = function() {\n $.extend(true, this._config, this._makeConfig());\n this._chartjs.update();\n };\n\n return Output;\n\n});\n"],"file":"chart_output_chartjs.min.js"} \ No newline at end of file +{"version":3,"sources":["../src/chart_output_chartjs.js"],"names":["define","$","Chartjs","Axis","Bar","Base","Line","Pie","Series","makeAxisId","xy","index","Output","prototype","constructor","apply","arguments","_canvas","_node","prop","append","_build","Object","create","_config","_chartjs","_makeConfig","_cleanData","data","Array","map","value","html","text","_getChartType","type","_chart","getType","TYPE","getHorizontal","getDoughnut","_makeAxisConfig","axis","scaleData","id","getPosition","POS_DEFAULT","position","getLabel","scaleLabel","display","labelString","getStepSize","ticks","stepSize","getMax","max","getMin","min","config","labels","getLabels","datasets","_makeDatasetsConfig","options","title","getTitle","legendOptions","getLegendOptions","legend","getXAxes","forEach","i","axisLabels","scales","xAxes","callback","stacked","_isStacked","bind","getYAxes","yAxes","parseInt","tooltips","callbacks","label","_makeTooltip","sets","getSeries","series","colors","hasColoredValues","getColors","getColor","dataset","getValues","fill","getFill","backgroundColor","borderColor","lineTension","_isSmooth","getXAxis","xAxisID","getYAxis","yAxisID","tooltipItem","datasetIndex","serieLabel","serieLabels","chartData","tooltipData","tooltip","xLabel","yLabel","chartLabels","push","smooth","getSmooth","TYPE_LINE","getStacked","update","extend"],"mappings":"AAsBAA,OAAM,6BAAC,CACH,QADG,CAEH,cAFG,CAGH,iBAHG,CAIH,gBAJG,CAKH,wBALG,CAMH,iBANG,CAOH,gBAPG,CAQH,mBARG,CAAD,CASH,SAASC,CAAT,CAAYC,CAAZ,CAAqBC,CAArB,CAA2BC,CAA3B,CAAgCC,CAAhC,CAAsCC,CAAtC,CAA4CC,CAA5C,CAAiDC,CAAjD,CAAyD,CASxD,GAAIC,CAAAA,CAAU,CAAG,SAASC,CAAT,CAAaC,CAAb,CAAoB,CACjC,MAAO,QAAUD,CAAV,CAAe,GAAf,CAAqBC,CAC/B,CAFD,CAUA,QAASC,CAAAA,CAAT,EAAkB,CACdP,CAAI,CAACQ,SAAL,CAAeC,WAAf,CAA2BC,KAA3B,CAAiC,IAAjC,CAAuCC,SAAvC,EAGA,KAAKC,OAAL,CAAe,KAAKC,KAApB,CACA,GAAoC,QAAhC,OAAKD,OAAL,CAAaE,IAAb,CAAkB,SAAlB,CAAJ,CAA8C,CAC1C,KAAKF,OAAL,CAAehB,CAAC,CAAC,UA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,IAA9B,CAAqCG,CAAlD,CACH,CAED,MAAOC,CAAAA,CACV,CA1BD,CAmCApG,CAAM,CAACC,SAAP,CAAiBwF,SAAjB,CAA6B,SAASZ,CAAT,CAAiB,CAC1C,GAAI4B,CAAAA,CAAM,GAAV,CACA,GAAI,KAAKjF,MAAL,CAAYC,OAAZ,KAA0B/B,CAAI,CAACO,SAAL,CAAeyB,IAA7C,CAAmD,CAC/C+E,CAAM,CAAG5B,CAAM,CAAC6B,SAAP,EAAT,CACA,GAAe,IAAX,GAAAD,CAAJ,CAAqB,CACjBA,CAAM,CAAG,KAAKjF,MAAL,CAAYkF,SAAZ,EACZ,CACJ,CALD,IAKO,IAAI7B,CAAM,CAACpD,OAAP,KAAqB7B,CAAM,CAACK,SAAP,CAAiB0G,SAA1C,CAAqD,CACxDF,CAAM,CAAG5B,CAAM,CAAC6B,SAAP,EACZ,CAED,MAAOD,CAAAA,CACV,CAZD,CAoBAzG,CAAM,CAACC,SAAP,CAAiBiE,UAAjB,CAA8B,UAAW,CACrC,GAAID,CAAAA,CAAO,GAAX,CAGA,GAAI,KAAKzC,MAAL,CAAYC,OAAZ,KAA0BjC,CAAG,CAACS,SAAJ,CAAcyB,IAA5C,CAAkD,CAC9CuC,CAAO,CAAG,KAAKzC,MAAL,CAAYoF,UAAZ,EACb,CAED,MAAO3C,CAAAA,CACV,CATD,CAYAjE,CAAM,CAACC,SAAP,CAAiB4G,MAAjB,CAA0B,UAAW,CACjCxH,CAAC,CAACyH,MAAF,IAAe,KAAKlG,OAApB,CAA6B,KAAKE,WAAL,EAA7B,EACA,KAAKD,QAAL,CAAcgG,MAAd,EACH,CAHD,CAKA,MAAO7G,CAAAA,CAEV,CAnVK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Chart output for chart.js.\n *\n * @copyright 2016 Frédéric Massart - FMCorz.net\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @module core/chart_output_chartjs\n */\ndefine([\n 'jquery',\n 'core/chartjs',\n 'core/chart_axis',\n 'core/chart_bar',\n 'core/chart_output_base',\n 'core/chart_line',\n 'core/chart_pie',\n 'core/chart_series'\n], function($, Chartjs, Axis, Bar, Base, Line, Pie, Series) {\n\n /**\n * Makes an axis ID.\n *\n * @param {String} xy Accepts 'x' and 'y'.\n * @param {Number} index The axis index.\n * @return {String}\n */\n var makeAxisId = function(xy, index) {\n return 'axis-' + xy + '-' + index;\n };\n\n /**\n * Chart output for Chart.js.\n *\n * @class\n * @extends {module:core/chart_output_base}\n */\n function Output() {\n Base.prototype.constructor.apply(this, arguments);\n\n // Make sure that we've got a canvas tag.\n this._canvas = this._node;\n if (this._canvas.prop('tagName') != 'CANVAS') {\n this._canvas = $('');\n this._node.append(this._canvas);\n }\n\n this._build();\n }\n Output.prototype = Object.create(Base.prototype);\n\n /**\n * Reference to the chart config object.\n *\n * @type {Object}\n * @protected\n */\n Output.prototype._config = null;\n\n /**\n * Reference to the instance of chart.js.\n *\n * @type {Object}\n * @protected\n */\n Output.prototype._chartjs = null;\n\n /**\n * Reference to the canvas node.\n *\n * @type {Jquery}\n * @protected\n */\n Output.prototype._canvas = null;\n\n /**\n * Builds the config and the chart.\n *\n * @protected\n */\n Output.prototype._build = function() {\n this._config = this._makeConfig();\n this._chartjs = new Chartjs(this._canvas[0], this._config);\n };\n\n /**\n * Clean data.\n *\n * @param {(String|String[])} data A single string or an array of strings.\n * @returns {(String|String[])}\n * @protected\n */\n Output.prototype._cleanData = function(data) {\n if (data instanceof Array) {\n return data.map(function(value) {\n return $('').html(value).text();\n });\n } else {\n return $('').html(data).text();\n }\n };\n\n /**\n * Get the chart type and handles the Chart.js specific chart types.\n *\n * By default returns the current chart TYPE value. Also does the handling of specific chart types, for example\n * check if the bar chart should be horizontal and the pie chart should be displayed as a doughnut.\n *\n * @method getChartType\n * @returns {String} the chart type.\n * @protected\n */\n Output.prototype._getChartType = function() {\n var type = this._chart.getType();\n\n // Bars can be displayed vertically and horizontally, defining horizontalBar type.\n if (this._chart.getType() === Bar.prototype.TYPE && this._chart.getHorizontal() === true) {\n type = 'horizontalBar';\n } else if (this._chart.getType() === Pie.prototype.TYPE && this._chart.getDoughnut() === true) {\n // Pie chart can be displayed as doughnut.\n type = 'doughnut';\n }\n\n return type;\n };\n\n /**\n * Make the axis config.\n *\n * @protected\n * @param {module:core/chart_axis} axis The axis.\n * @param {String} xy Accepts 'x' or 'y'.\n * @param {Number} index The axis index.\n * @return {Object} The axis config.\n */\n Output.prototype._makeAxisConfig = function(axis, xy, index) {\n var scaleData = {\n id: makeAxisId(xy, index)\n };\n\n if (axis.getPosition() !== Axis.prototype.POS_DEFAULT) {\n scaleData.position = axis.getPosition();\n }\n\n if (axis.getLabel() !== null) {\n scaleData.scaleLabel = {\n display: true,\n labelString: this._cleanData(axis.getLabel())\n };\n }\n\n if (axis.getStepSize() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.stepSize = axis.getStepSize();\n }\n\n if (axis.getMax() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.max = axis.getMax();\n }\n\n if (axis.getMin() !== null) {\n scaleData.ticks = scaleData.ticks || {};\n scaleData.ticks.min = axis.getMin();\n }\n\n return scaleData;\n };\n\n /**\n * Make the config config.\n *\n * @protected\n * @return {Object} The axis config.\n */\n Output.prototype._makeConfig = function() {\n var config = {\n type: this._getChartType(),\n data: {\n labels: this._cleanData(this._chart.getLabels()),\n datasets: this._makeDatasetsConfig()\n },\n options: {\n title: {\n display: this._chart.getTitle() !== null,\n text: this._cleanData(this._chart.getTitle())\n }\n }\n };\n var legendOptions = this._chart.getLegendOptions();\n if (legendOptions) {\n config.options.legend = legendOptions;\n }\n\n\n this._chart.getXAxes().forEach(function(axis, i) {\n var axisLabels = axis.getLabels();\n\n config.options.scales = config.options.scales || {};\n config.options.scales.xAxes = config.options.scales.xAxes || [];\n config.options.scales.xAxes[i] = this._makeAxisConfig(axis, 'x', i);\n\n if (axisLabels !== null) {\n config.options.scales.xAxes[i].ticks.callback = function(value, index) {\n return axisLabels[index] || '';\n };\n }\n config.options.scales.xAxes[i].stacked = this._isStacked();\n }.bind(this));\n\n this._chart.getYAxes().forEach(function(axis, i) {\n var axisLabels = axis.getLabels();\n\n config.options.scales = config.options.scales || {};\n config.options.scales.yAxes = config.options.scales.yAxes || [];\n config.options.scales.yAxes[i] = this._makeAxisConfig(axis, 'y', i);\n\n if (axisLabels !== null) {\n config.options.scales.yAxes[i].ticks.callback = function(value) {\n return axisLabels[parseInt(value, 10)] || '';\n };\n }\n config.options.scales.yAxes[i].stacked = this._isStacked();\n }.bind(this));\n\n config.options.tooltips = {\n callbacks: {\n label: this._makeTooltip.bind(this)\n }\n };\n\n return config;\n };\n\n /**\n * Get the datasets configurations.\n *\n * @protected\n * @return {Object[]}\n */\n Output.prototype._makeDatasetsConfig = function() {\n var sets = this._chart.getSeries().map(function(series) {\n var colors = series.hasColoredValues() ? series.getColors() : series.getColor();\n var dataset = {\n label: this._cleanData(series.getLabel()),\n data: series.getValues(),\n type: series.getType(),\n fill: series.getFill(),\n backgroundColor: colors,\n // Pie charts look better without borders.\n borderColor: this._chart.getType() == Pie.prototype.TYPE ? '#fff' : colors,\n lineTension: this._isSmooth(series) ? 0.3 : 0\n };\n\n if (series.getXAxis() !== null) {\n dataset.xAxisID = makeAxisId('x', series.getXAxis());\n }\n if (series.getYAxis() !== null) {\n dataset.yAxisID = makeAxisId('y', series.getYAxis());\n }\n\n return dataset;\n }.bind(this));\n return sets;\n };\n\n /**\n * Get the chart data, add labels and rebuild the tooltip.\n *\n * @param {Object[]} tooltipItem The tooltip item data.\n * @param {Object[]} data The chart data.\n * @returns {String}\n * @protected\n */\n Output.prototype._makeTooltip = function(tooltipItem, data) {\n\n // Get series and chart data to rebuild the tooltip and add labels.\n var series = this._chart.getSeries()[tooltipItem.datasetIndex];\n var serieLabel = series.getLabel();\n var serieLabels = series.getLabels();\n var chartData = data.datasets[tooltipItem.datasetIndex].data;\n var tooltipData = chartData[tooltipItem.index];\n\n // Build default tooltip.\n var tooltip = [];\n\n // Pie and doughnut charts does not have axis.\n if (tooltipItem.xLabel == '' && tooltipItem.yLabel == '') {\n var chartLabels = this._cleanData(this._chart.getLabels());\n tooltip.push(chartLabels[tooltipItem.index]);\n }\n\n // Add series labels to the tooltip if any.\n if (serieLabels !== null) {\n tooltip.push(this._cleanData(serieLabels[tooltipItem.index]));\n } else {\n tooltip.push(this._cleanData(serieLabel) + ': ' + tooltipData);\n }\n\n return tooltip;\n };\n\n /**\n * Verify if the chart line is smooth or not.\n *\n * @protected\n * @param {module:core/chart_series} series The series.\n * @returns {Bool}\n */\n Output.prototype._isSmooth = function(series) {\n var smooth = false;\n if (this._chart.getType() === Line.prototype.TYPE) {\n smooth = series.getSmooth();\n if (smooth === null) {\n smooth = this._chart.getSmooth();\n }\n } else if (series.getType() === Series.prototype.TYPE_LINE) {\n smooth = series.getSmooth();\n }\n\n return smooth;\n };\n\n /**\n * Verify if the bar chart is stacked or not.\n *\n * @protected\n * @returns {Bool}\n */\n Output.prototype._isStacked = function() {\n var stacked = false;\n\n // Stacking is (currently) only supported for bar charts.\n if (this._chart.getType() === Bar.prototype.TYPE) {\n stacked = this._chart.getStacked();\n }\n\n return stacked;\n };\n\n /** @override */\n Output.prototype.update = function() {\n $.extend(true, this._config, this._makeConfig());\n this._chartjs.update();\n };\n\n return Output;\n\n});\n"],"file":"chart_output_chartjs.min.js"} \ No newline at end of file diff --git a/lib/amd/build/local/reactive/debug.min.js.map b/lib/amd/build/local/reactive/debug.min.js.map index e6855c5e1f79a..05ea7fa9eea15 100644 --- a/lib/amd/build/local/reactive/debug.min.js.map +++ b/lib/amd/build/local/reactive/debug.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/reactive/debug.js"],"names":["reactiveInstances","reactiveDebuggers","Debug","stateData","log","debug","instance","name","state","reactives","length","replace","DebugInstance","dispatch","refreshMethod","target","addEventListener","storeTransaction","detail","changes","JSON","parse","stringify","Reactive","Mutations","stateManager","setReadOnly","has","get","countcomponents","components","readOnly","readonly","modified","Date","getTime","add","id","lastChanges","forEach","change","push","eventName","_reactiveDebugData","highlighted","updates","processUpdates","value","element","border","style","result","eventsToPublish","stateChangedEventName","dispatchStateChangedEvent","document","dispatchEvent","CustomEvent","bubbles","initDebug","eventDispatch","mutations","registerNewInstance","bind","debuggers"],"mappings":"2LAuBA,OACA,O,ijGAGMA,CAAAA,CAAiB,CAAG,E,CAGpBC,CAAiB,CAAG,E,CAgBpBC,C,gJAOcC,C,CAAW,CACvB,mDAAsBA,CAAtB,EACAC,UAAIC,KAAJ,uCACH,C,gEAgBmBC,C,CAAU,cAGtBC,CAAI,WAAGD,CAAQ,CAACC,IAAZ,kCAA+B,KAAKC,KAAL,CAAWC,SAAX,CAAqBC,MAApD,CAHkB,CAI1BH,CAAI,CAAGA,CAAI,CAACI,OAAL,CAAa,KAAb,CAAoB,EAApB,CAAP,CAEAP,UAAIC,KAAJ,0DAA2DE,CAA3D,QAEAP,CAAiB,CAACO,CAAD,CAAjB,CAA0BD,CAA1B,CACAL,CAAiB,CAACM,CAAD,CAAjB,CAA0B,GAAIK,CAAAA,CAAJ,CAAkBZ,CAAiB,CAACO,CAAD,CAAnC,CAA1B,CAEA,KAAKM,QAAL,CAAc,aAAd,CAA6BN,CAA7B,CAAmCD,CAAnC,EAEA,GAAMQ,CAAAA,CAAa,CAAG,UAAM,CACxB,CAAI,CAACD,QAAL,CAAc,aAAd,CAA6BN,CAA7B,CAAmCD,CAAnC,CACH,CAFD,CAGAA,CA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ApB,CAAX,CACV,C,gBAYC6C,CAAqB,CAAG,kC,CAS9B,QAASC,CAAAA,CAAT,CAAmCpC,CAAnC,CAA2CH,CAA3C,CAAmD,CAC/C,GAAIA,CAAM,SAAV,CAA0B,CACtBA,CAAM,CAAGwC,QACZ,CACDxC,CAAM,CAACyC,aAAP,CACI,GAAIC,CAAAA,WAAJ,CACIJ,CADJ,CAEI,CACIK,OAAO,GADX,CAEIxC,MAAM,CAAEA,CAFZ,CAFJ,CADJ,CASH,C,YAMwB,QAAZyC,CAAAA,SAAY,EAAM,CAC3B,GAAMtD,CAAAA,CAAK,CAAG,GAAIH,CAAAA,CAAJ,CAAU,CACpBK,IAAI,CAAE,mBADc,CAEpBmC,SAAS,CAAEW,CAFS,CAGpBO,aAAa,CAAEN,CAHK,CAIpBO,SAAS,CAAE,GAAIrC,CAAAA,CAJK,CAKpBhB,KAAK,CAAE,CACHC,SAAS,CAAE,EADR,CALa,CAAV,CAAd,CAYAR,CAAiB,CAAC6D,mBAAlB,CAAwCzD,CAAK,CAACyD,mBAAN,CAA0BC,IAA1B,CAA+B1D,CAA/B,CAAxC,CAEA,MAAO,CACHA,KAAK,CAALA,CADG,CAEH2D,SAAS,CAAE/D,CAFR,CAIV,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Reactive module debug tools.\n *\n * @module core/reactive/local/reactive/debug\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Reactive from 'core/local/reactive/reactive';\nimport log from 'core/log';\n\n// The list of reactives instances.\nconst reactiveInstances = {};\n\n// The reactive debugging objects.\nconst reactiveDebuggers = {};\n\n/**\n * Reactive module debug tools.\n *\n * If debug is enabled, this reactive module will spy all the reactive instances and keep a record\n * of the changes and components they have.\n *\n * It is important to note that the Debug class is also a Reactive module. The debug instance keeps\n * the reactive instances data as its own state. This way it is possible to implement development tools\n * that whatches this data.\n *\n * @class core/reactive/local/reactive/debug/Debug\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nclass Debug extends Reactive {\n\n /**\n * Set the initial state.\n *\n * @param {object} stateData the initial state data.\n */\n setInitialState(stateData) {\n super.setInitialState(stateData);\n log.debug(`Debug module \"M.reactive\" loaded.`);\n }\n\n /**\n * List the currents page reactives instances.\n */\n get list() {\n return JSON.parse(JSON.stringify(this.state.reactives));\n }\n\n /**\n * Register a new Reactive instance.\n *\n * This method is called every time a \"new Reactive\" is executed.\n *\n * @param {Reactive} instance the reactive instance\n */\n registerNewInstance(instance) {\n\n // Generate a valid variable name for that instance.\n let name = instance.name ?? `instance${this.state.reactives.length}`;\n name = name.replace(/\\W/g, '');\n\n log.debug(`Registering new reactive instance \"M.reactive.${name}\"`);\n\n reactiveInstances[name] = instance;\n reactiveDebuggers[name] = new DebugInstance(reactiveInstances[name]);\n // Register also in the state.\n this.dispatch('putInstance', name, instance);\n // Add debug watchers to instance.\n const refreshMethod = () => {\n this.dispatch('putInstance', name, instance);\n };\n instance.target.addEventListener('readmode:on', refreshMethod);\n instance.target.addEventListener('readmode:off', refreshMethod);\n instance.target.addEventListener('registerComponent:success', refreshMethod);\n instance.target.addEventListener('transaction:end', refreshMethod);\n // We store the last transaction into the state.\n const storeTransaction = ({detail}) => {\n const changes = detail?.changes;\n this.dispatch('lastTransaction', name, changes);\n };\n instance.target.addEventListener('transaction:start', storeTransaction);\n }\n\n /**\n * Returns a debugging object for a specific Reactive instance.\n *\n * A debugging object is a class that wraps a Reactive instance to quick access some of the\n * reactive methods using the browser JS console.\n *\n * @param {string} name the Reactive instance name\n * @returns {DebugInstance} a debug object wrapping the Reactive instance\n */\n debug(name) {\n return reactiveDebuggers[name];\n }\n}\n\n/**\n * The debug state mutations class.\n *\n * @class core/reactive/local/reactive/debug/Mutations\n */\nclass Mutations {\n\n /**\n * Insert or update a new instance into the debug state.\n *\n * @param {StateManager} stateManager the debug state manager\n * @param {string} name the instance name\n * @param {Reactive} instance the reactive instance\n */\n putInstance(stateManager, name, instance) {\n const state = stateManager.state;\n\n stateManager.setReadOnly(false);\n\n if (state.reactives.has(name)) {\n state.reactives.get(name).countcomponents = instance.components.length;\n state.reactives.get(name).readOnly = instance.stateManager.readonly;\n state.reactives.get(name).modified = new Date().getTime();\n } else {\n state.reactives.add({\n id: name,\n countcomponents: instance.components.length,\n readOnly: instance.stateManager.readonly,\n lastChanges: [],\n modified: new Date().getTime(),\n });\n }\n stateManager.setReadOnly(true);\n }\n\n /**\n * Update the lastChanges attribute with a list of changes\n *\n * @param {StateManager} stateManager the debug reactive state\n * @param {string} name tje instance name\n * @param {array} changes the list of changes\n */\n lastTransaction(stateManager, name, changes) {\n if (!changes || changes.length === 0) {\n return;\n }\n\n const state = stateManager.state;\n const lastChanges = ['transaction:start'];\n\n changes.forEach(change => {\n lastChanges.push(change.eventName);\n });\n\n lastChanges.push('transaction:end');\n\n stateManager.setReadOnly(false);\n\n state.reactives.get(name).lastChanges = lastChanges;\n\n stateManager.setReadOnly(true);\n }\n}\n\n/**\n * Class used to debug a specific instance and manipulate the state from the JS console.\n *\n * @class core/reactive/local/reactive/debug/DebugInstance\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nclass DebugInstance {\n\n /**\n * Constructor.\n *\n * @param {Reactive} instance the reactive instance\n */\n constructor(instance) {\n this.instance = instance;\n // Add some debug data directly into the instance. This way we avoid having attributes\n // that will confuse the console aoutocomplete.\n if (instance._reactiveDebugData === undefined) {\n instance._reactiveDebugData = {\n highlighted: false,\n };\n }\n }\n\n /**\n * Set the read only mode.\n *\n * Quick access to the instance setReadOnly method.\n *\n * @param {bool} value: the new read only value\n */\n set readOnly(value) {\n this.instance.stateManager.setReadOnly(value);\n }\n\n /**\n * Get the read only value\n *\n * @return {bool}\n */\n get readOnly() {\n return this.instance.stateManager.readonly;\n }\n\n /**\n * Return the current state object.\n *\n * @return {object}\n */\n get state() {\n return this.instance.state;\n }\n\n /**\n * Tooggle the reactive HTML element highlight registered in this reactive instance.\n *\n * @param {bool} value the highlight value\n */\n set highlight(value) {\n this.instance._reactiveDebugData.highlighted = value;\n this.instance.components.forEach(({element}) => {\n const border = (value) ? `thick solid #0000FF` : '';\n element.style.border = border;\n });\n }\n\n /**\n * Get the current highligh value.\n *\n * @return {bool}\n */\n get highlight() {\n return this.instance._reactiveDebugData.highlighted;\n }\n\n /**\n * List all the components registered in this instance.\n *\n * @return {array}\n */\n get components() {\n return [...this.instance.components];\n }\n\n /**\n * List all the state changes evenet pending to dispatch.\n *\n * @return {array}\n */\n get changes() {\n const result = [];\n this.instance.stateManager.eventsToPublish.forEach(\n (element) => {\n result.push(element.eventName);\n }\n );\n return result;\n }\n\n /**\n * Dispatch a change in the state.\n *\n * Usually reactive modules throw an error directly to the components when something\n * goes wrong. However, course editor can directly display a notification.\n *\n * @method dispatch\n * @param {string} actionName the action name (usually the mutation name)\n * @param {*} param any number of params the mutation needs.\n */\n async dispatch(...args) {\n this.instance.dispatch(...args);\n }\n\n /**\n * Return all the HTML elements registered in the instance components.\n *\n * @return {array}\n */\n get elements() {\n const result = [];\n this.instance.components.forEach(({element}) => {\n result.push(element);\n });\n return result;\n }\n\n /**\n * Return a plain copy of the state data.\n *\n * @return {object}\n */\n get stateData() {\n return JSON.parse(JSON.stringify(this.state));\n }\n\n /**\n * Process an update state array.\n *\n * @param {array} updates an array of update state messages\n */\n processUpdates(updates) {\n this.instance.stateManager.processUpdates(updates);\n }\n}\n\nconst stateChangedEventName = 'core_reactive_debug:stateChanged';\n\n/**\n * Internal state changed event.\n *\n * @method dispatchStateChangedEvent\n * @param {object} detail the full state\n * @param {object} target the custom event target (document if none provided)\n */\nfunction dispatchStateChangedEvent(detail, target) {\n if (target === undefined) {\n target = document;\n }\n target.dispatchEvent(\n new CustomEvent(\n stateChangedEventName,\n {\n bubbles: true,\n detail: detail,\n }\n )\n );\n}\n\n/**\n * The main init method to initialize the reactive debug.\n * @returns {object}\n */\nexport const initDebug = () => {\n const debug = new Debug({\n name: 'CoreReactiveDebug',\n eventName: stateChangedEventName,\n eventDispatch: dispatchStateChangedEvent,\n mutations: new Mutations(),\n state: {\n reactives: [],\n },\n });\n\n // The reactiveDebuggers will be used as a way of access the debug instances but also to register every new\n // instance. To ensure this will update the reactive debug state we add the registerNewInstance method to it.\n reactiveDebuggers.registerNewInstance = debug.registerNewInstance.bind(debug);\n\n return {\n debug,\n debuggers: reactiveDebuggers,\n };\n};\n"],"file":"debug.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/reactive/debug.js"],"names":["reactiveInstances","reactiveDebuggers","Debug","stateData","log","debug","instance","name","state","reactives","length","replace","DebugInstance","dispatch","refreshMethod","target","addEventListener","storeTransaction","detail","changes","JSON","parse","stringify","Reactive","Mutations","stateManager","setReadOnly","has","get","countcomponents","components","readOnly","readonly","modified","Date","getTime","add","id","lastChanges","forEach","change","push","eventName","_reactiveDebugData","highlighted","updates","processUpdates","value","element","border","style","result","eventsToPublish","stateChangedEventName","dispatchStateChangedEvent","document","dispatchEvent","CustomEvent","bubbles","initDebug","eventDispatch","mutations","registerNewInstance","bind","debuggers"],"mappings":"2LAuBA,OACA,O,ijGAGMA,CAAAA,CAAiB,CAAG,E,CAGpBC,CAAiB,CAAG,E,CAgBpBC,C,gJAOcC,C,CAAW,CACvB,mDAAsBA,CAAtB,EACAC,UAAIC,KAAJ,uCACH,C,gEAgBmBC,C,CAAU,cAGtBC,CAAI,WAAGD,CAAQ,CAACC,IAAZ,kCAA+B,KAAKC,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AAS,CAAE/D,CAFR,CAIV,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Reactive module debug tools.\n *\n * @module core/reactive/local/reactive/debug\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Reactive from 'core/local/reactive/reactive';\nimport log from 'core/log';\n\n// The list of reactives instances.\nconst reactiveInstances = {};\n\n// The reactive debugging objects.\nconst reactiveDebuggers = {};\n\n/**\n * Reactive module debug tools.\n *\n * If debug is enabled, this reactive module will spy all the reactive instances and keep a record\n * of the changes and components they have.\n *\n * It is important to note that the Debug class is also a Reactive module. The debug instance keeps\n * the reactive instances data as its own state. This way it is possible to implement development tools\n * that whatches this data.\n *\n * @class core/reactive/local/reactive/debug/Debug\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nclass Debug extends Reactive {\n\n /**\n * Set the initial state.\n *\n * @param {object} stateData the initial state data.\n */\n setInitialState(stateData) {\n super.setInitialState(stateData);\n log.debug(`Debug module \"M.reactive\" loaded.`);\n }\n\n /**\n * List the currents page reactives instances.\n */\n get list() {\n return JSON.parse(JSON.stringify(this.state.reactives));\n }\n\n /**\n * Register a new Reactive instance.\n *\n * This method is called every time a \"new Reactive\" is executed.\n *\n * @param {Reactive} instance the reactive instance\n */\n registerNewInstance(instance) {\n\n // Generate a valid variable name for that instance.\n let name = instance.name ?? `instance${this.state.reactives.length}`;\n name = name.replace(/\\W/g, '');\n\n log.debug(`Registering new reactive instance \"M.reactive.${name}\"`);\n\n reactiveInstances[name] = instance;\n reactiveDebuggers[name] = new DebugInstance(reactiveInstances[name]);\n // Register also in the state.\n this.dispatch('putInstance', name, instance);\n // Add debug watchers to instance.\n const refreshMethod = () => {\n this.dispatch('putInstance', name, instance);\n };\n instance.target.addEventListener('readmode:on', refreshMethod);\n instance.target.addEventListener('readmode:off', refreshMethod);\n instance.target.addEventListener('registerComponent:success', refreshMethod);\n instance.target.addEventListener('transaction:end', refreshMethod);\n // We store the last transaction into the state.\n const storeTransaction = ({detail}) => {\n const changes = detail?.changes;\n this.dispatch('lastTransaction', name, changes);\n };\n instance.target.addEventListener('transaction:start', storeTransaction);\n }\n\n /**\n * Returns a debugging object for a specific Reactive instance.\n *\n * A debugging object is a class that wraps a Reactive instance to quick access some of the\n * reactive methods using the browser JS console.\n *\n * @param {string} name the Reactive instance name\n * @returns {DebugInstance} a debug object wrapping the Reactive instance\n */\n debug(name) {\n return reactiveDebuggers[name];\n }\n}\n\n/**\n * The debug state mutations class.\n *\n * @class core/reactive/local/reactive/debug/Mutations\n */\nclass Mutations {\n\n /**\n * Insert or update a new instance into the debug state.\n *\n * @param {StateManager} stateManager the debug state manager\n * @param {string} name the instance name\n * @param {Reactive} instance the reactive instance\n */\n putInstance(stateManager, name, instance) {\n const state = stateManager.state;\n\n stateManager.setReadOnly(false);\n\n if (state.reactives.has(name)) {\n state.reactives.get(name).countcomponents = instance.components.length;\n state.reactives.get(name).readOnly = instance.stateManager.readonly;\n state.reactives.get(name).modified = new Date().getTime();\n } else {\n state.reactives.add({\n id: name,\n countcomponents: instance.components.length,\n readOnly: instance.stateManager.readonly,\n lastChanges: [],\n modified: new Date().getTime(),\n });\n }\n stateManager.setReadOnly(true);\n }\n\n /**\n * Update the lastChanges attribute with a list of changes\n *\n * @param {StateManager} stateManager the debug reactive state\n * @param {string} name tje instance name\n * @param {array} changes the list of changes\n */\n lastTransaction(stateManager, name, changes) {\n if (!changes || changes.length === 0) {\n return;\n }\n\n const state = stateManager.state;\n const lastChanges = ['transaction:start'];\n\n changes.forEach(change => {\n lastChanges.push(change.eventName);\n });\n\n lastChanges.push('transaction:end');\n\n stateManager.setReadOnly(false);\n\n state.reactives.get(name).lastChanges = lastChanges;\n\n stateManager.setReadOnly(true);\n }\n}\n\n/**\n * Class used to debug a specific instance and manipulate the state from the JS console.\n *\n * @class core/reactive/local/reactive/debug/DebugInstance\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nclass DebugInstance {\n\n /**\n * Constructor.\n *\n * @param {Reactive} instance the reactive instance\n */\n constructor(instance) {\n this.instance = instance;\n // Add some debug data directly into the instance. This way we avoid having attributes\n // that will confuse the console aoutocomplete.\n if (instance._reactiveDebugData === undefined) {\n instance._reactiveDebugData = {\n highlighted: false,\n };\n }\n }\n\n /**\n * Set the read only mode.\n *\n * Quick access to the instance setReadOnly method.\n *\n * @param {bool} value the new read only value\n */\n set readOnly(value) {\n this.instance.stateManager.setReadOnly(value);\n }\n\n /**\n * Get the read only value\n *\n * @returns {bool}\n */\n get readOnly() {\n return this.instance.stateManager.readonly;\n }\n\n /**\n * Return the current state object.\n *\n * @returns {object}\n */\n get state() {\n return this.instance.state;\n }\n\n /**\n * Tooggle the reactive HTML element highlight registered in this reactive instance.\n *\n * @param {bool} value the highlight value\n */\n set highlight(value) {\n this.instance._reactiveDebugData.highlighted = value;\n this.instance.components.forEach(({element}) => {\n const border = (value) ? `thick solid #0000FF` : '';\n element.style.border = border;\n });\n }\n\n /**\n * Get the current highligh value.\n *\n * @returns {bool}\n */\n get highlight() {\n return this.instance._reactiveDebugData.highlighted;\n }\n\n /**\n * List all the components registered in this instance.\n *\n * @returns {array}\n */\n get components() {\n return [...this.instance.components];\n }\n\n /**\n * List all the state changes evenet pending to dispatch.\n *\n * @returns {array}\n */\n get changes() {\n const result = [];\n this.instance.stateManager.eventsToPublish.forEach(\n (element) => {\n result.push(element.eventName);\n }\n );\n return result;\n }\n\n /**\n * Dispatch a change in the state.\n *\n * Usually reactive modules throw an error directly to the components when something\n * goes wrong. However, course editor can directly display a notification.\n *\n * @method dispatch\n * @param {*} args\n */\n async dispatch(...args) {\n this.instance.dispatch(...args);\n }\n\n /**\n * Return all the HTML elements registered in the instance components.\n *\n * @returns {array}\n */\n get elements() {\n const result = [];\n this.instance.components.forEach(({element}) => {\n result.push(element);\n });\n return result;\n }\n\n /**\n * Return a plain copy of the state data.\n *\n * @returns {object}\n */\n get stateData() {\n return JSON.parse(JSON.stringify(this.state));\n }\n\n /**\n * Process an update state array.\n *\n * @param {array} updates an array of update state messages\n */\n processUpdates(updates) {\n this.instance.stateManager.processUpdates(updates);\n }\n}\n\nconst stateChangedEventName = 'core_reactive_debug:stateChanged';\n\n/**\n * Internal state changed event.\n *\n * @method dispatchStateChangedEvent\n * @param {object} detail the full state\n * @param {object} target the custom event target (document if none provided)\n */\nfunction dispatchStateChangedEvent(detail, target) {\n if (target === undefined) {\n target = document;\n }\n target.dispatchEvent(\n new CustomEvent(\n stateChangedEventName,\n {\n bubbles: true,\n detail: detail,\n }\n )\n );\n}\n\n/**\n * The main init method to initialize the reactive debug.\n * @returns {object}\n */\nexport const initDebug = () => {\n const debug = new Debug({\n name: 'CoreReactiveDebug',\n eventName: stateChangedEventName,\n eventDispatch: dispatchStateChangedEvent,\n mutations: new Mutations(),\n state: {\n reactives: [],\n },\n });\n\n // The reactiveDebuggers will be used as a way of access the debug instances but also to register every new\n // instance. To ensure this will update the reactive debug state we add the registerNewInstance method to it.\n reactiveDebuggers.registerNewInstance = debug.registerNewInstance.bind(debug);\n\n return {\n debug,\n debuggers: reactiveDebuggers,\n };\n};\n"],"file":"debug.min.js"} \ No newline at end of file diff --git a/lib/amd/build/local/reactive/debugpanel.min.js.map b/lib/amd/build/local/reactive/debugpanel.min.js.map index ad4de543e8dda..2931a336e79b3 100644 --- a/lib/amd/build/local/reactive/debugpanel.min.js.map +++ b/lib/amd/build/local/reactive/debugpanel.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/reactive/debugpanel.js"],"names":["init","target","selectors","element","document","getElementById","debug","remove","GlobalDebugPanel","reactive","initsubpanel","DebugInstanceSubpanel","name","LOADERS","SUBPANEL","LOG","state","reactives","size","getElement","innerHTML","forEach","instance","_createLoader","loaders","btn","createElement","id","dataset","appendChild","addEventListener","_openPanel","data","renderComponent","log","error","BaseComponent","NAME","CLOSE","READMODE","HIGHLIGHT","STATE","CLEAN","PIN","SAVE","INVALID","controller","M","draggable","relativeDrag","strings","savewarning","dragdrop","DragDrop","highlight","_toggleButtonText","_toggleEditMode","_cleanAreas","_togglePin","disabled","_checkJSON","_saveState","_refreshState","unregister","watch","handler","_refreshLog","_refreshReadOnly","list","lastChanges","logContent","join","value","scrollTop","scrollHeight","JSON","stringify","readonly","readOnly","alt","invalid","save","edited","currentStateData","stateData","style","color","newState","parse","result","_generateStateUpdates","message","updates","processUpdates","newStateData","ids","key","newValue","Array","isArray","Error","push","action","fields","index","valueOf","Object","entries","oldValue","deleteField","deleteEntry","dropdata","event","top","newFixedTop","left","newFixedLeft","setDraggable","_unpin","_pin","pageCenterY","window","innerHeight","pageCenterX","innerWidth","position","resize","overflow","height","width","assign","prop","removeProperty"],"mappings":"0MA4BA,uD,ymHASoB,QAAPA,CAAAA,IAAO,CAACC,CAAD,CAASC,CAAT,CAAuB,CACvC,GAAMC,CAAAA,CAAO,CAAGC,QAAQ,CAACC,cAAT,CAAwBJ,CAAxB,CAAhB,CAEA,GAAIK,gBAAJ,CAAyB,CACrBH,CAAO,CAACI,MAAR,GACA,MACH,CAED,GAAIC,CAAAA,CAAJ,CAAqB,CACjBL,OAAO,CAAPA,CADiB,CAEjBM,QAAQ,CAAEH,OAFO,CAGjBJ,SAAS,CAATA,CAHiB,CAArB,CAKH,C,gBAQ2B,QAAfQ,CAAAA,YAAe,CAACT,CAAD,CAASC,CAAT,CAAuB,CAC/C,GAAMC,CAAAA,CAAO,CAAGC,QAAQ,CAACC,c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CAAO,CAACiB,SAA9B,CADpB,CACtBjB,CAAO,CAACiB,SADc,MACHjB,CAAO,CAACyB,OAAR,CAAgBmD,GADb,KAE1B,C,cAvZ+B3C,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Reactive module debug panel.\n *\n * This module contains all the UI components for the reactive debug tools.\n * Those tools are only available if the debug is enables and could be used\n * from the footer.\n *\n * @module core/local/reactive/debugpanel\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent, DragDrop, debug} from 'core/reactive';\nimport log from 'core/log';\nimport {debounce} from 'core/utils';\n\n/**\n * Init the main reactive panel.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n */\nexport const init = (target, selectors) => {\n const element = document.getElementById(target);\n // Check if the debug reactive module is available.\n if (debug === undefined) {\n element.remove();\n return;\n }\n // Create the main component.\n new GlobalDebugPanel({\n element,\n reactive: debug,\n selectors,\n });\n};\n\n/**\n * Init an instance reactive subpanel.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n */\nexport const initsubpanel = (target, selectors) => {\n const element = document.getElementById(target);\n // Check if the debug reactive module is available.\n if (debug === undefined) {\n element.remove();\n return;\n }\n // Create the main component.\n new DebugInstanceSubpanel({\n element,\n reactive: debug,\n selectors,\n });\n};\n\n/**\n * Component for the main reactive dev panel.\n *\n * This component shows the list of reactive instances and handle the buttons\n * to open a specific instance panel.\n */\nclass GlobalDebugPanel extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'GlobalDebugPanel';\n // Default query selectors.\n this.selectors = {\n LOADERS: `[data-for='loaders']`,\n SUBPANEL: `[data-for='subpanel']`,\n LOG: `[data-for='log']`,\n };\n }\n\n /**\n * Initial state ready method.\n *\n * @param {object} state the initial state\n */\n stateReady(state) {\n if (state.reactives.size > 0) {\n this.getElement(this.selectors.LOADERS).innerHTML = '';\n }\n // Generate loading buttons.\n state.reactives.forEach(\n instance => {\n this._createLoader(instance);\n }\n );\n // Remove loading wheel.\n this.getElement(this.selectors.SUBPANEL).innerHTML = '';\n }\n\n /**\n * Create a debug panel button for a specific reactive instance.\n *\n * @param {object} instance hte instance data\n */\n _createLoader(instance) {\n const loaders = this.getElement(this.selectors.LOADERS);\n const btn = document.createElement(\"button\");\n btn.innerHTML = instance.id;\n btn.dataset.id = instance.id;\n loaders.appendChild(btn);\n // Add click event.\n this.addEventListener(btn, 'click', () => this._openPanel(btn, instance));\n }\n\n /**\n * Open a debug panel.\n *\n * @param {Element} btn the button element\n * @param {object} instance the instance data\n */\n async _openPanel(btn, instance) {\n try {\n const target = this.getElement(this.selectors.SUBPANEL);\n const data = {...instance};\n await this.renderComponent(target, 'core/local/reactive/debuginstancepanel', data);\n } catch (error) {\n log.error('Cannot load reactive debug subpanel');\n throw error;\n }\n }\n}\n\n/**\n * Component for the main reactive dev panel.\n *\n * This component shows the list of reactive instances and handle the buttons\n * to open a specific instance panel.\n */\nclass DebugInstanceSubpanel extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'DebugInstanceSubpanel';\n // Default query selectors.\n this.selectors = {\n NAME: `[data-for='name']`,\n CLOSE: `[data-for='close']`,\n READMODE: `[data-for='readmode']`,\n HIGHLIGHT: `[data-for='highlight']`,\n LOG: `[data-for='log']`,\n STATE: `[data-for='state']`,\n CLEAN: `[data-for='clean']`,\n PIN: `[data-for='pin']`,\n SAVE: `[data-for='save']`,\n INVALID: `[data-for='invalid']`,\n };\n this.id = this.element.dataset.id;\n this.controller = M.reactive[this.id];\n\n // The component is created always pinned.\n this.draggable = false;\n // We want the element to be dragged like modal.\n this.relativeDrag = true;\n // Save warning (will be loaded when state is ready.\n this.strings = {\n savewarning: '',\n };\n }\n\n /**\n * Initial state ready method.\n *\n */\n stateReady() {\n // Enable drag and drop.\n this.dragdrop = new DragDrop(this);\n\n // Close button.\n this.addEventListener(\n this.getElement(this.selectors.CLOSE),\n 'click',\n this.remove\n );\n // Highlight button.\n if (this.controller.highlight) {\n this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT));\n }\n this.addEventListener(\n this.getElement(this.selectors.HIGHLIGHT),\n 'click',\n () => {\n this.controller.highlight = !this.controller.highlight;\n this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT));\n }\n );\n // Edit mode button.\n this.addEventListener(\n this.getElement(this.selectors.READMODE),\n 'click',\n this._toggleEditMode\n );\n // Clean log and state.\n this.addEventListener(\n this.getElement(this.selectors.CLEAN),\n 'click',\n this._cleanAreas\n );\n // Unpin panel butotn.\n this.addEventListener(\n this.getElement(this.selectors.PIN),\n 'click',\n this._togglePin\n );\n // Save button, state format error message and state textarea.\n this.getElement(this.selectors.SAVE).disabled = true;\n\n this.addEventListener(\n this.getElement(this.selectors.STATE),\n 'keyup',\n debounce(this._checkJSON, 500)\n );\n\n this.addEventListener(\n this.getElement(this.selectors.SAVE),\n 'click',\n this._saveState\n );\n // Save the default save warning message.\n this.strings.savewarning = this.getElement(this.selectors.INVALID)?.innerHTML ?? '';\n // Add current state.\n this._refreshState();\n }\n\n /**\n * Remove all subcomponents dependencies.\n */\n destroy() {\n if (this.dragdrop !== undefined) {\n this.dragdrop.unregister();\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `reactives[${this.id}].lastChanges:updated`, handler: this._refreshLog},\n {watch: `reactives[${this.id}].modified:updated`, handler: this._refreshState},\n {watch: `reactives[${this.id}].readOnly:updated`, handler: this._refreshReadOnly},\n ];\n }\n\n /**\n * Wtacher method to refresh the log panel.\n *\n * @param {object} detail of the change\n */\n _refreshLog({element}) {\n const list = element?.lastChanges ?? [];\n\n const logContent = list.join(\"\\n\");\n // Append last log.\n const target = this.getElement(this.selectors.LOG);\n target.value += `\\n\\n= Transaction =\\n ${logContent}`;\n target.scrollTop = target.scrollHeight;\n }\n\n /**\n * Listener method to clean the log area.\n */\n _cleanAreas() {\n let target = this.getElement(this.selectors.LOG);\n target.value = '';\n\n this._refreshState();\n }\n\n /**\n * Watcher to refresh the state information.\n */\n _refreshState() {\n const target = this.getElement(this.selectors.STATE);\n target.value = JSON.stringify(this.controller.state, null, 4);\n }\n\n /**\n * Watcher to update the read only information.\n */\n _refreshReadOnly() {\n // Toggle the read mode button.\n const target = this.getElement(this.selectors.READMODE);\n if (target.dataset.readonly === undefined) {\n target.dataset.readonly = target.innerHTML;\n }\n if (this.controller.readOnly) {\n target.innerHTML = target.dataset.readonly;\n } else {\n target.innerHTML = target.dataset.alt;\n }\n }\n\n /**\n * Listener to toggle the edit mode of the component.\n */\n _toggleEditMode() {\n this.controller.readOnly = !this.controller.readOnly;\n }\n\n /**\n * Check that the edited state JSON is valid.\n *\n * Not all valid JSON are suitable for transforming the state. For example,\n * the first level attributes cannot change the type.\n *\n * @return {undefined|array} Array of state updates.\n */\n _checkJSON() {\n const invalid = this.getElement(this.selectors.INVALID);\n const save = this.getElement(this.selectors.SAVE);\n\n const edited = this.getElement(this.selectors.STATE).value;\n\n const currentStateData = this.controller.stateData;\n\n // Check if the json is tha same as state.\n if (edited == JSON.stringify(this.controller.state, null, 4)) {\n invalid.style.color = '';\n invalid.innerHTML = '';\n save.disabled = true;\n return undefined;\n }\n\n // Check if the json format is valid.\n try {\n const newState = JSON.parse(edited);\n // Check the first level did not change types.\n const result = this._generateStateUpdates(currentStateData, newState);\n // Enable save button.\n invalid.style.color = '';\n invalid.innerHTML = this.strings.savewarning;\n save.disabled = false;\n return result;\n } catch (error) {\n invalid.style.color = 'red';\n invalid.innerHTML = error.message ?? 'Invalid JSON sctructure';\n save.disabled = true;\n return undefined;\n }\n }\n\n /**\n * Listener to save the current edited state into the real state.\n */\n _saveState() {\n const updates = this._checkJSON();\n if (!updates) {\n return;\n }\n // Sent the updates to the state manager.\n this.controller.processUpdates(updates);\n }\n\n /**\n * Check that the edited state JSON is valid.\n *\n * Not all valid JSON are suitable for transforming the state. For example,\n * the first level attributes cannot change the type. This method do a two\n * steps comparison between the current state data and the new state data.\n *\n * A reactive state cannot be overridden like any other variable. To keep\n * the watchers updated is necessary to transform the current state into\n * the new one. As a result, this method generates all the necessary state\n * updates to convert the state into the new state.\n *\n * @param {object} currentStateData\n * @param {object} newStateData\n * @return {array} Array of state updates.\n * @throws {Error} is the structure is not compatible\n */\n _generateStateUpdates(currentStateData, newStateData) {\n\n const updates = [];\n\n const ids = {};\n\n // Step 1: Add all overrides newStateData.\n for (const [key, newValue] of Object.entries(newStateData)) {\n // Check is it is new.\n if (Array.isArray(newValue)) {\n ids[key] = {};\n newValue.forEach(element => {\n if (element.id === undefined) {\n throw Error(`Array ${key} element without id attribute`);\n }\n updates.push({\n name: key,\n action: 'override',\n fields: element,\n });\n const index = String(element.id).valueOf();\n ids[key][index] = true;\n });\n } else {\n updates.push({\n name: key,\n action: 'override',\n fields: newValue,\n });\n }\n }\n // Step 2: delete unnecesary data from currentStateData.\n for (const [key, oldValue] of Object.entries(currentStateData)) {\n let deleteField = false;\n // Check if the attribute is still there.\n if (newStateData[key] === undefined) {\n deleteField = true;\n }\n if (Array.isArray(oldValue)) {\n if (!deleteField && ids[key] === undefined) {\n throw Error(`Array ${key} cannot change to object.`);\n }\n oldValue.forEach(element => {\n const index = String(element.id).valueOf();\n let deleteEntry = deleteField;\n // Check if the id is there.\n if (!deleteEntry && ids[key][index] === undefined) {\n deleteEntry = true;\n }\n if (deleteEntry) {\n updates.push({\n name: key,\n action: 'delete',\n fields: element,\n });\n }\n });\n } else {\n if (!deleteField && ids[key] !== undefined) {\n throw Error(`Object ${key} cannot change to array.`);\n }\n if (deleteField) {\n updates.push({\n name: key,\n action: 'delete',\n fields: oldValue,\n });\n }\n }\n }\n // Delete all elements without action.\n return updates;\n }\n\n // Drag and drop methods.\n\n /**\n * Get the draggable data of this component.\n *\n * @returns {Object} exported course module drop data\n */\n getDraggableData() {\n return this.draggable;\n }\n\n /**\n * The element drop end hook.\n *\n * @param {Object} dropdata the dropdata\n * @param {Event} event the dropdata\n */\n dragEnd(dropdata, event) {\n this.element.style.top = `${event.newFixedTop}px`;\n this.element.style.left = `${event.newFixedLeft}px`;\n }\n\n /**\n * Pin and unpin the panel.\n */\n _togglePin() {\n this.draggable = !this.draggable;\n this.dragdrop.setDraggable(this.draggable);\n if (this.draggable) {\n this._unpin();\n } else {\n this._pin();\n }\n }\n\n /**\n * Unpin the panel form the footer.\n */\n _unpin() {\n // Find the initial spot.\n const pageCenterY = window.innerHeight / 2;\n const pageCenterX = window.innerWidth / 2;\n // Put the element in the middle of the screen\n const style = {\n position: 'fixed',\n resize: 'both',\n overflow: 'auto',\n height: '400px',\n width: '400px',\n top: `${pageCenterY - 200}px`,\n left: `${pageCenterX - 200}px`,\n };\n Object.assign(this.element.style, style);\n // Small also the text areas.\n this.getElement(this.selectors.STATE).style.height = '50px';\n this.getElement(this.selectors.LOG).style.height = '50px';\n\n this._toggleButtonText(this.getElement(this.selectors.PIN));\n }\n\n /**\n * Pin the panel into the footer.\n */\n _pin() {\n const props = [\n 'position',\n 'resize',\n 'overflow',\n 'top',\n 'left',\n 'height',\n 'width',\n ];\n props.forEach(\n prop => this.element.style.removeProperty(prop)\n );\n this._toggleButtonText(this.getElement(this.selectors.PIN));\n }\n\n /**\n * Toogle the button text with the data-alt value.\n *\n * @param {Element} element the button element\n */\n _toggleButtonText(element) {\n [element.innerHTML, element.dataset.alt] = [element.dataset.alt, element.innerHTML];\n }\n\n}\n"],"file":"debugpanel.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/reactive/debugpanel.js"],"names":["init","target","selectors","element","document","getElementById","debug","remove","GlobalDebugPanel","reactive","initsubpanel","DebugInstanceSubpanel","name","LOADERS","SUBPANEL","LOG","state","reactives","size","getElement","innerHTML","forEach","instance","_createLoader","loaders","btn","createElement","id","dataset","appendChild","addEventListener","_openPanel","data","renderComponent","log","error","BaseComponent","NAME","CLOSE","READMODE","HIGHLIGHT","STATE","CLEAN","PIN","SAVE","INVALID","controller","M","draggable","relativeDrag","strings","savewarning","dragdrop","DragDrop","highlight","_toggleButtonText","_toggleEditMode","_cleanAreas","_togglePin","disabled","_checkJSON","_saveState","_refreshState","unregister","watch","handler","_refreshLog","_refreshReadOnly","list","lastChanges","logContent","join","value","scrollTop","scrollHeight","JSON","stringify","readonly","readOnly","alt","invalid","save","edited","currentStateData","stateData","style","color","newState","parse","result","_generateStateUpdates","message","updates","processUpdates","newStateData","ids","key","newValue","Array","isArray","Error","push","action","fields","index","valueOf","Object","entries","oldValue","deleteField","deleteEntry","dropdata","event","top","newFixedTop","left","newFixedLeft","setDraggable","_unpin","_pin","pageCenterY","window","innerHeight","pageCenterX","innerWidth","position","resize","overflow","height","width","assign","prop","removeProperty"],"mappings":"0MA4BA,uD,ymHASoB,QAAPA,CAAAA,IAAO,CAACC,CAAD,CAASC,CAAT,CAAuB,CACvC,GAAMC,CAAAA,CAAO,CAAGC,QAAQ,CAACC,cAAT,CAAwBJ,CAAxB,CAAhB,CAEA,GAAIK,gBAAJ,CAAyB,CACrBH,CAAO,CAACI,MAAR,GACA,MACH,CAED,GAAIC,CAAAA,CAAJ,CAAqB,CACjBL,OAAO,CAAPA,CADiB,CAEjBM,QAAQ,CAAEH,OAFO,CAGjBJ,SAAS,CAATA,CAHiB,CAArB,CAKH,C,gBAQ2B,QAAfQ,CAAAA,YAAe,CAACT,CAAD,CAASC,CAAT,CAAuB,CAC/C,GAAMC,CAAAA,CAAO,CAAGC,QAAQ,CAACC,cAA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AO,CAACiB,SAA9B,CADpB,CACtBjB,CAAO,CAACiB,SADc,MACHjB,CAAO,CAACyB,OAAR,CAAgBmD,GADb,KAE1B,C,cAxZ+B3C,e","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Reactive module debug panel.\n *\n * This module contains all the UI components for the reactive debug tools.\n * Those tools are only available if the debug is enables and could be used\n * from the footer.\n *\n * @module core/local/reactive/debugpanel\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {BaseComponent, DragDrop, debug} from 'core/reactive';\nimport log from 'core/log';\nimport {debounce} from 'core/utils';\n\n/**\n * Init the main reactive panel.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n */\nexport const init = (target, selectors) => {\n const element = document.getElementById(target);\n // Check if the debug reactive module is available.\n if (debug === undefined) {\n element.remove();\n return;\n }\n // Create the main component.\n new GlobalDebugPanel({\n element,\n reactive: debug,\n selectors,\n });\n};\n\n/**\n * Init an instance reactive subpanel.\n *\n * @param {element|string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n */\nexport const initsubpanel = (target, selectors) => {\n const element = document.getElementById(target);\n // Check if the debug reactive module is available.\n if (debug === undefined) {\n element.remove();\n return;\n }\n // Create the main component.\n new DebugInstanceSubpanel({\n element,\n reactive: debug,\n selectors,\n });\n};\n\n/**\n * Component for the main reactive dev panel.\n *\n * This component shows the list of reactive instances and handle the buttons\n * to open a specific instance panel.\n */\nclass GlobalDebugPanel extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'GlobalDebugPanel';\n // Default query selectors.\n this.selectors = {\n LOADERS: `[data-for='loaders']`,\n SUBPANEL: `[data-for='subpanel']`,\n LOG: `[data-for='log']`,\n };\n }\n\n /**\n * Initial state ready method.\n *\n * @param {object} state the initial state\n */\n stateReady(state) {\n if (state.reactives.size > 0) {\n this.getElement(this.selectors.LOADERS).innerHTML = '';\n }\n // Generate loading buttons.\n state.reactives.forEach(\n instance => {\n this._createLoader(instance);\n }\n );\n // Remove loading wheel.\n this.getElement(this.selectors.SUBPANEL).innerHTML = '';\n }\n\n /**\n * Create a debug panel button for a specific reactive instance.\n *\n * @param {object} instance hte instance data\n */\n _createLoader(instance) {\n const loaders = this.getElement(this.selectors.LOADERS);\n const btn = document.createElement(\"button\");\n btn.innerHTML = instance.id;\n btn.dataset.id = instance.id;\n loaders.appendChild(btn);\n // Add click event.\n this.addEventListener(btn, 'click', () => this._openPanel(btn, instance));\n }\n\n /**\n * Open a debug panel.\n *\n * @param {Element} btn the button element\n * @param {object} instance the instance data\n */\n async _openPanel(btn, instance) {\n try {\n const target = this.getElement(this.selectors.SUBPANEL);\n const data = {...instance};\n await this.renderComponent(target, 'core/local/reactive/debuginstancepanel', data);\n } catch (error) {\n log.error('Cannot load reactive debug subpanel');\n throw error;\n }\n }\n}\n\n/**\n * Component for the main reactive dev panel.\n *\n * This component shows the list of reactive instances and handle the buttons\n * to open a specific instance panel.\n */\nclass DebugInstanceSubpanel extends BaseComponent {\n\n /**\n * Constructor hook.\n */\n create() {\n // Optional component name for debugging.\n this.name = 'DebugInstanceSubpanel';\n // Default query selectors.\n this.selectors = {\n NAME: `[data-for='name']`,\n CLOSE: `[data-for='close']`,\n READMODE: `[data-for='readmode']`,\n HIGHLIGHT: `[data-for='highlight']`,\n LOG: `[data-for='log']`,\n STATE: `[data-for='state']`,\n CLEAN: `[data-for='clean']`,\n PIN: `[data-for='pin']`,\n SAVE: `[data-for='save']`,\n INVALID: `[data-for='invalid']`,\n };\n this.id = this.element.dataset.id;\n this.controller = M.reactive[this.id];\n\n // The component is created always pinned.\n this.draggable = false;\n // We want the element to be dragged like modal.\n this.relativeDrag = true;\n // Save warning (will be loaded when state is ready.\n this.strings = {\n savewarning: '',\n };\n }\n\n /**\n * Initial state ready method.\n *\n */\n stateReady() {\n // Enable drag and drop.\n this.dragdrop = new DragDrop(this);\n\n // Close button.\n this.addEventListener(\n this.getElement(this.selectors.CLOSE),\n 'click',\n this.remove\n );\n // Highlight button.\n if (this.controller.highlight) {\n this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT));\n }\n this.addEventListener(\n this.getElement(this.selectors.HIGHLIGHT),\n 'click',\n () => {\n this.controller.highlight = !this.controller.highlight;\n this._toggleButtonText(this.getElement(this.selectors.HIGHLIGHT));\n }\n );\n // Edit mode button.\n this.addEventListener(\n this.getElement(this.selectors.READMODE),\n 'click',\n this._toggleEditMode\n );\n // Clean log and state.\n this.addEventListener(\n this.getElement(this.selectors.CLEAN),\n 'click',\n this._cleanAreas\n );\n // Unpin panel butotn.\n this.addEventListener(\n this.getElement(this.selectors.PIN),\n 'click',\n this._togglePin\n );\n // Save button, state format error message and state textarea.\n this.getElement(this.selectors.SAVE).disabled = true;\n\n this.addEventListener(\n this.getElement(this.selectors.STATE),\n 'keyup',\n debounce(this._checkJSON, 500)\n );\n\n this.addEventListener(\n this.getElement(this.selectors.SAVE),\n 'click',\n this._saveState\n );\n // Save the default save warning message.\n this.strings.savewarning = this.getElement(this.selectors.INVALID)?.innerHTML ?? '';\n // Add current state.\n this._refreshState();\n }\n\n /**\n * Remove all subcomponents dependencies.\n */\n destroy() {\n if (this.dragdrop !== undefined) {\n this.dragdrop.unregister();\n }\n }\n\n /**\n * Component watchers.\n *\n * @returns {Array} of watchers\n */\n getWatchers() {\n return [\n {watch: `reactives[${this.id}].lastChanges:updated`, handler: this._refreshLog},\n {watch: `reactives[${this.id}].modified:updated`, handler: this._refreshState},\n {watch: `reactives[${this.id}].readOnly:updated`, handler: this._refreshReadOnly},\n ];\n }\n\n /**\n * Wtacher method to refresh the log panel.\n *\n * @param {object} args\n * @param {HTMLElement} args.element\n */\n _refreshLog({element}) {\n const list = element?.lastChanges ?? [];\n\n const logContent = list.join(\"\\n\");\n // Append last log.\n const target = this.getElement(this.selectors.LOG);\n target.value += `\\n\\n= Transaction =\\n ${logContent}`;\n target.scrollTop = target.scrollHeight;\n }\n\n /**\n * Listener method to clean the log area.\n */\n _cleanAreas() {\n let target = this.getElement(this.selectors.LOG);\n target.value = '';\n\n this._refreshState();\n }\n\n /**\n * Watcher to refresh the state information.\n */\n _refreshState() {\n const target = this.getElement(this.selectors.STATE);\n target.value = JSON.stringify(this.controller.state, null, 4);\n }\n\n /**\n * Watcher to update the read only information.\n */\n _refreshReadOnly() {\n // Toggle the read mode button.\n const target = this.getElement(this.selectors.READMODE);\n if (target.dataset.readonly === undefined) {\n target.dataset.readonly = target.innerHTML;\n }\n if (this.controller.readOnly) {\n target.innerHTML = target.dataset.readonly;\n } else {\n target.innerHTML = target.dataset.alt;\n }\n }\n\n /**\n * Listener to toggle the edit mode of the component.\n */\n _toggleEditMode() {\n this.controller.readOnly = !this.controller.readOnly;\n }\n\n /**\n * Check that the edited state JSON is valid.\n *\n * Not all valid JSON are suitable for transforming the state. For example,\n * the first level attributes cannot change the type.\n *\n * @return {undefined|array} Array of state updates.\n */\n _checkJSON() {\n const invalid = this.getElement(this.selectors.INVALID);\n const save = this.getElement(this.selectors.SAVE);\n\n const edited = this.getElement(this.selectors.STATE).value;\n\n const currentStateData = this.controller.stateData;\n\n // Check if the json is tha same as state.\n if (edited == JSON.stringify(this.controller.state, null, 4)) {\n invalid.style.color = '';\n invalid.innerHTML = '';\n save.disabled = true;\n return undefined;\n }\n\n // Check if the json format is valid.\n try {\n const newState = JSON.parse(edited);\n // Check the first level did not change types.\n const result = this._generateStateUpdates(currentStateData, newState);\n // Enable save button.\n invalid.style.color = '';\n invalid.innerHTML = this.strings.savewarning;\n save.disabled = false;\n return result;\n } catch (error) {\n invalid.style.color = 'red';\n invalid.innerHTML = error.message ?? 'Invalid JSON sctructure';\n save.disabled = true;\n return undefined;\n }\n }\n\n /**\n * Listener to save the current edited state into the real state.\n */\n _saveState() {\n const updates = this._checkJSON();\n if (!updates) {\n return;\n }\n // Sent the updates to the state manager.\n this.controller.processUpdates(updates);\n }\n\n /**\n * Check that the edited state JSON is valid.\n *\n * Not all valid JSON are suitable for transforming the state. For example,\n * the first level attributes cannot change the type. This method do a two\n * steps comparison between the current state data and the new state data.\n *\n * A reactive state cannot be overridden like any other variable. To keep\n * the watchers updated is necessary to transform the current state into\n * the new one. As a result, this method generates all the necessary state\n * updates to convert the state into the new state.\n *\n * @param {object} currentStateData\n * @param {object} newStateData\n * @return {array} Array of state updates.\n * @throws {Error} is the structure is not compatible\n */\n _generateStateUpdates(currentStateData, newStateData) {\n\n const updates = [];\n\n const ids = {};\n\n // Step 1: Add all overrides newStateData.\n for (const [key, newValue] of Object.entries(newStateData)) {\n // Check is it is new.\n if (Array.isArray(newValue)) {\n ids[key] = {};\n newValue.forEach(element => {\n if (element.id === undefined) {\n throw Error(`Array ${key} element without id attribute`);\n }\n updates.push({\n name: key,\n action: 'override',\n fields: element,\n });\n const index = String(element.id).valueOf();\n ids[key][index] = true;\n });\n } else {\n updates.push({\n name: key,\n action: 'override',\n fields: newValue,\n });\n }\n }\n // Step 2: delete unnecesary data from currentStateData.\n for (const [key, oldValue] of Object.entries(currentStateData)) {\n let deleteField = false;\n // Check if the attribute is still there.\n if (newStateData[key] === undefined) {\n deleteField = true;\n }\n if (Array.isArray(oldValue)) {\n if (!deleteField && ids[key] === undefined) {\n throw Error(`Array ${key} cannot change to object.`);\n }\n oldValue.forEach(element => {\n const index = String(element.id).valueOf();\n let deleteEntry = deleteField;\n // Check if the id is there.\n if (!deleteEntry && ids[key][index] === undefined) {\n deleteEntry = true;\n }\n if (deleteEntry) {\n updates.push({\n name: key,\n action: 'delete',\n fields: element,\n });\n }\n });\n } else {\n if (!deleteField && ids[key] !== undefined) {\n throw Error(`Object ${key} cannot change to array.`);\n }\n if (deleteField) {\n updates.push({\n name: key,\n action: 'delete',\n fields: oldValue,\n });\n }\n }\n }\n // Delete all elements without action.\n return updates;\n }\n\n // Drag and drop methods.\n\n /**\n * Get the draggable data of this component.\n *\n * @returns {Object} exported course module drop data\n */\n getDraggableData() {\n return this.draggable;\n }\n\n /**\n * The element drop end hook.\n *\n * @param {Object} dropdata the dropdata\n * @param {Event} event the dropdata\n */\n dragEnd(dropdata, event) {\n this.element.style.top = `${event.newFixedTop}px`;\n this.element.style.left = `${event.newFixedLeft}px`;\n }\n\n /**\n * Pin and unpin the panel.\n */\n _togglePin() {\n this.draggable = !this.draggable;\n this.dragdrop.setDraggable(this.draggable);\n if (this.draggable) {\n this._unpin();\n } else {\n this._pin();\n }\n }\n\n /**\n * Unpin the panel form the footer.\n */\n _unpin() {\n // Find the initial spot.\n const pageCenterY = window.innerHeight / 2;\n const pageCenterX = window.innerWidth / 2;\n // Put the element in the middle of the screen\n const style = {\n position: 'fixed',\n resize: 'both',\n overflow: 'auto',\n height: '400px',\n width: '400px',\n top: `${pageCenterY - 200}px`,\n left: `${pageCenterX - 200}px`,\n };\n Object.assign(this.element.style, style);\n // Small also the text areas.\n this.getElement(this.selectors.STATE).style.height = '50px';\n this.getElement(this.selectors.LOG).style.height = '50px';\n\n this._toggleButtonText(this.getElement(this.selectors.PIN));\n }\n\n /**\n * Pin the panel into the footer.\n */\n _pin() {\n const props = [\n 'position',\n 'resize',\n 'overflow',\n 'top',\n 'left',\n 'height',\n 'width',\n ];\n props.forEach(\n prop => this.element.style.removeProperty(prop)\n );\n this._toggleButtonText(this.getElement(this.selectors.PIN));\n }\n\n /**\n * Toogle the button text with the data-alt value.\n *\n * @param {Element} element the button element\n */\n _toggleButtonText(element) {\n [element.innerHTML, element.dataset.alt] = [element.dataset.alt, element.innerHTML];\n }\n\n}\n"],"file":"debugpanel.min.js"} \ No newline at end of file diff --git a/lib/amd/build/local/reactive/reactive.min.js.map b/lib/amd/build/local/reactive/reactive.min.js.map index ae35109812923..0485762170753 100644 --- a/lib/amd/build/local/reactive/reactive.min.js.map +++ b/lib/amd/build/local/reactive/reactive.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/reactive/reactive.js"],"names":["pendingCount","description","eventName","eventDispatch","Error","name","target","document","createTextNode","stateManager","StateManager","watchers","Map","components","Set","mutations","addEventListener","callWatchersHandler","bind","pendingState","Pending","state","setInitialState","M","reactive","registerNewInstance","event","dispatchEvent","CustomEvent","detail","action","bubbles","stateData","resolve","newFunctions","init","Object","entries","mutation","mutationFunction","manager","id","get","getInitialPromise","component","componentName","dispatchSuccess","dispatchFail","dispatchRegistrationSuccess","dispatchRegistrationFail","has","pendingPromise","listeners","handlers","getWatchers","forEach","watch","handler","listener","apply","push","stateReady","getInitialStatePromise","then","catch","reason","log","error","set","add","delete","removeEventListener","actionName","charAt","params","setReadOnly"],"mappings":"iNAwBA,OACA,OACA,O,kpDAGIA,CAAAA,CAAY,CAAG,C,cA2Cf,WAAYC,CAAZ,CAAyB,mBAErB,GAAIA,CAAW,CAACC,SAAZ,WAAuCD,CAAW,CAACE,aAAZ,SAA3C,CAAoF,CAChF,KAAM,IAAIC,CAAAA,KAAJ,6BACT,CAED,GAAIH,CAAW,CAACI,IAAZ,SAAJ,CAAoC,CAChC,KAAKA,IAAL,CAAYJ,CAAW,CAACI,IAC3B,CAMD,KAAKC,MAAL,WAAcL,CAAW,CAACK,MAA1B,gBAAoCC,QAAQ,CAACC,cAAT,CAAwB,IAAxB,CAApC,CAEA,KAAKN,SAAL,CAAiBD,CAAW,CAACC,SAA7B,CACA,KAAKC,aAAL,CAAqBF,CAAW,CAACE,aAAjC,CAGA,KAAKM,YAAL,CAAoB,GAAIC,UAAJ,CAAiB,KAAKP,aAAtB,CAAqC,KAAKG,MAA1C,CAApB,CAGA,KAAKK,QAAL,CAAgB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,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A generic single state reactive module.\n *\n * @module core/reactive/local/reactive/reactive\n * @class core/reactive/local/reactive/reactive\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport log from 'core/log';\nimport StateManager from 'core/local/reactive/statemanager';\nimport Pending from 'core/pending';\n\n// Count the number of pending operations done to ensure we have a unique id for each one.\nlet pendingCount = 0;\n\n/**\n * Set up general reactive class to create a single state application with components.\n *\n * The reactive class is used for registering new UI components and manage the access to the state values\n * and mutations.\n *\n * When a new reactive instance is created, it will contain an empty state and and empty mutations\n * lists. When the state data is ready, the initial state can be loaded using the \"setInitialState\"\n * method. This will protect the state from writing and will trigger all the components \"stateReady\"\n * methods.\n *\n * State can only be altered by mutations. To replace all the mutations with a specific class,\n * use \"setMutations\" method. If you need to just add some new mutation methods, use \"addMutations\".\n *\n * To register new components into a reactive instance, use \"registerComponent\".\n *\n * Inside a component, use \"dispatch\" to invoke a mutation on the state (components can only access\n * the state in read only mode).\n */\nexport default class {\n\n /**\n * The component descriptor data structure.\n *\n * @typedef {object} description\n * @property {string} eventName the custom event name used for state changed events\n * @property {Function} eventDispatch the state update event dispatch function\n * @property {Element} [target] the target of the event dispatch. If not passed a fake element will be created\n * @property {Object} [mutations] an object with state mutations functions\n * @property {Object} [state] an object to initialize the state.\n */\n\n /**\n * Create a basic reactive manager.\n *\n * Note that if your state is not async loaded, you can pass directly on creation by using the\n * description.state attribute. However, this will initialize the state, this means\n * setInitialState will throw an exception because the state is already defined.\n *\n * @param {description} description reactive manager description.\n */\n constructor(description) {\n\n if (description.eventName === undefined || description.eventDispatch === undefined) {\n throw new Error(`Reactivity event required`);\n }\n\n if (description.name !== undefined) {\n this.name = description.name;\n }\n\n // Each reactive instance has its own element anchor to propagate state changes internally.\n // By default the module will create a fake DOM element to target custom events but\n // if all reactive components is constrait to a single element, this can be passed as\n // target in the description.\n this.target = description.target ?? document.createTextNode(null);\n\n this.eventName = description.eventName;\n this.eventDispatch = description.eventDispatch;\n\n // State manager is responsible for dispatch state change events when a mutation happens.\n this.stateManager = new StateManager(this.eventDispatch, this.target);\n\n // An internal registry of watchers and components.\n this.watchers = new Map([]);\n this.components = new Set([]);\n\n // Mutations can be overridden later using setMutations method.\n this.mutations = description.mutations ?? {};\n\n // Register the event to alert watchers when specific state change happens.\n this.target.addEventListener(this.eventName, this.callWatchersHandler.bind(this));\n\n // Add a pending operation waiting for the initial state.\n this.pendingState = new Pending(`core/reactive:registerInstance${pendingCount++}`);\n\n // Set initial state if we already have it.\n if (description.state !== undefined) {\n this.setInitialState(description.state);\n }\n\n // Check if we have a debug instance to register the instance.\n if (M.reactive !== undefined) {\n M.reactive.registerNewInstance(this);\n }\n }\n\n /**\n * State changed listener.\n *\n * This function take any state change and send it to the proper watchers.\n *\n * To prevent internal state changes from colliding with other reactive instances, only the\n * general \"state changed\" is triggered at document level. All the internal changes are\n * triggered at private target level without bubbling. This way any reactive instance can alert\n * only its own watchers.\n *\n * @param {CustomEvent} event\n */\n callWatchersHandler(event) {\n // Execute any registered component watchers.\n this.target.dispatchEvent(new CustomEvent(event.detail.action, {\n bubbles: false,\n detail: event.detail,\n }));\n }\n\n /**\n * Set the initial state.\n *\n * @param {object} stateData the initial state data.\n */\n setInitialState(stateData) {\n this.pendingState.resolve();\n this.stateManager.setInitialState(stateData);\n }\n\n /**\n * Add individual functions to the mutations.\n *\n * Note new mutations will be added to the existing ones. To replace the full mutation\n * object with a new one, use setMutations method.\n *\n * @method addMutations\n * @param {Object} newFunctions an object with new mutation functions.\n */\n addMutations(newFunctions) {\n // Mutations can provide an init method to do some setup in the statemanager.\n if (newFunctions.init !== undefined) {\n newFunctions.init(this.stateManager);\n }\n // Save all mutations.\n for (const [mutation, mutationFunction] of Object.entries(newFunctions)) {\n this.mutations[mutation] = mutationFunction.bind(newFunctions);\n }\n }\n\n /**\n * Replace the current mutations with a new object.\n *\n * This method is designed to override the full mutations class, for example by extending\n * the original one. To add some individual mutations, use addMutations instead.\n *\n * @param {object} manager the new mutations intance\n */\n setMutations(manager) {\n this.mutations = manager;\n // Mutations can provide an init method to do some setup in the statemanager.\n if (manager.init !== undefined) {\n manager.init(this.stateManager);\n }\n }\n\n /**\n * Return the current state.\n *\n * @return {object}\n */\n get state() {\n return this.stateManager.state;\n }\n\n /**\n * Get state data.\n *\n * Components access the state frequently. This convenience method is a shortcut to\n * this.reactive.state.stateManager.get() method.\n *\n * @param {String} name the state object name\n * @param {*} id an optional object id for state maps.\n * @return {Object|undefined} the state object found\n */\n get(name, id) {\n return this.stateManager.get(name, id);\n }\n\n /**\n * Return the initial state promise.\n *\n * Typically, components do not require to use this promise because registerComponent\n * will trigger their stateReady method automatically. But it could be useful for complex\n * components that require to combine state, template and string loadings.\n *\n * @method getState\n * @return {Promise}\n */\n getInitialStatePromise() {\n return this.stateManager.getInitialPromise();\n }\n\n /**\n * Register a new component.\n *\n * Component can provide some optional functions to the reactive module:\n * - getWatchers: returns an array of watchers\n * - stateReady: a method to call when the initial state is loaded\n *\n * It can also provide some optional attributes:\n * - name: the component name (default value: \"Unkown component\") to customize debug messages.\n *\n * The method will also use dispatchRegistrationSuccess and dispatchRegistrationFail. Those\n * are BaseComponent methods to inform parent components of the registration status.\n * Components should not override those methods.\n *\n * @method registerComponent\n * @param {object} component the new component\n * @property {string} [component.name] the component name to display in warnings and errors.\n * @property {Function} [component.dispatchRegistrationSuccess] method to notify registration success\n * @property {Function} [component.dispatchRegistrationFail] method to notify registration fail\n * @property {Function} [component.getWatchers] getter of the component watchers\n * @property {Function} [component.stateReady] method to call when the state is ready\n * @return {object} the registered component\n */\n registerComponent(component) {\n\n // Component name is an optional attribute to customize debug messages.\n const componentName = component.name ?? 'Unkown component';\n\n // Components can provide special methods to communicate registration to parent components.\n let dispatchSuccess = () => {\n return;\n };\n let dispatchFail = dispatchSuccess;\n if (component.dispatchRegistrationSuccess !== undefined) {\n dispatchSuccess = component.dispatchRegistrationSuccess.bind(component);\n }\n if (component.dispatchRegistrationFail !== undefined) {\n dispatchFail = component.dispatchRegistrationFail.bind(component);\n }\n\n // Components can be registered only one time.\n if (this.components.has(component)) {\n dispatchSuccess();\n return component;\n }\n\n // Components are fully registered only when the state ready promise is resolved.\n const pendingPromise = new Pending(`core/reactive:registerComponent${pendingCount++}`);\n\n // Keep track of the event listeners.\n let listeners = [];\n\n // Register watchers.\n let handlers = [];\n if (component.getWatchers !== undefined) {\n handlers = component.getWatchers();\n }\n handlers.forEach(({watch, handler}) => {\n\n if (watch === undefined) {\n dispatchFail();\n throw new Error(`Missing watch attribute in ${componentName} watcher`);\n }\n if (handler === undefined) {\n dispatchFail();\n throw new Error(`Missing handler for watcher ${watch} in ${componentName}`);\n }\n\n const listener = (event) => {\n handler.apply(component, [event.detail]);\n };\n\n // Save the listener information in case the component must be unregistered later.\n listeners.push({target: this.target, watch, listener});\n\n // The state manager triggers a general \"state changed\" event at a document level. However,\n // for the internal watchers, each component can listen to specific state changed custom events\n // in the target element. This way we can use the native event loop without colliding with other\n // reactive instances.\n this.target.addEventListener(watch, listener);\n });\n\n // Register state ready function. There's the possibility a component is registered after the initial state\n // is loaded. For those cases we have a state promise to handle this specific state change.\n if (component.stateReady !== undefined) {\n this.getInitialStatePromise()\n .then(state => {\n component.stateReady(state);\n pendingPromise.resolve();\n return true;\n })\n .catch(reason => {\n pendingPromise.resolve();\n log.error(`Initial state in ${componentName} rejected due to: ${reason}`);\n log.error(reason);\n });\n }\n\n // Save unregister data.\n this.watchers.set(component, listeners);\n this.components.add(component);\n\n // Dispatch an event to communicate the registration to the debug module.\n this.target.dispatchEvent(new CustomEvent('registerComponent:success', {\n bubbles: false,\n detail: {component},\n }));\n\n dispatchSuccess();\n return component;\n }\n\n /**\n * Unregister a component and its watchers.\n *\n * @param {object} component the object instance to unregister\n * @returns {object} the deleted component\n */\n unregisterComponent(component) {\n if (!this.components.has(component)) {\n return component;\n }\n\n this.components.delete(component);\n\n // Remove event listeners.\n const listeners = this.watchers.get(component);\n if (listeners === undefined) {\n return component;\n }\n\n listeners.forEach(({target, watch, listener}) => {\n target.removeEventListener(watch, listener);\n });\n\n this.watchers.delete(component);\n\n return component;\n }\n\n /**\n * Dispatch a change in the state.\n *\n * This method is the only way for components to alter the state. Watchers will receive a\n * read only state to prevent illegal changes. If some user action require a state change, the\n * component should dispatch a mutation to trigger all the necessary logic to alter the state.\n *\n * @method dispatch\n * @param {string} actionName the action name (usually the mutation name)\n * @param {*} param any number of params the mutation needs.\n */\n async dispatch(actionName, ...params) {\n if (typeof actionName !== 'string') {\n throw new Error(`Dispatch action name must be a string`);\n }\n // JS does not have private methods yet. However, we prevent any component from calling\n // a method starting with \"_\" because the most accepted convention for private methods.\n if (actionName.charAt(0) === '_') {\n throw new Error(`Illegal Private ${actionName} mutation method dispatch`);\n }\n if (this.mutations[actionName] === undefined) {\n throw new Error(`Unkown ${actionName} mutation`);\n }\n\n const pendingPromise = new Pending(`core/reactive:${actionName}${pendingCount++}`);\n\n const mutationFunction = this.mutations[actionName];\n try {\n await mutationFunction.apply(this.mutations, [this.stateManager, ...params]);\n pendingPromise.resolve();\n } catch (error) {\n // Ensure the state is locked.\n this.stateManager.setReadOnly(true);\n pendingPromise.resolve();\n throw error;\n }\n }\n}\n"],"file":"reactive.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/reactive/reactive.js"],"names":["pendingCount","description","eventName","eventDispatch","Error","name","target","document","createTextNode","stateManager","StateManager","watchers","Map","components","Set","mutations","addEventListener","callWatchersHandler","bind","pendingState","Pending","state","setInitialState","M","reactive","registerNewInstance","event","dispatchEvent","CustomEvent","detail","action","bubbles","stateData","resolve","newFunctions","init","Object","entries","mutation","mutationFunction","manager","id","get","getInitialPromise","component","componentName","dispatchSuccess","dispatchFail","dispatchRegistrationSuccess","dispatchRegistrationFail","has","pendingPromise","listeners","handlers","getWatchers","forEach","watch","handler","listener","apply","push","stateReady","getInitialStatePromise","then","catch","reason","log","error","set","add","delete","removeEventListener","actionName","charAt","params","setReadOnly"],"mappings":"iNAwBA,OACA,OACA,O,kpDAGIA,CAAAA,CAAY,CAAG,C,cA2Cf,WAAYC,CAAZ,CAAyB,mBAErB,GAAIA,CAAW,CAACC,SAAZ,WAAuCD,CAAW,CAACE,aAAZ,SAA3C,CAAoF,CAChF,KAAM,IAAIC,CAAAA,KAAJ,6BACT,CAED,GAAIH,CAAW,CAACI,IAAZ,SAAJ,CAAoC,CAChC,KAAKA,IAAL,CAAYJ,CAAW,CAACI,IAC3B,CAMD,KAAKC,MAAL,WAAcL,CAAW,CAACK,MAA1B,gBAAoCC,QAAQ,CAACC,cAAT,CAAwB,IAAxB,CAApC,CAEA,KAAKN,SAAL,CAAiBD,CAAW,CAACC,SAA7B,CACA,KAAKC,aAAL,CAAqBF,CAAW,CAACE,aAAjC,CAGA,KAAKM,YAAL,CAAoB,GAAIC,UAAJ,CAAiB,KAAKP,aAAtB,CAAqC,KAAKG,MAA1C,CAApB,CAGA,KAAKK,QAAL,CAAgB,GAAIC,CAAAA,GAAJ,CAAQ,EAAR,CAAhB,CACA,KAAKC,UAAL,CAAkB,GAAIC,CAAAA,GAAJ,CAAQ,EAAR,CAAlB,CAGA,KAAKC,SAAL,WAAiBd,CAAW,CAACc,SAA7B,gBAA0C,EAA1C,CAGA,KAAKT,MAAL,CAAYU,gBAAZ,CAA6B,KAAKd,SAAlC,CAA6C,KAAKe,mBAAL,CAAyBC,IAAzB,CAA8B,IAA9B,CAA7C,EAGA,KAAKC,YAAL,CAAoB,GAAIC,UA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BjD,CAAAA,CAA6B,GAA7BA,MAA6B,CAArBkD,CAAqB,GAArBA,KAAqB,CAAdE,CAAc,GAAdA,QAAc,CAC7CpD,CAAM,CAACiE,mBAAP,CAA2Bf,CAA3B,CAAkCE,CAAlC,CACH,CAFD,EAIA,KAAK/C,QAAL,CAAc2D,MAAd,CAAqB1B,CAArB,EAEA,MAAOA,CAAAA,CACV,C,8EAac4B,C,kHACe,QAAtB,QAAOA,CAAAA,C,uBACD,IAAIpE,CAAAA,KAAJ,yC,aAImB,GAAzB,GAAAoE,CAAU,CAACC,MAAX,CAAkB,CAAlB,C,uBACM,IAAIrE,CAAAA,KAAJ,2BAA6BoE,CAA7B,8B,aAEN,KAAKzD,SAAL,CAAeyD,CAAf,U,uBACM,IAAIpE,CAAAA,KAAJ,kBAAoBoE,CAApB,c,QAGJrB,C,CAAiB,GAAI/B,UAAJ,yBAA6BoD,CAA7B,SAA0CxE,CAAY,EAAtD,E,CAEjBuC,C,CAAmB,KAAKxB,SAAL,CAAeyD,CAAf,C,yBAfCE,C,+BAAAA,C,2BAiBhBnC,CAAAA,CAAgB,CAACoB,KAAjB,CAAuB,KAAK5C,SAA5B,EAAwC,KAAKN,YAA7C,SAA8DiE,CAA9D,E,SACNvB,CAAc,CAAClB,OAAf,G,qDAGA,KAAKxB,YAAL,CAAkBkE,WAAlB,KACAxB,CAAc,CAAClB,OAAf,G,mKA7MI,CACR,MAAO,MAAKxB,YAAL,CAAkBY,KAC5B,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A generic single state reactive module.\n *\n * @module core/reactive/local/reactive/reactive\n * @class core/reactive/local/reactive/reactive\n * @copyright 2021 Ferran Recio \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport log from 'core/log';\nimport StateManager from 'core/local/reactive/statemanager';\nimport Pending from 'core/pending';\n\n// Count the number of pending operations done to ensure we have a unique id for each one.\nlet pendingCount = 0;\n\n/**\n * Set up general reactive class to create a single state application with components.\n *\n * The reactive class is used for registering new UI components and manage the access to the state values\n * and mutations.\n *\n * When a new reactive instance is created, it will contain an empty state and and empty mutations\n * lists. When the state data is ready, the initial state can be loaded using the \"setInitialState\"\n * method. This will protect the state from writing and will trigger all the components \"stateReady\"\n * methods.\n *\n * State can only be altered by mutations. To replace all the mutations with a specific class,\n * use \"setMutations\" method. If you need to just add some new mutation methods, use \"addMutations\".\n *\n * To register new components into a reactive instance, use \"registerComponent\".\n *\n * Inside a component, use \"dispatch\" to invoke a mutation on the state (components can only access\n * the state in read only mode).\n */\nexport default class {\n\n /**\n * The component descriptor data structure.\n *\n * @typedef {object} description\n * @property {string} eventName the custom event name used for state changed events\n * @property {Function} eventDispatch the state update event dispatch function\n * @property {Element} [target] the target of the event dispatch. If not passed a fake element will be created\n * @property {Object} [mutations] an object with state mutations functions\n * @property {Object} [state] an object to initialize the state.\n */\n\n /**\n * Create a basic reactive manager.\n *\n * Note that if your state is not async loaded, you can pass directly on creation by using the\n * description.state attribute. However, this will initialize the state, this means\n * setInitialState will throw an exception because the state is already defined.\n *\n * @param {description} description reactive manager description.\n */\n constructor(description) {\n\n if (description.eventName === undefined || description.eventDispatch === undefined) {\n throw new Error(`Reactivity event required`);\n }\n\n if (description.name !== undefined) {\n this.name = description.name;\n }\n\n // Each reactive instance has its own element anchor to propagate state changes internally.\n // By default the module will create a fake DOM element to target custom events but\n // if all reactive components is constrait to a single element, this can be passed as\n // target in the description.\n this.target = description.target ?? document.createTextNode(null);\n\n this.eventName = description.eventName;\n this.eventDispatch = description.eventDispatch;\n\n // State manager is responsible for dispatch state change events when a mutation happens.\n this.stateManager = new StateManager(this.eventDispatch, this.target);\n\n // An internal registry of watchers and components.\n this.watchers = new Map([]);\n this.components = new Set([]);\n\n // Mutations can be overridden later using setMutations method.\n this.mutations = description.mutations ?? {};\n\n // Register the event to alert watchers when specific state change happens.\n this.target.addEventListener(this.eventName, this.callWatchersHandler.bind(this));\n\n // Add a pending operation waiting for the initial state.\n this.pendingState = new Pending(`core/reactive:registerInstance${pendingCount++}`);\n\n // Set initial state if we already have it.\n if (description.state !== undefined) {\n this.setInitialState(description.state);\n }\n\n // Check if we have a debug instance to register the instance.\n if (M.reactive !== undefined) {\n M.reactive.registerNewInstance(this);\n }\n }\n\n /**\n * State changed listener.\n *\n * This function take any state change and send it to the proper watchers.\n *\n * To prevent internal state changes from colliding with other reactive instances, only the\n * general \"state changed\" is triggered at document level. All the internal changes are\n * triggered at private target level without bubbling. This way any reactive instance can alert\n * only its own watchers.\n *\n * @param {CustomEvent} event\n */\n callWatchersHandler(event) {\n // Execute any registered component watchers.\n this.target.dispatchEvent(new CustomEvent(event.detail.action, {\n bubbles: false,\n detail: event.detail,\n }));\n }\n\n /**\n * Set the initial state.\n *\n * @param {object} stateData the initial state data.\n */\n setInitialState(stateData) {\n this.pendingState.resolve();\n this.stateManager.setInitialState(stateData);\n }\n\n /**\n * Add individual functions to the mutations.\n *\n * Note new mutations will be added to the existing ones. To replace the full mutation\n * object with a new one, use setMutations method.\n *\n * @method addMutations\n * @param {Object} newFunctions an object with new mutation functions.\n */\n addMutations(newFunctions) {\n // Mutations can provide an init method to do some setup in the statemanager.\n if (newFunctions.init !== undefined) {\n newFunctions.init(this.stateManager);\n }\n // Save all mutations.\n for (const [mutation, mutationFunction] of Object.entries(newFunctions)) {\n this.mutations[mutation] = mutationFunction.bind(newFunctions);\n }\n }\n\n /**\n * Replace the current mutations with a new object.\n *\n * This method is designed to override the full mutations class, for example by extending\n * the original one. To add some individual mutations, use addMutations instead.\n *\n * @param {object} manager the new mutations intance\n */\n setMutations(manager) {\n this.mutations = manager;\n // Mutations can provide an init method to do some setup in the statemanager.\n if (manager.init !== undefined) {\n manager.init(this.stateManager);\n }\n }\n\n /**\n * Return the current state.\n *\n * @return {object}\n */\n get state() {\n return this.stateManager.state;\n }\n\n /**\n * Get state data.\n *\n * Components access the state frequently. This convenience method is a shortcut to\n * this.reactive.state.stateManager.get() method.\n *\n * @param {String} name the state object name\n * @param {*} id an optional object id for state maps.\n * @return {Object|undefined} the state object found\n */\n get(name, id) {\n return this.stateManager.get(name, id);\n }\n\n /**\n * Return the initial state promise.\n *\n * Typically, components do not require to use this promise because registerComponent\n * will trigger their stateReady method automatically. But it could be useful for complex\n * components that require to combine state, template and string loadings.\n *\n * @method getState\n * @return {Promise}\n */\n getInitialStatePromise() {\n return this.stateManager.getInitialPromise();\n }\n\n /**\n * Register a new component.\n *\n * Component can provide some optional functions to the reactive module:\n * - getWatchers: returns an array of watchers\n * - stateReady: a method to call when the initial state is loaded\n *\n * It can also provide some optional attributes:\n * - name: the component name (default value: \"Unkown component\") to customize debug messages.\n *\n * The method will also use dispatchRegistrationSuccess and dispatchRegistrationFail. Those\n * are BaseComponent methods to inform parent components of the registration status.\n * Components should not override those methods.\n *\n * @method registerComponent\n * @param {object} component the new component\n * @param {string} [component.name] the component name to display in warnings and errors.\n * @param {Function} [component.dispatchRegistrationSuccess] method to notify registration success\n * @param {Function} [component.dispatchRegistrationFail] method to notify registration fail\n * @param {Function} [component.getWatchers] getter of the component watchers\n * @param {Function} [component.stateReady] method to call when the state is ready\n * @return {object} the registered component\n */\n registerComponent(component) {\n\n // Component name is an optional attribute to customize debug messages.\n const componentName = component.name ?? 'Unkown component';\n\n // Components can provide special methods to communicate registration to parent components.\n let dispatchSuccess = () => {\n return;\n };\n let dispatchFail = dispatchSuccess;\n if (component.dispatchRegistrationSuccess !== undefined) {\n dispatchSuccess = component.dispatchRegistrationSuccess.bind(component);\n }\n if (component.dispatchRegistrationFail !== undefined) {\n dispatchFail = component.dispatchRegistrationFail.bind(component);\n }\n\n // Components can be registered only one time.\n if (this.components.has(component)) {\n dispatchSuccess();\n return component;\n }\n\n // Components are fully registered only when the state ready promise is resolved.\n const pendingPromise = new Pending(`core/reactive:registerComponent${pendingCount++}`);\n\n // Keep track of the event listeners.\n let listeners = [];\n\n // Register watchers.\n let handlers = [];\n if (component.getWatchers !== undefined) {\n handlers = component.getWatchers();\n }\n handlers.forEach(({watch, handler}) => {\n\n if (watch === undefined) {\n dispatchFail();\n throw new Error(`Missing watch attribute in ${componentName} watcher`);\n }\n if (handler === undefined) {\n dispatchFail();\n throw new Error(`Missing handler for watcher ${watch} in ${componentName}`);\n }\n\n const listener = (event) => {\n handler.apply(component, [event.detail]);\n };\n\n // Save the listener information in case the component must be unregistered later.\n listeners.push({target: this.target, watch, listener});\n\n // The state manager triggers a general \"state changed\" event at a document level. However,\n // for the internal watchers, each component can listen to specific state changed custom events\n // in the target element. This way we can use the native event loop without colliding with other\n // reactive instances.\n this.target.addEventListener(watch, listener);\n });\n\n // Register state ready function. There's the possibility a component is registered after the initial state\n // is loaded. For those cases we have a state promise to handle this specific state change.\n if (component.stateReady !== undefined) {\n this.getInitialStatePromise()\n .then(state => {\n component.stateReady(state);\n pendingPromise.resolve();\n return true;\n })\n .catch(reason => {\n pendingPromise.resolve();\n log.error(`Initial state in ${componentName} rejected due to: ${reason}`);\n log.error(reason);\n });\n }\n\n // Save unregister data.\n this.watchers.set(component, listeners);\n this.components.add(component);\n\n // Dispatch an event to communicate the registration to the debug module.\n this.target.dispatchEvent(new CustomEvent('registerComponent:success', {\n bubbles: false,\n detail: {component},\n }));\n\n dispatchSuccess();\n return component;\n }\n\n /**\n * Unregister a component and its watchers.\n *\n * @param {object} component the object instance to unregister\n * @returns {object} the deleted component\n */\n unregisterComponent(component) {\n if (!this.components.has(component)) {\n return component;\n }\n\n this.components.delete(component);\n\n // Remove event listeners.\n const listeners = this.watchers.get(component);\n if (listeners === undefined) {\n return component;\n }\n\n listeners.forEach(({target, watch, listener}) => {\n target.removeEventListener(watch, listener);\n });\n\n this.watchers.delete(component);\n\n return component;\n }\n\n /**\n * Dispatch a change in the state.\n *\n * This method is the only way for components to alter the state. Watchers will receive a\n * read only state to prevent illegal changes. If some user action require a state change, the\n * component should dispatch a mutation to trigger all the necessary logic to alter the state.\n *\n * @method dispatch\n * @param {string} actionName the action name (usually the mutation name)\n * @param {mixed} params any number of params the mutation needs.\n */\n async dispatch(actionName, ...params) {\n if (typeof actionName !== 'string') {\n throw new Error(`Dispatch action name must be a string`);\n }\n // JS does not have private methods yet. However, we prevent any component from calling\n // a method starting with \"_\" because the most accepted convention for private methods.\n if (actionName.charAt(0) === '_') {\n throw new Error(`Illegal Private ${actionName} mutation method dispatch`);\n }\n if (this.mutations[actionName] === undefined) {\n throw new Error(`Unkown ${actionName} mutation`);\n }\n\n const pendingPromise = new Pending(`core/reactive:${actionName}${pendingCount++}`);\n\n const mutationFunction = this.mutations[actionName];\n try {\n await mutationFunction.apply(this.mutations, [this.stateManager, ...params]);\n pendingPromise.resolve();\n } catch (error) {\n // Ensure the state is locked.\n this.stateManager.setReadOnly(true);\n pendingPromise.resolve();\n throw error;\n }\n }\n}\n"],"file":"reactive.min.js"} \ No newline at end of file diff --git a/lib/amd/build/local/repository/dynamic_tabs.min.js.map b/lib/amd/build/local/repository/dynamic_tabs.min.js.map index 09d0b64c01b9a..c5eeaf18e5537 100644 --- a/lib/amd/build/local/repository/dynamic_tabs.min.js.map +++ b/lib/amd/build/local/repository/dynamic_tabs.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/local/repository/dynamic_tabs.js"],"names":["getContent","tab","jsondata","Ajax","call","methodname","args"],"mappings":"qKAuBA,uDASO,GAAMA,CAAAA,CAAU,CAAG,SAACC,CAAD,CAAMC,CAAN,CAAmB,CAMzC,MAAOC,WAAKC,IAAL,CAAU,CALD,CACZC,UAAU,CAAE,+BADA,CAEZC,IAAI,CAAE,CAACL,GAAG,CAAEA,CAAN,CAAWC,QAAQ,CAAEA,CAArB,CAFM,CAKC,CAAV,EAAqB,CAArB,CACV,CAPM,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n* Module to handle dynamic tabs AJAX requests\n*\n* @module core/local/repository/dynamic_tabs\n* @copyright 2021 David Matamoros \n* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n*/\n\nimport Ajax from 'core/ajax';\n\n/**\n* Return tab content\n*\n* @param {String} tab\n* @param {String} jsondata\n* @return {Promise}\n*/\nexport const getContent = (tab, jsondata) => {\n const request = {\n methodname: 'core_dynamic_tabs_get_content',\n args: {tab: tab, jsondata: jsondata}\n };\n\n return Ajax.call([request])[0];\n};\n"],"file":"dynamic_tabs.min.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/local/repository/dynamic_tabs.js"],"names":["getContent","tab","jsondata","Ajax","call","methodname","args"],"mappings":"qKAuBA,uDASO,GAAMA,CAAAA,CAAU,CAAG,SAACC,CAAD,CAAMC,CAAN,CAAmB,CAMzC,MAAOC,WAAKC,IAAL,CAAU,CALD,CACZC,UAAU,CAAE,+BADA,CAEZC,IAAI,CAAE,CAACL,GAAG,CAAEA,CAAN,CAAWC,QAAQ,CAAEA,CAArB,CAFM,CAKC,CAAV,EAAqB,CAArB,CACV,CAPM,C","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Module to handle dynamic tabs AJAX requests\n *\n * @module core/local/repository/dynamic_tabs\n * @copyright 2021 David Matamoros \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\n\n/**\n * Return tab content\n *\n * @param {String} tab\n * @param {String} jsondata\n * @return {Promise}\n */\nexport const getContent = (tab, jsondata) => {\n const request = {\n methodname: 'core_dynamic_tabs_get_content',\n args: {tab: tab, jsondata: jsondata}\n };\n\n return Ajax.call([request])[0];\n};\n"],"file":"dynamic_tabs.min.js"} \ No newline at end of file diff --git a/lib/amd/build/sortable_list.min.js.map b/lib/amd/build/sortable_list.min.js.map index 1c0d3dde72ce4..3536547152323 100644 --- a/lib/amd/build/sortable_list.min.js.map +++ b/lib/amd/build/sortable_list.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/sortable_list.js"],"names":["define","$","log","autoScroll","str","ModalFactory","ModalEvents","Notification","defaultParameters","targetListSelector","moveHandlerSelector","isHorizontal","CSS","keyboardDragClass","isDraggedClass","currentPositionClass","sourceListClass","targetListClass","overElementClass","registerNotPassiveListeners","eventname","setup","x","ns","handle","includes","addEventListener","passive","eventListenerOptionsSupported","passivesupported","options","Object","defineProperty","get","document","removeEventListener","err","event","special","touchstart","touchmove","touchend","SortableList","root","config","info","proxy","proxyDelta","dragCounter","lastEvent","extend","listSelector","on","dragStartHandler","clickHandler","EVENTS","DRAGSTART","DRAG","DROP","DRAGEND","prototype","resetDraggedClasses","classes","i","removeClass","remove","calculatePositionOnPage","evt","originalEvent","touches","touch","pageX","pageY","clientX","Math","round","window","scrollLeft","clientY","scrollTop","type","moveElement","sourceList","sourceNextElement","finishDragging","which","movedElement","target","closest","currentTarget","children","length","stopPropagation","preventDefault","element","next","parent","targetNextElement","targetList","dropped","startX","startY","startTime","Date","getTime","addClass","offset","left","y","top","thisDragCounter","setTimeout","createProxy","dragHandler","dragcancelHandler","start","trigger","executeCallback","clone","append","removeAttr","css","position","keyCode","clickedElement","displayMoveDialogue","getPositionInNode","node","rect","getBoundingClientRect","scrollY","scrollX","width","height","xRatio","yRatio","isListHorizontal","elementFromPoint","mainElement","isNotSelf","current","filter","currentList","isNotProxy","find","coordinates","ratio","subList","subListEmpty","endX","endY","endTime","positionChanged","hasPositionChanged","oldinfo","parentElement","beforeElement","dragEl","insertBefore","appendChild","stop","off","eventName","getElementName","Deferred","resolve","text","getDestinationName","afterElement","get_string","then","name","getMoveDialogueTitle","handler","attr","getDestinationsList","addedLists","targets","destinations","result","when","createLink","is","contains","txt","li","appendTo","a","data","addList","inArray","push","list","each","prev","last","create","types","CANCEL","title","body","modal","quickMoveHandler","e","focus","hide","getRoot","hidden","destroy","setLarge","show","catch","exception"],"mappings":"mSA4DAA,OAAM,sBAAC,CAAC,QAAD,CAAW,UAAX,CAAuB,iBAAvB,CAA0C,UAA1C,CAAsD,oBAAtD,CAA4E,mBAA5E,CAAiG,mBAAjG,CAAD,CACN,SAASC,CAAT,CAAYC,CAAZ,CAAiBC,CAAjB,CAA6BC,CAA7B,CAAkCC,CAAlC,CAAgDC,CAAhD,CAA6DC,CAA7D,CAA2E,IAQnEC,CAAAA,CAAiB,CAAG,CACpBC,kBAAkB,CAAE,IADA,CAEpBC,mBAAmB,CAAE,uBAFD,CAGpBC,YAAY,GAHQ,CAIpBR,UAAU,GAJU,CAR+C,CAqBnES,CAAG,CAAG,CACNC,iBAAiB,CAAE,wBADb,CAENC,cAAc,CAAE,0BAFV,CAGNC,oBAAoB,CAAE,gCAHhB,CAINC,eAAe,CAAE,sBAJX,CAKNC,eAAe,CAAE,sBALX,CAMNC,gBAAgB,CAAE,4BANZ,CArB6D,CAkEnEC,CAA2B,CAAG,SAASC,CAAT,CAAoB,CAClD,M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gF,KAAf,GACA,KAAKvF,eAAL,CAAqB3E,CAAY,CAACa,MAAb,CAAoBG,IAAzC,EACA+I,CAAK,CAACI,IAAN,EACH,CAVsB,CAUpB,IAVoB,CAAvB,CAWAJ,CAAK,CAACK,OAAN,GAAgB1J,EAAhB,CAAmB,OAAnB,CAA4B,qCAA5B,CAAmEsJ,CAAnE,EACAD,CAAK,CAACK,OAAN,GAAgB1J,EAAhB,CAAmB9C,CAAW,CAACyM,MAA/B,CAAuC9M,CAAC,CAAC6C,KAAF,CAAQ,UAAW,CAEtD2J,CAAK,CAACK,OAAN,GAAgB7C,GAAhB,CAAoB,OAApB,CAA6B,qCAA7B,CAAoEyC,CAApE,EACAD,CAAK,CAACO,OAAN,GACA,KAAK5H,cAAL,EACH,CALsC,CAKpC,IALoC,CAAvC,EAMAqH,CAAK,CAACQ,QAAN,GACAR,CAAK,CAACS,IAAN,GACA,MAAOT,CAAAA,CACV,CAtBO,CAsBL,IAtBK,CAJR,EA0BUU,KA1BV,CA0BgB5M,CAAY,CAAC6M,SA1B7B,CA2BH,CA5BD,CA8BA,MAAO1K,CAAAA,CAEV,CA5rBK,CAAN","sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * A javascript module to handle list items drag and drop\n *\n * Example of usage:\n *\n * Create a list (for example `