diff --git a/amd/build/calendar.min.js b/amd/build/calendar.min.js index 45d125d..d3f4fc2 100644 --- a/amd/build/calendar.min.js +++ b/amd/build/calendar.min.js @@ -1,2 +1,10 @@ -function _slicedToArray(a,b){return _arrayWithHoles(a)||_iterableToArrayLimit(a,b)||_unsupportedIterableToArray(a,b)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(a,b){if(!a)return;if("string"==typeof a)return _arrayLikeToArray(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);if("Object"===c&&a.constructor)c=a.constructor.name;if("Map"===c||"Set"===c)return Array.from(c);if("Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c))return _arrayLikeToArray(a,b)}function _arrayLikeToArray(a,b){if(null==b||b>a.length)b=a.length;for(var c=0,d=Array(b);cg;g++){if("undefined"!=typeof f[g]){for(var l=f[g],m=0;32>m;m++){if("undefined"!=typeof l[m]){e.push(l[m].number)}}}}h=Math.max.apply(Math,e);k=Math.min.apply(Math,e)}else{h=0;k=0}c(a)})},t=function(a){if(a==k){return 1}var b=h-k,c=(a-k)/b,d=Math.round(c*5+1);if(1>d){d=1}if(6s;s++){j=document.createElement("th");j.innerHTML=g[s];p.appendChild(j)}o.appendChild(q);m.appendChild(o);m.appendChild(p);r.appendChild(m);r.appendChild(n);l.appendChild(r);f.appendChild(l);h++}if("undefined"==typeof b||"undefined"==typeof c||"undefined"==typeof d){e(Error("Failed to create calendar tables."))}else{a({calendarContainer:f,year:b,startMonth:c})}})},x=function(a){for(var b="",c=0,d=Object.entries(a);c"+m[f]+": "+g+"
"}return b},y=function(a,b,c){for(var d=new Date(b,c).getDay(),e=v(b,c+1),f=1,g=0,h;6>g;g++){h=document.createElement("tr");for(var q=0;7>q;q++){if(0===g&&qp(c,b)){break}else{k=document.createElement("td");m=document.createTextNode(f);if("undefined"!=typeof e&&e.hasOwnProperty(f)){var j=t(e[f].number);if(0==n[j]||n[j]>e[f].number){n[j]=e[f].number}k.style.backgroundColor=l[j];k.style.color=o(l[j]);k.dataset.toggle="tooltip";k.dataset.html="true";k.dataset.event="true";k.dataset.date=b+"-"+(c+1)+"-"+f;k.title=x(e[f]);k.style.cursor="pointer"}f++}k.appendChild(m);h.appendChild(k)}a.appendChild(h)}},z=function(a){var b=a.calendarContainer,c=a.year,d=a.startMonth;return new Promise(function(a,e){for(var f=b.getElementsByTagName("tbody"),g=d,h=0,j;he;e++){if(0!==n[e]){var f=document.createElement("td"),g=document.createTextNode(n[e]+"+");f.appendChild(g);f.style.backgroundColor=l[e];f.style.color=o(l[e]);d.appendChild(f)}}c.appendChild(d);b.appendChild(c);n={1:0,2:0,3:0,4:0,5:0,6:0};a(b)})};d.generate=function(c,d,e,h,i){return new Promise(function(j,k){var l={year:c,startMonth:d,endMonth:e},m={year:c,metric:h,modules:i};a.get_strings(f).catch(function(){b.exception(new Error("Failed to load strings"))}).then(function(a){g=a;return m}).then(u).then(function(a){s(a,l)}).then(q).then(r).then(function(){return l}).then(w).then(z).then(function(a){if("undefined"!=typeof a){j(a)}else{k(Error("Could not generate calendar"))}})})};return d}); -//# sourceMappingURL=calendar.min.js.map +/** + * Javascript for heatmap calendar generation and display. + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/calendar",["core/str","core/notification","core/ajax"],(function(Str,Notification,Ajax){var Calendar={},eventArray=[];const stringArr=[{key:"sun",component:"calendar"},{key:"mon",component:"calendar"},{key:"tue",component:"calendar"},{key:"wed",component:"calendar"},{key:"thu",component:"calendar"},{key:"fri",component:"calendar"},{key:"sat",component:"calendar"},{key:"jan",component:"local_assessfreq"},{key:"feb",component:"local_assessfreq"},{key:"mar",component:"local_assessfreq"},{key:"apr",component:"local_assessfreq"},{key:"may",component:"local_assessfreq"},{key:"jun",component:"local_assessfreq"},{key:"jul",component:"local_assessfreq"},{key:"aug",component:"local_assessfreq"},{key:"sep",component:"local_assessfreq"},{key:"oct",component:"local_assessfreq"},{key:"nov",component:"local_assessfreq"},{key:"dec",component:"local_assessfreq"}];var stringResult,heatRangeMax,heatRangeMin,colorArray,processModules,heatRangeScale={1:0,2:0,3:0,4:0,5:0,6:0};const getContrast=function(hexcolor){return void 0===hexcolor?"#000000":("#"===hexcolor.slice(0,1)&&(hexcolor=hexcolor.slice(1)),(299*parseInt(hexcolor.substr(0,2),16)+587*parseInt(hexcolor.substr(2,2),16)+114*parseInt(hexcolor.substr(4,2),16))/1e3>=128?"#000000":"#FFFFFF")},daysInMonth=function(month,year){return 32-new Date(year,month,32).getDate()},getHeatColors=function(){return new Promise(((resolve,reject)=>{Ajax.call([{methodname:"local_assessfreq_get_heat_colors",args:{}}],!0,!1)[0].done((function(response){colorArray=JSON.parse(response),resolve(colorArray)})).fail((function(){reject(new Error("Failed to get heat colors"))}))}))},getProcessModules=function(){return new Promise(((resolve,reject)=>{Ajax.call([{methodname:"local_assessfreq_get_process_modules",args:{}}],!0,!1)[0].done((function(response){processModules=JSON.parse(response),resolve(processModules)})).fail((function(){reject(new Error("Failed to get process events"))}))}))},getHeat=function(eventCount){if(eventCount==heatRangeMin)return 1;const localPercent=(eventCount-heatRangeMin)/(heatRangeMax-heatRangeMin);let heat=Math.round(5*localPercent+1);return heat<1&&(heat=1),heat>6&&(heat=6),heat},getEvents=function(_ref){let{year:year,metric:metric,modules:modules}=_ref;return new Promise(((resolve,reject)=>{let args={year:year,metric:metric,modules:modules},jsonArgs=JSON.stringify(args);Ajax.call([{methodname:"local_assessfreq_get_frequency",args:{jsondata:jsonArgs}}])[0].done((response=>{eventArray=JSON.parse(response),resolve(eventArray)})).fail((()=>{reject(new Error("Failed to get events"))}))}))},createTables=function(_ref2){let{year:year,startMonth:startMonth,endMonth:endMonth}=_ref2;return new Promise(((resolve,reject)=>{let calendarContainer=document.createElement("div"),month=startMonth;for(let i=startMonth;i<=endMonth;i++){let container=document.createElement("div");container.classList.add("local-assessfreq-month");let table=document.createElement("table");table.classList.add("table-striped");let thead=document.createElement("thead"),tbody=document.createElement("tbody");tbody.id="calendar-body-"+i;let monthRow=document.createElement("tr"),dayrow=document.createElement("tr"),monthHeader=document.createElement("th");monthHeader.colSpan=7,monthHeader.innerHTML=stringResult[7+month];for(let j=0;j<7;j++){let dayHeader=document.createElement("th");dayHeader.innerHTML=stringResult[j],dayrow.appendChild(dayHeader)}monthRow.appendChild(monthHeader),thead.appendChild(monthRow),thead.appendChild(dayrow),table.appendChild(thead),table.appendChild(tbody),container.appendChild(table),calendarContainer.appendChild(container),month++}if(void 0===year||void 0===startMonth||void 0===endMonth)reject(Error("Failed to create calendar tables."));else{resolve({calendarContainer:calendarContainer,year:year,startMonth:startMonth})}}))},getTooltip=function(dayArray){let tipHTML="";for(let[key,value]of Object.entries(dayArray))tipHTML+=""+processModules[key]+": "+value+"
";return tipHTML},populateCalendarDays=function(table,year,month){let firstDay=new Date(year,month).getDay(),monthEvents=function(year,month){let monthevents;return void 0!==eventArray[year]&&void 0!==eventArray[year][month]&&(monthevents=eventArray[year][month]),monthevents}(year,month+1),date=1;for(let i=0;i<6;i++){let row=document.createElement("tr");for(let j=0;j<7;j++){if(0===i&&jdaysInMonth(month,year))break;if(cell=document.createElement("td"),cellText=document.createTextNode(date),void 0!==monthEvents&&monthEvents.hasOwnProperty(date)){let heat=getHeat(monthEvents[date].number);(0==heatRangeScale[heat]||heatRangeScale[heat]>monthEvents[date].number)&&(heatRangeScale[heat]=monthEvents[date].number),cell.style.backgroundColor=colorArray[heat],cell.style.color=getContrast(colorArray[heat]),cell.dataset.toggle="tooltip",cell.dataset.html="true",cell.dataset.event="true",cell.dataset.date=year+"-"+(month+1)+"-"+date,cell.title=getTooltip(monthEvents[date]),cell.style.cursor="pointer"}date++}cell.appendChild(cellText),row.appendChild(cell)}table.appendChild(row)}},populateCalendar=function(_ref3){let{calendarContainer:calendarContainer,year:year,startMonth:startMonth}=_ref3;return new Promise(((resolve,reject)=>{let tables=calendarContainer.getElementsByTagName("tbody"),month=startMonth;for(var i=0;i{let table=document.createElement("table"),tbody=document.createElement("tbody"),trow=document.createElement("tr");for(var i=1;i<7;i++)if(0!==heatRangeScale[i]){let cell=document.createElement("td"),cellText=document.createTextNode(heatRangeScale[i]+"+");cell.appendChild(cellText),cell.style.backgroundColor=colorArray[i],cell.style.color=getContrast(colorArray[i]),trow.appendChild(cell)}tbody.appendChild(trow),table.appendChild(tbody),heatRangeScale={1:0,2:0,3:0,4:0,5:0,6:0},resolve(table)}))},Calendar.generate=function(year,startMonth,endMonth,metric,modules){return new Promise(((resolve,reject)=>{const dateObj={year:year,startMonth:startMonth,endMonth:endMonth},eventObj={year:year,metric:metric,modules:modules};Str.get_strings(stringArr).catch((()=>{Notification.exception(new Error("Failed to load strings"))})).then((stringReturn=>(stringResult=stringReturn,eventObj))).then(getEvents).then((eventArray=>{!function(eventArray,dateObj){new Promise((resolve=>{if(void 0===eventArray&&(heatRangeMax=0,heatRangeMin=0,resolve(eventArray)),Object.keys(eventArray).length>0&&"undefined"!==eventArray[dateObj.year]){let eventcount=new Array,year=eventArray[dateObj.year];for(let i=0;i<12;i++)if(void 0!==year[i]){let month=year[i];for(let j=0;j<32;j++)void 0!==month[j]&&eventcount.push(month[j].number)}heatRangeMax=Math.max(...eventcount),heatRangeMin=Math.min(...eventcount)}else heatRangeMax=0,heatRangeMin=0;resolve(eventArray)}))}(eventArray,dateObj)})).then(getHeatColors).then(getProcessModules).then((()=>dateObj)).then(createTables).then(populateCalendar).then((calendarHTML=>{void 0!==calendarHTML?resolve(calendarHTML):reject(Error("Could not generate calendar"))}))}))},Calendar})); + +//# sourceMappingURL=calendar.min.js.map \ No newline at end of file diff --git a/amd/build/calendar.min.js.map b/amd/build/calendar.min.js.map index 3bac26b..bc98101 100644 --- a/amd/build/calendar.min.js.map +++ b/amd/build/calendar.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/calendar.js"],"names":["define","Str","Notification","Ajax","Calendar","eventArray","stringArr","key","component","stringResult","heatRangeMax","heatRangeMin","colorArray","processModules","heatRangeScale","getContrast","hexcolor","slice","r","parseInt","substr","g","b","daysInMonth","month","year","Date","getDate","getHeatColors","Promise","resolve","reject","call","methodname","args","done","response","JSON","parse","fail","Error","getProcessModules","calcHeatRange","dateObj","eventArrayLength","Object","keys","length","eventcount","i","j","push","number","Math","max","min","getHeat","eventCount","localRange","localPercent","heat","round","getEvents","metric","modules","jsonArgs","stringify","jsondata","getMonthEvents","monthevents","createTables","startMonth","endMonth","calendarContainer","document","createElement","container","classList","add","table","thead","tbody","id","monthRow","dayrow","monthHeader","colSpan","innerHTML","dayHeader","appendChild","getTooltip","dayArray","tipHTML","entries","value","populateCalendarDays","firstDay","getDay","monthEvents","date","row","cell","cellText","createTextNode","dataset","event","hasOwnProperty","style","backgroundColor","color","toggle","html","title","cursor","populateCalendar","tables","getElementsByTagName","createHeatScale","trow","generate","eventObj","get_strings","catch","exception","then","stringReturn","calendarHTML"],"mappings":"+qCAuBAA,OAAM,6BAAC,CAAC,UAAD,CAAa,mBAAb,CAAkC,WAAlC,CAAD,CAAiD,SAASC,CAAT,CAAcC,CAAd,CAA4BC,CAA5B,CAAkC,IAKjFC,CAAAA,CAAQ,CAAG,EALsE,CAMjFC,CAAU,CAAG,EANoE,CAO/EC,CAAS,CAAG,CACd,CAACC,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CADc,CAEd,CAACD,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CAFc,CAGd,CAACD,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CAHc,CAId,CAACD,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CAJc,CAKd,CAACD,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CALc,CAMd,CAACD,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB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ACtE,MAAO,IAAInC,CAAAA,OAAJ,CAAY,SAACC,CAAD,CAAUC,CAAV,CAAqB,IAC9BY,CAAAA,CAAO,CAAG,CACZlB,IAAI,CAAGA,CADK,CAEZ8C,UAAU,CAAGA,CAFD,CAGZC,QAAQ,CAAGA,CAHC,CADoB,CAO9BgD,CAAQ,CAAG,CACb/F,IAAI,CAAGA,CADM,CAEbsC,MAAM,CAAGA,CAFI,CAGbC,OAAO,CAAGA,CAHG,CAPmB,CAapC/D,CAAG,CAACwH,WAAJ,CAAgBnH,CAAhB,EAA2BoH,KAA3B,CAAiC,UAAM,CACnCxH,CAAY,CAACyH,SAAb,CAAuB,GAAInF,CAAAA,KAAJ,CAAU,wBAAV,CAAvB,CAEH,CAHD,EAGGoF,IAHH,CAGQ,SAAAC,CAAY,CAAI,CACpBpH,CAAY,CAAGoH,CAAf,CACA,MAAOL,CAAAA,CACV,CAND,EAOCI,IAPD,CAOM9D,CAPN,EAQC8D,IARD,CAQM,SAACvH,CAAD,CAAgB,CAClBqC,CAAa,CAACrC,CAAD,CAAasC,CAAb,CAChB,CAVD,EAWCiF,IAXD,CAWMhG,CAXN,EAYCgG,IAZD,CAYMnF,CAZN,EAaCmF,IAbD,CAaM,UAAM,CACR,MAAOjF,CAAAA,CACV,CAfD,EAgBCiF,IAhBD,CAgBMtD,CAhBN,EAiBCsD,IAjBD,CAiBMV,CAjBN,EAkBCU,IAlBD,CAkBM,SAACE,CAAD,CAAkB,CACpB,GAA4B,WAAxB,QAAOA,CAAAA,CAAX,CAAyC,CACrChG,CAAO,CAACgG,CAAD,CACV,CAFD,IAEO,CACH/F,CAAM,CAACS,KAAK,CAAC,6BAAD,CAAN,CACT,CACJ,CAxBD,CAyBH,CAtCM,CAwCV,CAzCD,CA2CA,MAAOpC,CAAAA,CACV,CApfK,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 * Javascript for heatmap calendar generation and display.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/str', 'core/notification', 'core/ajax'], function(Str, Notification, Ajax) {\n\n /**\n * Module level variables.\n */\n var Calendar = {};\n var eventArray = [];\n const stringArr = [\n {key: 'sun', component: 'calendar'},\n {key: 'mon', component: 'calendar'},\n {key: 'tue', component: 'calendar'},\n {key: 'wed', component: 'calendar'},\n {key: 'thu', component: 'calendar'},\n {key: 'fri', component: 'calendar'},\n {key: 'sat', component: 'calendar'},\n {key: 'jan', component: 'local_assessfreq'},\n {key: 'feb', component: 'local_assessfreq'},\n {key: 'mar', component: 'local_assessfreq'},\n {key: 'apr', component: 'local_assessfreq'},\n {key: 'may', component: 'local_assessfreq'},\n {key: 'jun', component: 'local_assessfreq'},\n {key: 'jul', component: 'local_assessfreq'},\n {key: 'aug', component: 'local_assessfreq'},\n {key: 'sep', component: 'local_assessfreq'},\n {key: 'oct', component: 'local_assessfreq'},\n {key: 'nov', component: 'local_assessfreq'},\n {key: 'dec', component: 'local_assessfreq'},\n ];\n var stringResult;\n var heatRangeMax;\n var heatRangeMin;\n var colorArray;\n var processModules;\n var heatRangeScale = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0};\n\n /**\n * Pick a contrasting text color based on the background color.\n *\n * @param {String} A hexcolor value.\n * @return {String} The contrasting color (black or white).\n */\n const getContrast = function (hexcolor) {\n\n if (typeof (hexcolor) === \"undefined\") {\n return '#000000';\n }\n\n // If a leading # is provided, remove it.\n if (hexcolor.slice(0, 1) === '#') {\n hexcolor = hexcolor.slice(1);\n }\n\n // Convert to RGB value.\n var r = parseInt(hexcolor.substr(0,2),16);\n var g = parseInt(hexcolor.substr(2,2),16);\n var b = parseInt(hexcolor.substr(4,2),16);\n\n // Get YIQ ratio.\n var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;\n\n // Check contrast.\n return (yiq >= 128) ? '#000000' : '#FFFFFF';\n };\n\n /**\n * Check how many days in a month code.\n * from https://dzone.com/articles/determining-number-days-month.\n *\n * @method daysInMonth\n * @param {Number} month The month to get the number of days for.\n * @param {Number} year The year to get the number of days for.\n */\n const daysInMonth = function(month, year) {\n return 32 - new Date(year, month, 32).getDate();\n };\n\n /**\n * Get the heat colors to use in the heat map via Ajax.\n *\n * @method getHeatColors\n */\n const getHeatColors = function() {\n return new Promise((resolve, reject) => {\n Ajax.call([{\n methodname: 'local_assessfreq_get_heat_colors',\n args: {},\n }], true, false)[0].done(function(response) {\n colorArray = JSON.parse(response);\n resolve(colorArray);\n }).fail(function() {\n reject(new Error('Failed to get heat colors'));\n });\n });\n };\n\n /**\n * Get the event names that we are processing.\n *\n * @method getProcessEvents\n */\n const getProcessModules = function() {\n return new Promise((resolve, reject) => {\n Ajax.call([{\n methodname: 'local_assessfreq_get_process_modules',\n args: {},\n }], true, false)[0].done(function(response) {\n processModules = JSON.parse(response);\n resolve(processModules);\n }).fail(function() {\n reject(new Error('Failed to get process events'));\n });\n });\n };\n\n /**\n * Calculate the min and max values to use in the heatmap.\n *\n * @method daysInMonth\n * @param {Object} eventArray All the event count for the heatmap.\n * @param {Object} dateObj Date details.\n */\n const calcHeatRange = function(eventArray, dateObj) {\n return new Promise((resolve) => {\n\n // Resolve early if there are no events.\n if (typeof (eventArray) === \"undefined\") {\n heatRangeMax = 0;\n heatRangeMin = 0;\n\n resolve(eventArray);\n }\n // If scheduled tasks have not run yet we may not have any data.\n let eventArrayLength = Object.keys(eventArray).length;\n if ((eventArrayLength > 0) && (eventArray[dateObj.year] !== \"undefined\")) {\n\n let eventcount = new Array;\n let year = eventArray[dateObj.year];\n\n // Iterate through all the event counts.\n // This code looks nasty but there is only 366 days in a year.\n for (let i = 0; i < 12; i++) {\n if (typeof year[i] !== \"undefined\") {\n let month = year[i];\n for (let j = 0; j < 32; j++) {\n if (typeof month[j] !== \"undefined\") {\n eventcount.push(month[j].number);\n }\n }\n }\n }\n\n // Get min and max values to calculate heat spread.\n heatRangeMax = Math.max(...eventcount);\n heatRangeMin = Math.min(...eventcount);\n } else {\n heatRangeMax = 0;\n heatRangeMin = 0;\n }\n\n resolve(eventArray);\n });\n };\n\n /**\n * Translate assessment frequency to a heat value.\n *\n * @method getHeat\n * @param {Number} eventCount The count to get the heat value.\n * @return {Number} heat The heat value.\n */\n const getHeat = function(eventCount) {\n let scaleMin = 1;\n\n if (eventCount == heatRangeMin) {\n return scaleMin;\n }\n\n const scaleRange = 5; // 0 - 5 steps.\n const localRange = heatRangeMax - heatRangeMin;\n const localPercent = (eventCount - heatRangeMin) / localRange;\n let heat = Math.round((localPercent * scaleRange) + 1);\n\n // Clamp values.\n if (heat < 1) {\n heat = 1;\n }\n\n if (heat > 6) {\n heat = 6;\n }\n\n return heat;\n };\n\n /**\n * Get the events to display in the calendar via ajax call.\n *\n * @method getEvents\n * @param {Number} year The year to get the events for.\n * @param {String} metric The type of metric to get, 'students' or 'assess'.\n * @param {Array} modules Array of the modules to get.\n * @return {Promise}\n */\n const getEvents = function({year, metric, modules}) {\n return new Promise((resolve, reject) => {\n let args = {\n year: year,\n metric: metric,\n modules: modules\n };\n let jsonArgs = JSON.stringify(args);\n\n // Get the events to use in the mapping.\n Ajax.call([{\n methodname: 'local_assessfreq_get_frequency',\n args: {\n jsondata: jsonArgs\n },\n }])[0].done((response) => {\n eventArray = JSON.parse(response);\n resolve(eventArray);\n }).fail(() => {\n reject(new Error('Failed to get events'));\n });\n });\n };\n\n /**\n * Get the events for a particular month and year.\n *\n * @param {Number} year The year to get the number of days for.\n * @param {Number} month The month to get the number of days for.\n * @return {Array} monthevents The events for the supplied month.\n */\n const getMonthEvents = function(year, month) {\n let monthevents;\n\n if ((typeof eventArray[year] !== \"undefined\") && (typeof eventArray[year][month] !== \"undefined\")) {\n monthevents = eventArray[year][month];\n }\n\n return monthevents;\n };\n\n /**\n * Create the table structure for the calendar months.\n *\n * @oaram {Number} year The year to generate the tables for.\n * @param {Number} startMonth The month to start table generation from.\n * @param {Number} endMonth The month to generate the tables to.\n * @return {Promise}\n */\n const createTables = function({year, startMonth, endMonth}) {\n return new Promise((resolve, reject) => {\n let calendarContainer = document.createElement('div');\n let month = startMonth;\n\n // Itterate through and build are tables.\n for (let i = startMonth; i <= endMonth; i++) {\n // Setup some elements.\n let container = document.createElement('div');\n container.classList.add('local-assessfreq-month');\n let table = document.createElement('table');\n table.classList.add('table-striped');\n let thead = document.createElement('thead');\n let tbody = document.createElement('tbody');\n tbody.id = 'calendar-body-' + i;\n let monthRow = document.createElement('tr');\n let dayrow = document.createElement('tr');\n let monthHeader = document.createElement('th');\n monthHeader.colSpan = 7;\n monthHeader.innerHTML = stringResult[(7 + month)];\n\n for (let j = 0; j < 7; j++) {\n let dayHeader = document.createElement('th');\n dayHeader.innerHTML = stringResult[j];\n dayrow.appendChild(dayHeader);\n }\n\n // Construct the table.\n monthRow.appendChild(monthHeader);\n\n thead.appendChild(monthRow);\n thead.appendChild(dayrow);\n\n table.appendChild(thead);\n table.appendChild(tbody);\n\n container.appendChild(table);\n\n // Add to parent.\n calendarContainer.appendChild(container);\n\n // Increment variables.\n month++;\n }\n\n if ((typeof year === 'undefined') || (typeof startMonth === 'undefined') || (typeof endMonth === 'undefined')) {\n reject(Error('Failed to create calendar tables.'));\n } else {\n const resultObj = {\n calendarContainer : calendarContainer,\n year : year,\n startMonth : startMonth\n };\n resolve(resultObj);\n }\n });\n };\n\n /**\n * Generate the tooltip HTML.\n *\n * @param {Object} dayArray The details of the events for that day/\n * @return {String} tipHTML The HTML for the tooltip.\n */\n const getTooltip = function(dayArray) {\n let tipHTML = '';\n\n for (let [key, value] of Object.entries(dayArray)) {\n tipHTML += '' + processModules[key] + ': ' + value + '
';\n }\n\n return tipHTML;\n };\n\n /**\n * Generate calendar markup for the month.\n *\n * @param {Object} table The base table to populate.\n * @param {Number} year The year to generate calendar for.\n * @param {Number} month The monthe to generate calendar for.\n */\n const populateCalendarDays = function(table, year, month) {\n let firstDay = (new Date(year, month)).getDay(); // Get the starting day of the month.\n let monthEvents = getMonthEvents(year, (month + 1)); // We add one due to month diferences between PHP and JS.\n let date = 1; // Creating all cells.\n\n for (let i = 0; i < 6; i++) {\n let row = document.createElement(\"tr\"); // Creates a table row.\n\n // Creating individual cells, filing them up with data.\n for (let j = 0; j < 7; j++) {\n if (i === 0 && j < firstDay) {\n var cell = document.createElement(\"td\");\n var cellText = document.createTextNode(\"\");\n cell.dataset.event = 'false';\n\n } else if (date > daysInMonth(month, year)) { // Break if we have generated all the days for this month.\n break;\n } else {\n cell = document.createElement(\"td\");\n cellText = document.createTextNode(date);\n if ((typeof monthEvents !== \"undefined\") && (monthEvents.hasOwnProperty(date))) {\n let heat = getHeat(monthEvents[date]['number']);\n\n if (heatRangeScale[heat] == 0 || heatRangeScale[heat] > monthEvents[date]['number']) {\n heatRangeScale[heat] = monthEvents[date]['number'];\n }\n\n cell.style.backgroundColor = colorArray[heat];\n cell.style.color = getContrast(colorArray[heat]);\n\n // Add tooltip to cell.\n cell.dataset.toggle = 'tooltip';\n cell.dataset.html = 'true';\n cell.dataset.event = 'true';\n cell.dataset.date = year + '-' + (month + 1) + '-' + date;\n cell.title = getTooltip(monthEvents[date]);\n cell.style.cursor = \"pointer\";\n\n }\n date++;\n }\n\n cell.appendChild(cellText);\n row.appendChild(cell);\n }\n table.appendChild(row); // Appending each row into calendar body.\n }\n };\n\n /**\n * Controls the population of the calendar in to the base tables.\n *\n * @param {Object} calendarContainer the container to populate.\n * @param {Number} year The year to generate calendar for.\n * @param {Number} startMonth The month to start generation from.\n * @return {Promise}\n */\n const populateCalendar = function({calendarContainer, year, startMonth}) {\n return new Promise((resolve, reject) => {\n // Get the table boodies.\n let tables = calendarContainer.getElementsByTagName(\"tbody\");\n let month = startMonth;\n\n // For each table body populate with calendar.\n for (var i = 0; i < tables.length; i++) {\n let table = tables[i];\n populateCalendarDays(table, year, month);\n month++;\n }\n\n if (typeof calendarContainer === 'undefined') {\n reject(Error('Failed to populate calendar tables.'));\n } else {\n resolve(calendarContainer);\n }\n });\n };\n\n /**\n * Create the heatmap scale for the calendar.\n *\n * @method createHeatScale\n */\n Calendar.createHeatScale = function() {\n return new Promise((resolve) => {\n let table = document.createElement('table');\n let tbody = document.createElement('tbody');\n let trow = document.createElement('tr');\n\n for (var i = 1; i < 7; i++) {\n if (heatRangeScale[i] !== 0) {\n let cell = document.createElement('td');\n let cellText = document.createTextNode(heatRangeScale[i] + '+');\n\n cell.appendChild(cellText);\n cell.style.backgroundColor = colorArray[i];\n cell.style.color = getContrast(colorArray[i]);\n\n trow.appendChild(cell);\n }\n\n }\n\n tbody.appendChild(trow);\n table.appendChild(tbody);\n\n // Reset heat range scale.\n heatRangeScale = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0};\n\n resolve(table);\n });\n };\n\n /**\n * Initialise method for report calendar heatmap creation.\n *\n * @param {Number} year The year to generate the heatmap for.\n * @param {Number} startMonth The month to start with for the heatmap calendar.\n * @param {Number} endMonth The month to end with for the heatmap calendar.\n * @param {String} metric The type of metric to display, 'students' or 'aseess'.\n * @param {Array} modules The modules to display in the heatamp.\n * @return {Promise}\n */\n Calendar.generate = function(year, startMonth, endMonth, metric, modules) {\n return new Promise((resolve, reject) => {\n const dateObj = {\n year : year,\n startMonth : startMonth,\n endMonth : endMonth\n };\n\n const eventObj = {\n year : year,\n metric : metric,\n modules : modules\n };\n\n Str.get_strings(stringArr).catch(() => { // Get required strings.\n Notification.exception(new Error('Failed to load strings'));\n return;\n }).then(stringReturn => { // Save string to global to be used later.\n stringResult = stringReturn;\n return eventObj;\n })\n .then(getEvents)\n .then((eventArray) => {\n calcHeatRange(eventArray, dateObj);\n })\n .then(getHeatColors)\n .then(getProcessModules)\n .then(() => {\n return dateObj;\n })\n .then(createTables) // Create tables for calendar.\n .then(populateCalendar)\n .then((calendarHTML) => { // Return the result of the generate function.\n if (typeof calendarHTML !== 'undefined') {\n resolve(calendarHTML);\n } else {\n reject(Error('Could not generate calendar'));\n }\n });\n });\n\n };\n\n return Calendar;\n});\n"],"file":"calendar.min.js"} \ No newline at end of file +{"version":3,"file":"calendar.min.js","sources":["../src/calendar.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for heatmap calendar generation and display.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/str', 'core/notification', 'core/ajax'], function (Str, Notification, Ajax) {\n\n /**\n * Module level variables.\n */\n var Calendar = {};\n var eventArray = [];\n const stringArr = [\n {key: 'sun', component: 'calendar'},\n {key: 'mon', component: 'calendar'},\n {key: 'tue', component: 'calendar'},\n {key: 'wed', component: 'calendar'},\n {key: 'thu', component: 'calendar'},\n {key: 'fri', component: 'calendar'},\n {key: 'sat', component: 'calendar'},\n {key: 'jan', component: 'local_assessfreq'},\n {key: 'feb', component: 'local_assessfreq'},\n {key: 'mar', component: 'local_assessfreq'},\n {key: 'apr', component: 'local_assessfreq'},\n {key: 'may', component: 'local_assessfreq'},\n {key: 'jun', component: 'local_assessfreq'},\n {key: 'jul', component: 'local_assessfreq'},\n {key: 'aug', component: 'local_assessfreq'},\n {key: 'sep', component: 'local_assessfreq'},\n {key: 'oct', component: 'local_assessfreq'},\n {key: 'nov', component: 'local_assessfreq'},\n {key: 'dec', component: 'local_assessfreq'},\n ];\n var stringResult;\n var heatRangeMax;\n var heatRangeMin;\n var colorArray;\n var processModules;\n var heatRangeScale = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0};\n\n /**\n * Pick a contrasting text color based on the background color.\n *\n * @param {String} A hexcolor value.\n * @return {String} The contrasting color (black or white).\n */\n const getContrast = function (hexcolor) {\n\n if (typeof (hexcolor) === \"undefined\") {\n return '#000000';\n }\n\n // If a leading # is provided, remove it.\n if (hexcolor.slice(0, 1) === '#') {\n hexcolor = hexcolor.slice(1);\n }\n\n // Convert to RGB value.\n var r = parseInt(hexcolor.substr(0,2),16);\n var g = parseInt(hexcolor.substr(2,2),16);\n var b = parseInt(hexcolor.substr(4,2),16);\n\n // Get YIQ ratio.\n var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;\n\n // Check contrast.\n return (yiq >= 128) ? '#000000' : '#FFFFFF';\n };\n\n /**\n * Check how many days in a month code.\n * from https://dzone.com/articles/determining-number-days-month.\n *\n * @method daysInMonth\n * @param {Number} month The month to get the number of days for.\n * @param {Number} year The year to get the number of days for.\n */\n const daysInMonth = function (month, year) {\n return 32 - new Date(year, month, 32).getDate();\n };\n\n /**\n * Get the heat colors to use in the heat map via Ajax.\n *\n * @method getHeatColors\n */\n const getHeatColors = function () {\n return new Promise((resolve, reject) => {\n Ajax.call([{\n methodname: 'local_assessfreq_get_heat_colors',\n args: {},\n }], true, false)[0].done(function (response) {\n colorArray = JSON.parse(response);\n resolve(colorArray);\n }).fail(function () {\n reject(new Error('Failed to get heat colors'));\n });\n });\n };\n\n /**\n * Get the event names that we are processing.\n *\n * @method getProcessEvents\n */\n const getProcessModules = function () {\n return new Promise((resolve, reject) => {\n Ajax.call([{\n methodname: 'local_assessfreq_get_process_modules',\n args: {},\n }], true, false)[0].done(function (response) {\n processModules = JSON.parse(response);\n resolve(processModules);\n }).fail(function () {\n reject(new Error('Failed to get process events'));\n });\n });\n };\n\n /**\n * Calculate the min and max values to use in the heatmap.\n *\n * @method daysInMonth\n * @param {Object} eventArray All the event count for the heatmap.\n * @param {Object} dateObj Date details.\n */\n const calcHeatRange = function (eventArray, dateObj) {\n return new Promise((resolve) => {\n\n // Resolve early if there are no events.\n if (typeof (eventArray) === \"undefined\") {\n heatRangeMax = 0;\n heatRangeMin = 0;\n\n resolve(eventArray);\n }\n // If scheduled tasks have not run yet we may not have any data.\n let eventArrayLength = Object.keys(eventArray).length;\n if ((eventArrayLength > 0) && (eventArray[dateObj.year] !== \"undefined\")) {\n let eventcount = new Array;\n let year = eventArray[dateObj.year];\n\n // Iterate through all the event counts.\n // This code looks nasty but there is only 366 days in a year.\n for (let i = 0; i < 12; i++) {\n if (typeof year[i] !== \"undefined\") {\n let month = year[i];\n for (let j = 0; j < 32; j++) {\n if (typeof month[j] !== \"undefined\") {\n eventcount.push(month[j].number);\n }\n }\n }\n }\n\n // Get min and max values to calculate heat spread.\n heatRangeMax = Math.max(...eventcount);\n heatRangeMin = Math.min(...eventcount);\n } else {\n heatRangeMax = 0;\n heatRangeMin = 0;\n }\n\n resolve(eventArray);\n });\n };\n\n /**\n * Translate assessment frequency to a heat value.\n *\n * @method getHeat\n * @param {Number} eventCount The count to get the heat value.\n * @return {Number} heat The heat value.\n */\n const getHeat = function (eventCount) {\n let scaleMin = 1;\n\n if (eventCount == heatRangeMin) {\n return scaleMin;\n }\n\n const scaleRange = 5; // 0 - 5 steps.\n const localRange = heatRangeMax - heatRangeMin;\n const localPercent = (eventCount - heatRangeMin) / localRange;\n let heat = Math.round((localPercent * scaleRange) + 1);\n\n // Clamp values.\n if (heat < 1) {\n heat = 1;\n }\n\n if (heat > 6) {\n heat = 6;\n }\n\n return heat;\n };\n\n /**\n * Get the events to display in the calendar via ajax call.\n *\n * @method getEvents\n * @param {Number} year The year to get the events for.\n * @param {String} metric The type of metric to get, 'students' or 'assess'.\n * @param {Array} modules Array of the modules to get.\n * @return {Promise}\n */\n const getEvents = function ({year, metric, modules}) {\n return new Promise((resolve, reject) => {\n let args = {\n year: year,\n metric: metric,\n modules: modules\n };\n let jsonArgs = JSON.stringify(args);\n\n // Get the events to use in the mapping.\n Ajax.call([{\n methodname: 'local_assessfreq_get_frequency',\n args: {\n jsondata: jsonArgs\n },\n }])[0].done((response) => {\n eventArray = JSON.parse(response);\n resolve(eventArray);\n }).fail(() => {\n reject(new Error('Failed to get events'));\n });\n });\n };\n\n /**\n * Get the events for a particular month and year.\n *\n * @param {Number} year The year to get the number of days for.\n * @param {Number} month The month to get the number of days for.\n * @return {Array} monthevents The events for the supplied month.\n */\n const getMonthEvents = function (year, month) {\n let monthevents;\n\n if ((typeof eventArray[year] !== \"undefined\") && (typeof eventArray[year][month] !== \"undefined\")) {\n monthevents = eventArray[year][month];\n }\n\n return monthevents;\n };\n\n /**\n * Create the table structure for the calendar months.\n *\n * @oaram {Number} year The year to generate the tables for.\n * @param {Number} startMonth The month to start table generation from.\n * @param {Number} endMonth The month to generate the tables to.\n * @return {Promise}\n */\n const createTables = function ({year, startMonth, endMonth}) {\n return new Promise((resolve, reject) => {\n let calendarContainer = document.createElement('div');\n let month = startMonth;\n\n // Itterate through and build are tables.\n for (let i = startMonth; i <= endMonth; i++) {\n // Setup some elements.\n let container = document.createElement('div');\n container.classList.add('local-assessfreq-month');\n let table = document.createElement('table');\n table.classList.add('table-striped');\n let thead = document.createElement('thead');\n let tbody = document.createElement('tbody');\n tbody.id = 'calendar-body-' + i;\n let monthRow = document.createElement('tr');\n let dayrow = document.createElement('tr');\n let monthHeader = document.createElement('th');\n monthHeader.colSpan = 7;\n monthHeader.innerHTML = stringResult[(7 + month)];\n\n for (let j = 0; j < 7; j++) {\n let dayHeader = document.createElement('th');\n dayHeader.innerHTML = stringResult[j];\n dayrow.appendChild(dayHeader);\n }\n\n // Construct the table.\n monthRow.appendChild(monthHeader);\n\n thead.appendChild(monthRow);\n thead.appendChild(dayrow);\n\n table.appendChild(thead);\n table.appendChild(tbody);\n\n container.appendChild(table);\n\n // Add to parent.\n calendarContainer.appendChild(container);\n\n // Increment variables.\n month++;\n }\n\n if ((typeof year === 'undefined') || (typeof startMonth === 'undefined') || (typeof endMonth === 'undefined')) {\n reject(Error('Failed to create calendar tables.'));\n } else {\n const resultObj = {\n calendarContainer : calendarContainer,\n year : year,\n startMonth : startMonth\n };\n resolve(resultObj);\n }\n });\n };\n\n /**\n * Generate the tooltip HTML.\n *\n * @param {Object} dayArray The details of the events for that day/\n * @return {String} tipHTML The HTML for the tooltip.\n */\n const getTooltip = function (dayArray) {\n let tipHTML = '';\n\n for (let [key, value] of Object.entries(dayArray)) {\n tipHTML += '' + processModules[key] + ': ' + value + '
';\n }\n\n return tipHTML;\n };\n\n /**\n * Generate calendar markup for the month.\n *\n * @param {Object} table The base table to populate.\n * @param {Number} year The year to generate calendar for.\n * @param {Number} month The monthe to generate calendar for.\n */\n const populateCalendarDays = function (table, year, month) {\n let firstDay = (new Date(year, month)).getDay(); // Get the starting day of the month.\n let monthEvents = getMonthEvents(year, (month + 1)); // We add one due to month diferences between PHP and JS.\n let date = 1; // Creating all cells.\n\n for (let i = 0; i < 6; i++) {\n let row = document.createElement(\"tr\"); // Creates a table row.\n\n // Creating individual cells, filing them up with data.\n for (let j = 0; j < 7; j++) {\n if (i === 0 && j < firstDay) {\n var cell = document.createElement(\"td\");\n var cellText = document.createTextNode(\"\");\n cell.dataset.event = 'false';\n } else if (date > daysInMonth(month, year)) { // Break if we have generated all the days for this month.\n break;\n } else {\n cell = document.createElement(\"td\");\n cellText = document.createTextNode(date);\n if ((typeof monthEvents !== \"undefined\") && (monthEvents.hasOwnProperty(date))) {\n let heat = getHeat(monthEvents[date]['number']);\n\n if (heatRangeScale[heat] == 0 || heatRangeScale[heat] > monthEvents[date]['number']) {\n heatRangeScale[heat] = monthEvents[date]['number'];\n }\n\n cell.style.backgroundColor = colorArray[heat];\n cell.style.color = getContrast(colorArray[heat]);\n\n // Add tooltip to cell.\n cell.dataset.toggle = 'tooltip';\n cell.dataset.html = 'true';\n cell.dataset.event = 'true';\n cell.dataset.date = year + '-' + (month + 1) + '-' + date;\n cell.title = getTooltip(monthEvents[date]);\n cell.style.cursor = \"pointer\";\n }\n date++;\n }\n\n cell.appendChild(cellText);\n row.appendChild(cell);\n }\n table.appendChild(row); // Appending each row into calendar body.\n }\n };\n\n /**\n * Controls the population of the calendar in to the base tables.\n *\n * @param {Object} calendarContainer the container to populate.\n * @param {Number} year The year to generate calendar for.\n * @param {Number} startMonth The month to start generation from.\n * @return {Promise}\n */\n const populateCalendar = function ({calendarContainer, year, startMonth}) {\n return new Promise((resolve, reject) => {\n // Get the table boodies.\n let tables = calendarContainer.getElementsByTagName(\"tbody\");\n let month = startMonth;\n\n // For each table body populate with calendar.\n for (var i = 0; i < tables.length; i++) {\n let table = tables[i];\n populateCalendarDays(table, year, month);\n month++;\n }\n\n if (typeof calendarContainer === 'undefined') {\n reject(Error('Failed to populate calendar tables.'));\n } else {\n resolve(calendarContainer);\n }\n });\n };\n\n /**\n * Create the heatmap scale for the calendar.\n *\n * @method createHeatScale\n */\n Calendar.createHeatScale = function () {\n return new Promise((resolve) => {\n let table = document.createElement('table');\n let tbody = document.createElement('tbody');\n let trow = document.createElement('tr');\n\n for (var i = 1; i < 7; i++) {\n if (heatRangeScale[i] !== 0) {\n let cell = document.createElement('td');\n let cellText = document.createTextNode(heatRangeScale[i] + '+');\n\n cell.appendChild(cellText);\n cell.style.backgroundColor = colorArray[i];\n cell.style.color = getContrast(colorArray[i]);\n\n trow.appendChild(cell);\n }\n }\n\n tbody.appendChild(trow);\n table.appendChild(tbody);\n\n // Reset heat range scale.\n heatRangeScale = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0};\n\n resolve(table);\n });\n };\n\n /**\n * Initialise method for report calendar heatmap creation.\n *\n * @param {Number} year The year to generate the heatmap for.\n * @param {Number} startMonth The month to start with for the heatmap calendar.\n * @param {Number} endMonth The month to end with for the heatmap calendar.\n * @param {String} metric The type of metric to display, 'students' or 'aseess'.\n * @param {Array} modules The modules to display in the heatamp.\n * @return {Promise}\n */\n Calendar.generate = function (year, startMonth, endMonth, metric, modules) {\n return new Promise((resolve, reject) => {\n const dateObj = {\n year : year,\n startMonth : startMonth,\n endMonth : endMonth\n };\n\n const eventObj = {\n year : year,\n metric : metric,\n modules : modules\n };\n\n Str.get_strings(stringArr).catch(() => { // Get required strings.\n Notification.exception(new Error('Failed to load strings'));\n return;\n }).then(stringReturn => { // Save string to global to be used later.\n stringResult = stringReturn;\n return eventObj;\n })\n .then(getEvents)\n .then((eventArray) => {\n calcHeatRange(eventArray, dateObj);\n })\n .then(getHeatColors)\n .then(getProcessModules)\n .then(() => {\n return dateObj;\n })\n .then(createTables) // Create tables for calendar.\n .then(populateCalendar)\n .then((calendarHTML) => { // Return the result of the generate function.\n if (typeof calendarHTML !== 'undefined') {\n resolve(calendarHTML);\n } else {\n reject(Error('Could not generate calendar'));\n }\n });\n });\n\n };\n\n return Calendar;\n});\n"],"names":["define","Str","Notification","Ajax","Calendar","eventArray","stringArr","key","component","stringResult","heatRangeMax","heatRangeMin","colorArray","processModules","heatRangeScale","getContrast","hexcolor","slice","parseInt","substr","daysInMonth","month","year","Date","getDate","getHeatColors","Promise","resolve","reject","call","methodname","args","done","response","JSON","parse","fail","Error","getProcessModules","getHeat","eventCount","localPercent","heat","Math","round","getEvents","metric","modules","jsonArgs","stringify","jsondata","createTables","startMonth","endMonth","calendarContainer","document","createElement","i","container","classList","add","table","thead","tbody","id","monthRow","dayrow","monthHeader","colSpan","innerHTML","j","dayHeader","appendChild","getTooltip","dayArray","tipHTML","value","Object","entries","populateCalendarDays","firstDay","getDay","monthEvents","monthevents","getMonthEvents","date","row","cell","cellText","createTextNode","dataset","event","hasOwnProperty","style","backgroundColor","color","toggle","html","title","cursor","populateCalendar","tables","getElementsByTagName","length","createHeatScale","trow","generate","dateObj","eventObj","get_strings","catch","exception","then","stringReturn","keys","eventcount","Array","push","number","max","min","calcHeatRange","calendarHTML"],"mappings":";;;;;;;AAuBAA,mCAAO,CAAC,WAAY,oBAAqB,cAAc,SAAUC,IAAKC,aAAcC,UAK5EC,SAAW,GACXC,WAAa,SACXC,UAAY,CACd,CAACC,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,yBAExBC,aACAC,aACAC,aACAC,WACAC,eACAC,eAAiB,GAAM,IAAQ,IAAQ,IAAQ,IAAQ,IAAQ,SAQ7DC,YAAc,SAAUC,sBAEA,IAAdA,SACD,WAIkB,MAAzBA,SAASC,MAAM,EAAG,KAClBD,SAAWA,SAASC,MAAM,KASd,IALRC,SAASF,SAASG,OAAO,EAAE,GAAG,IAKV,IAJpBD,SAASF,SAASG,OAAO,EAAE,GAAG,IAIE,IAHhCD,SAASF,SAASG,OAAO,EAAE,GAAG,KAGU,KAGjC,IAAO,UAAY,YAWhCC,YAAc,SAAUC,MAAOC,aAC1B,GAAK,IAAIC,KAAKD,KAAMD,MAAO,IAAIG,WA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MAAMiD,GAAGgD,QAOzC5G,aAAeiC,KAAK4E,OAAOJ,YAC3BxG,aAAegC,KAAK6E,OAAOL,iBAE3BzG,aAAe,EACfC,aAAe,EAGnBgB,QAAQtB,eA6TJoH,CAAcpH,WAAYsG,YAE7BK,KAAKvF,eACLuF,KAAK1E,mBACL0E,MAAK,IACKL,UAEVK,KAAK7D,cACL6D,KAAKZ,kBACLY,MAAMU,oBACyB,IAAjBA,aACP/F,QAAQ+F,cAER9F,OAAOS,MAAM,uCAOtBjC"} \ No newline at end of file diff --git a/amd/build/chart_data.min.js b/amd/build/chart_data.min.js index d9f4d65..b022511 100644 --- a/amd/build/chart_data.min.js +++ b/amd/build/chart_data.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/chart_data",["exports","core/fragment","core/notification","core/str","core/templates"],function(a,b,c,d,e){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=a.getCardCharts=void 0;b=h(b);c=h(c);d=g(d);e=h(e);function f(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;f=function(){return a};return a}function g(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=f();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var g=d?Object.getOwnPropertyDescriptor(a,e):null;if(g&&(g.get||g.set)){Object.defineProperty(c,e,g)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function h(a){return a&&a.__esModule?a:{default:a}}var i,j,k,l,m=function(a,f,g){i.forEach(function(h){var i=document.getElementById(h.cardId),m=i.getElementsByClassName("overlay-icon-container")[0],n=i.getElementsByClassName("chart-body")[0],o={call:h.call};if(f){o.hoursahead=f[0];o.hoursbehind=f[1]}if(a){o.quiz=a}if(g){o.year=g}var p={data:JSON.stringify(o)};m.classList.remove("hide");b.default.loadFragment("local_assessfreq",k,j,p).done(function(a){var b=JSON.parse(a);if(!0===b.hasdata){var f={withtable:!0,chartdata:JSON.stringify(b.chart)};if("undefined"!=typeof h.aspect){f.aspect=h.aspect}e.default.render(l,f).done(function(a,b){m.classList.add("hide");e.default.replaceNodeContents(n,a,b)}).fail(function(){c.default.exception(new Error("Failed to load chart template."))})}else{d.get_string("nodata","local_assessfreq").then(function(a){var b=document.createElement("h3");b.innerHTML=a;n.innerHTML=b.outerHTML;m.classList.add("hide")}).catch(function(){c.default.exception(new Error("Failed to load string: nodata"))})}}).fail(function(){c.default.exception(new Error("Failed to load card."))})})};a.getCardCharts=m;a.init=function init(a,b,c,d){i=a;j=b;k=c;l=d}}); -//# sourceMappingURL=chart_data.min.js.map +define("local_assessfreq/chart_data",["exports","core/fragment","core/notification","core/str","core/templates"],(function(_exports,_fragment,_notification,Str,_templates){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} +/** + * Chart data JS module. + * + * @module local_assessfreq/char_data + * @package local_assessfreq + * @copyright 2020 Guillermo Gomez + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */let cards,contextId,fragment,template;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=_exports.getCardCharts=void 0,_fragment=_interopRequireDefault(_fragment),_notification=_interopRequireDefault(_notification),Str=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(Str),_templates=_interopRequireDefault(_templates);_exports.getCardCharts=(quizId,hoursFilter,yearSelect)=>{cards.forEach((cardData=>{let cardElement=document.getElementById(cardData.cardId),spinner=cardElement.getElementsByClassName("overlay-icon-container")[0],chartBody=cardElement.getElementsByClassName("chart-body")[0],values={call:cardData.call};hoursFilter&&(values.hoursahead=hoursFilter[0],values.hoursbehind=hoursFilter[1]),quizId&&(values.quiz=quizId),yearSelect&&(values.year=yearSelect);let params={data:JSON.stringify(values)};spinner.classList.remove("hide"),_fragment.default.loadFragment("local_assessfreq",fragment,contextId,params).done((response=>{let resObj=JSON.parse(response);if(!0===resObj.hasdata){let context={withtable:!0,chartdata:JSON.stringify(resObj.chart)};return void 0!==cardData.aspect&&(context.aspect=cardData.aspect),void _templates.default.render(template,context).done(((html,js)=>{spinner.classList.add("hide"),_templates.default.replaceNodeContents(chartBody,html,js)})).fail((()=>{_notification.default.exception(new Error("Failed to load chart template."))}))}Str.get_string("nodata","local_assessfreq").then((str=>{const noDatastr=document.createElement("h3");noDatastr.innerHTML=str,chartBody.innerHTML=noDatastr.outerHTML,spinner.classList.add("hide")}))})).fail((()=>{_notification.default.exception(new Error("Failed to load card."))}))}))};_exports.init=(cardsArray,contextIdChart,fragmentChart,templateChart)=>{cards=cardsArray,contextId=contextIdChart,fragment=fragmentChart,template=templateChart}})); + +//# sourceMappingURL=chart_data.min.js.map \ No newline at end of file diff --git a/amd/build/chart_data.min.js.map b/amd/build/chart_data.min.js.map index 352ad82..cb07422 100644 --- a/amd/build/chart_data.min.js.map +++ b/amd/build/chart_data.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/chart_data.js"],"names":["cards","contextId","fragment","template","getCardCharts","quizId","hoursFilter","yearSelect","forEach","cardData","cardElement","document","getElementById","cardId","spinner","getElementsByClassName","chartBody","values","call","hoursahead","hoursbehind","quiz","year","params","JSON","stringify","classList","remove","Fragment","loadFragment","done","response","resObj","parse","hasdata","context","chart","aspect","Templates","render","html","js","add","replaceNodeContents","fail","Notification","exception","Error","Str","get_string","then","str","noDatastr","createElement","innerHTML","outerHTML","catch","init","cardsArray","contextIdChart","fragmentChart","templateChart"],"mappings":"qgBAwBA,OACA,OACA,OACA,O,4lBAKIA,CAAAA,C,CACAC,C,CACAC,C,CACAC,C,CAWSC,CAAa,CAAG,SAACC,CAAD,CAASC,CAAT,CAAsBC,CAAtB,CAAqC,CAC9DP,CAAK,CAACQ,OAAN,CAAc,SAACC,CAAD,CAAc,IACpBC,CAAAA,CAAW,CAAGC,QAAQ,CAACC,cAAT,CAAwBH,CAAQ,CAACI,MAAjC,CADM,CAEpBC,CAAO,CAAGJ,CAAW,CAACK,sBAAZ,CAAmC,wBAAnC,EAA6D,CAA7D,CAFU,CAGpBC,CAAS,CAAGN,CAAW,CAACK,sBAAZ,CAAmC,YAAnC,EAAiD,CAAjD,CAHQ,CAIpBE,CAAM,CAAG,CAAC,KAAQR,CAAQ,CAACS,IAAlB,CAJW,CAMxB,GAAIZ,CAAJ,CAAiB,CACbW,CAAM,CAACE,UAAP,CAAoBb,CAAW,CAAC,CAAD,CAA/B,CACAW,CAAM,CAACG,WAAP,CAAqBd,CAAW,CAAC,CAAD,CACnC,CACD,GAAID,CAAJ,CAAY,CACRY,CAAM,CAACI,IAAP,CAAchB,CACjB,CACD,GAAIE,CAAJ,CAAgB,CACZU,CAAM,CAACK,IAAP,CAAcf,CACjB,CACD,GAAIgB,CAAAA,CAAM,CAAG,CAAC,KAAQC,IAAI,CAACC,SAAL,CAAeR,CAAf,CAAT,CAAb,CAEAH,C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S,UAAM,CACXX,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,+BAAV,CAAvB,CACH,CARD,CASH,CACJ,CA9BL,EA8BOH,IA9BP,CA8BY,UAAM,CACdC,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,sBAAV,CAAvB,CAEH,CAjCD,CAkCH,CArDD,CAsDH,C,0BAUmB,QAAPU,CAAAA,IAAO,CAACC,CAAD,CAAaC,CAAb,CAA6BC,CAA7B,CAA4CC,CAA5C,CAA8D,CAC9E7D,CAAK,CAAG0D,CAAR,CACAzD,CAAS,CAAG0D,CAAZ,CACAzD,CAAQ,CAAG0D,CAAX,CACAzD,CAAQ,CAAG0D,CACd,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 * Chart data JS module.\n *\n * @module local_assessfreq/char_data\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Fragment from 'core/fragment';\nimport Notification from 'core/notification';\nimport * as Str from 'core/str';\nimport Templates from 'core/templates';\n\n/**\n * Module level variables.\n */\nlet cards;\nlet contextId;\nlet fragment;\nlet template;\n\n/**\n * For each of the cards on the dashboard get their corresponding chart data.\n * Data is based on the year variable from the corresponding dropdown.\n * Chart data is loaded via ajax.\n *\n * @param {int|null} quizId The quiz Id.\n * @param {array|null} hoursFilter Array with hour ahead or behind preference.\n * @param {int|null} yearSelect Year selected.\n */\nexport const getCardCharts = (quizId, hoursFilter, yearSelect) => {\n cards.forEach((cardData) => {\n let cardElement = document.getElementById(cardData.cardId);\n let spinner = cardElement.getElementsByClassName('overlay-icon-container')[0];\n let chartBody = cardElement.getElementsByClassName('chart-body')[0];\n let values = {'call': cardData.call};\n // Add values to Object depending on dashboard type.\n if (hoursFilter) {\n values.hoursahead = hoursFilter[0];\n values.hoursbehind = hoursFilter[1];\n }\n if (quizId) {\n values.quiz = quizId;\n }\n if (yearSelect) {\n values.year = yearSelect;\n }\n let params = {'data': JSON.stringify(values)};\n\n spinner.classList.remove('hide'); // Show sinner if not already shown.\n Fragment.loadFragment('local_assessfreq', fragment, contextId, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata === true) {\n let context = {\n 'withtable': true, 'chartdata': JSON.stringify(resObj.chart)\n };\n if (typeof cardData.aspect !== 'undefined') {\n context.aspect = cardData.aspect;\n }\n Templates.render(template, context).done((html, js) => {\n spinner.classList.add('hide'); // Hide spinner if not already hidden.\n // Load card body.\n Templates.replaceNodeContents(chartBody, html, js);\n }).fail(() => {\n Notification.exception(new Error('Failed to load chart template.'));\n return;\n });\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n chartBody.innerHTML = noDatastr.outerHTML;\n spinner.classList.add('hide'); // Hide spinner if not already hidden.\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: nodata'));\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load card.'));\n return;\n });\n });\n};\n\n/**\n * Initialise method for table handler.\n *\n * @param {array} cardsArray Cards array.\n * @param {int} contextIdChart The context id.\n * @param {string} fragmentChart Fragment name.\n * @param {string} templateChart Template name.\n */\nexport const init = (cardsArray, contextIdChart, fragmentChart, templateChart) => {\n cards = cardsArray;\n contextId = contextIdChart;\n fragment = fragmentChart;\n template = templateChart;\n};\n"],"file":"chart_data.min.js"} \ No newline at end of file +{"version":3,"file":"chart_data.min.js","sources":["../src/chart_data.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Chart data JS module.\n *\n * @module local_assessfreq/char_data\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Fragment from 'core/fragment';\nimport Notification from 'core/notification';\nimport * as Str from 'core/str';\nimport Templates from 'core/templates';\n\n/**\n * Module level variables.\n */\nlet cards;\nlet contextId;\nlet fragment;\nlet template;\n\n/**\n * For each of the cards on the dashboard get their corresponding chart data.\n * Data is based on the year variable from the corresponding dropdown.\n * Chart data is loaded via ajax.\n *\n * @param {int|null} quizId The quiz Id.\n * @param {array|null} hoursFilter Array with hour ahead or behind preference.\n * @param {int|null} yearSelect Year selected.\n */\nexport const getCardCharts = (quizId, hoursFilter, yearSelect) => {\n cards.forEach((cardData) => {\n let cardElement = document.getElementById(cardData.cardId);\n let spinner = cardElement.getElementsByClassName('overlay-icon-container')[0];\n let chartBody = cardElement.getElementsByClassName('chart-body')[0];\n let values = {'call': cardData.call};\n // Add values to Object depending on dashboard type.\n if (hoursFilter) {\n values.hoursahead = hoursFilter[0];\n values.hoursbehind = hoursFilter[1];\n }\n if (quizId) {\n values.quiz = quizId;\n }\n if (yearSelect) {\n values.year = yearSelect;\n }\n let params = {'data': JSON.stringify(values)};\n\n spinner.classList.remove('hide'); // Show sinner if not already shown.\n Fragment.loadFragment('local_assessfreq', fragment, contextId, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata === true) {\n let context = {\n 'withtable': true, 'chartdata': JSON.stringify(resObj.chart)\n };\n if (typeof cardData.aspect !== 'undefined') {\n context.aspect = cardData.aspect;\n }\n Templates.render(template, context).done((html, js) => {\n spinner.classList.add('hide'); // Hide spinner if not already hidden.\n // Load card body.\n Templates.replaceNodeContents(chartBody, html, js);\n }).fail(() => {\n Notification.exception(new Error('Failed to load chart template.'));\n return;\n });\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n chartBody.innerHTML = noDatastr.outerHTML;\n spinner.classList.add('hide'); // Hide spinner if not already hidden.\n return;\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load card.'));\n return;\n });\n });\n};\n\n/**\n * Initialise method for table handler.\n *\n * @param {array} cardsArray Cards array.\n * @param {int} contextIdChart The context id.\n * @param {string} fragmentChart Fragment name.\n * @param {string} templateChart Template name.\n */\nexport const init = (cardsArray, contextIdChart, fragmentChart, templateChart) => {\n cards = cardsArray;\n contextId = contextIdChart;\n fragment = fragmentChart;\n template = templateChart;\n};\n"],"names":["cards","contextId","fragment","template","quizId","hoursFilter","yearSelect","forEach","cardData","cardElement","document","getElementById","cardId","spinner","getElementsByClassName","chartBody","values","call","hoursahead","hoursbehind","quiz","year","params","JSON","stringify","classList","remove","loadFragment","done","response","resObj","parse","hasdata","context","chart","aspect","render","html","js","add","replaceNodeContents","fail","exception","Error","Str","get_string","then","str","noDatastr","createElement","innerHTML","outerHTML","cardsArray","contextIdChart","fragmentChart","templateChart"],"mappings":";;;;;;;;SAgCIA,MACAC,UACAC,SACAC,w6BAWyB,CAACC,OAAQC,YAAaC,cAC/CN,MAAMO,SAASC,eACPC,YAAcC,SAASC,eAAeH,SAASI,QAC/CC,QAAUJ,YAAYK,uBAAuB,0BAA0B,GACvEC,UAAYN,YAAYK,uBAAuB,cAAc,GAC7DE,OAAS,MAASR,SAASS,MAE3BZ,cACAW,OAAOE,WAAab,YAAY,GAChCW,OAAOG,YAAcd,YAAY,IAEjCD,SACAY,OAAOI,KAAOhB,QAEdE,aACAU,OAAOK,KAAOf,gBAEdgB,OAAS,MAASC,KAAKC,UAAUR,SAErCH,QAAQY,UAAUC,OAAO,0BAChBC,aAAa,mBAAoBzB,SAAUD,UAAWqB,QAC1DM,MAAMC,eACCC,OAASP,KAAKQ,MAAMF,cACD,IAAnBC,OAAOE,QAAkB,KACrBC,QAAU,YACG,YAAmBV,KAAKC,UAAUM,OAAOI,oBAE3B,IAApB1B,SAAS2B,SAChBF,QAAQE,OAAS3B,SAAS2B,gCAEpBC,OAAOjC,SAAU8B,SAASL,MAAK,CAACS,KAAMC,MAC5CzB,QAAQY,UAAUc,IAAI,2BAEZC,oBAAoBzB,UAAWsB,KAAMC,OAChDG,MAAK,2BACSC,UAAU,IAAIC,MAAM,sCAKrCC,IAAIC,WAAW,SAAU,oBAAoBC,MAAMC,YACzCC,UAAYtC,SAASuC,cAAc,MACzCD,UAAUE,UAAYH,IACtBhC,UAAUmC,UAAYF,UAAUG,UAChCtC,QAAQY,UAAUc,IAAI,cAI/BE,MAAK,2BACSC,UAAU,IAAIC,MAAM,8CAc7B,CAACS,WAAYC,eAAgBC,cAAeC,iBAC5DvD,MAAQoD,WACRnD,UAAYoD,eACZnD,SAAWoD,cACXnD,SAAWoD"} \ No newline at end of file diff --git a/amd/build/chart_output_chartjs.min.js b/amd/build/chart_output_chartjs.min.js index bbf31b5..95ef0ee 100644 --- a/amd/build/chart_output_chartjs.min.js +++ b/amd/build/chart_output_chartjs.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/chart_output_chartjs",["core/chart_output_chartjs"],function(a){var b={},c=!1,d=!1;a.prototype._makeConfig=function(){var a={type:this._getChartType(),data:{labels:this._cleanData(this._chart.getLabels()),datasets:this._makeDatasetsConfig()},options:{title:{display:null!==this._chart.getTitle(),text:this._cleanData(this._chart.getTitle())}}},b=this._chart.getLegendOptions();if(b){a.options.legend=b}if(d){a.options.legend=d}this._chart.getXAxes().forEach(function(b,c){var d=b.getLabels();a.options.scales=a.options.scales||{};a.options.scales.xAxes=a.options.scales.xAxes||[];a.options.scales.xAxes[c]=this._makeAxisConfig(b,"x",c);if(null!==d){a.options.scales.xAxes[c].ticks.callback=function(a,b){return d[b]||""}}a.options.scales.xAxes[c].stacked=this._isStacked()}.bind(this));this._chart.getYAxes().forEach(function(b,c){var d=b.getLabels();a.options.scales=a.options.scales||{};a.options.scales.yAxes=a.options.scales.yAxes||[];a.options.scales.yAxes[c]=this._makeAxisConfig(b,"y",c);if(null!==d){a.options.scales.yAxes[c].ticks.callback=function(a){return d[parseInt(a,10)]||""}}a.options.scales.yAxes[c].stacked=this._isStacked()}.bind(this));a.options.tooltips={callbacks:{label:this._makeTooltip.bind(this)}};a.options.maintainAspectRatio=c;return a};b.init=function(b,e,f,g){c=f;d=g;new a(b,e)};return b}); -//# sourceMappingURL=chart_output_chartjs.min.js.map +/** + * Chart output for chart.js with custom override for aspect config. + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/chart_output_chartjs",["core/chart_output_chartjs"],(function(Output){var ChartOutput={},aspectRatio=!1,rtLegendoptions=!1;return Output.prototype._makeConfig=function(){var config={type:this._getChartType(),data:{labels:this._cleanData(this._chart.getLabels()),datasets:this._makeDatasetsConfig()},options:{title:{display:null!==this._chart.getTitle(),text:this._cleanData(this._chart.getTitle())}}},legendOptions=this._chart.getLegendOptions();return legendOptions&&(config.options.legend=legendOptions),rtLegendoptions&&(config.options.legend=rtLegendoptions),this._chart.getXAxes().forEach(function(axis,i){var axisLabels=axis.getLabels();config.options.scales=config.options.scales||{},config.options.scales.xAxes=config.options.scales.xAxes||[],config.options.scales.xAxes[i]=this._makeAxisConfig(axis,"x",i),null!==axisLabels&&(config.options.scales.xAxes[i].ticks.callback=function(value,index){return axisLabels[index]||""}),config.options.scales.xAxes[i].stacked=this._isStacked()}.bind(this)),this._chart.getYAxes().forEach(function(axis,i){var axisLabels=axis.getLabels();config.options.scales=config.options.scales||{},config.options.scales.yAxes=config.options.scales.yAxes||[],config.options.scales.yAxes[i]=this._makeAxisConfig(axis,"y",i),null!==axisLabels&&(config.options.scales.yAxes[i].ticks.callback=function(value){return axisLabels[parseInt(value,10)]||""}),config.options.scales.yAxes[i].stacked=this._isStacked()}.bind(this)),config.options.tooltips={callbacks:{label:this._makeTooltip.bind(this)}},config.options.maintainAspectRatio=aspectRatio,config},ChartOutput.init=function(chartImage,ChartInst,aspect,legend){aspectRatio=aspect,rtLegendoptions=legend,new Output(chartImage,ChartInst)},ChartOutput})); + +//# sourceMappingURL=chart_output_chartjs.min.js.map \ No newline at end of file diff --git a/amd/build/chart_output_chartjs.min.js.map b/amd/build/chart_output_chartjs.min.js.map index 3791981..86cb9e0 100644 --- a/amd/build/chart_output_chartjs.min.js.map +++ b/amd/build/chart_output_chartjs.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/chart_output_chartjs.js"],"names":["define","Output","ChartOutput","aspectRatio","rtLegendoptions","prototype","_makeConfig","config","type","_getChartType","data","labels","_cleanData","_chart","getLabels","datasets","_makeDatasetsConfig","options","title","display","getTitle","text","legendOptions","getLegendOptions","legend","getXAxes","forEach","axis","i","axisLabels","scales","xAxes","_makeAxisConfig","ticks","callback","value","index","stacked","_isStacked","bind","getYAxes","yAxes","parseInt","tooltips","callbacks","label","_makeTooltip","maintainAspectRatio","init","chartImage","ChartInst","aspect"],"mappings":"AAsBAA,OAAM,yCAAC,CAAC,2BAAD,CAAD,CAAgC,SAASC,CAAT,CAAiB,IAK/CC,CAAAA,CAAW,CAAG,EALiC,CAM/CC,CAAW,GANoC,CAO/CC,CAAe,GAPgC,CAgBnDH,CAAM,CAACI,SAAP,CAAiBC,WAAjB,CAA+B,UAAW,IAClCC,CAAAA,CAAM,CAAG,CACTC,IAAI,CAAE,KAAKC,aAAL,EADG,CAETC,IAAI,CAAE,CACFC,MAAM,CAAE,KAAKC,UAAL,CAAg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B,CADA,CADW,CAA1B,CAMAhC,CAAM,CAACU,OAAP,CAAe8B,mBAAf,CAAqC5C,CAArC,CAEA,MAAOI,CAAAA,CACV,CA/DD,CAoEAL,CAAW,CAAC8C,IAAZ,CAAmB,SAASC,CAAT,CAAqBC,CAArB,CAAgCC,CAAhC,CAAwC3B,CAAxC,CAAgD,CAC/DrB,CAAW,CAAGgD,CAAd,CACA/C,CAAe,CAAGoB,CAAlB,CACA,GAAIvB,CAAAA,CAAJ,CAAWgD,CAAX,CAAuBC,CAAvB,CACH,CAJD,CAMA,MAAOhD,CAAAA,CAEV,CA5FK,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 with custom override for aspect config.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['core/chart_output_chartjs'], function(Output) {\n\n /**\n * Module level variables.\n */\n var ChartOutput = {};\n var aspectRatio = false;\n var rtLegendoptions = false;\n\n /**\n * Overrride the 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 // Override legend options with those provided at run time.\n if (rtLegendoptions) {\n config.options.legend = rtLegendoptions;\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 config.options.maintainAspectRatio = aspectRatio;\n\n return config;\n };\n\n /**\n * Get the aspect ratio setting and initialise the chart.\n */\n ChartOutput.init = function(chartImage, ChartInst, aspect, legend) {\n aspectRatio = aspect;\n rtLegendoptions = legend;\n new Output(chartImage, ChartInst);\n };\n\n return ChartOutput;\n\n});\n"],"file":"chart_output_chartjs.min.js"} \ No newline at end of file +{"version":3,"file":"chart_output_chartjs.min.js","sources":["../src/chart_output_chartjs.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Chart output for chart.js with custom override for aspect config.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\ndefine(['core/chart_output_chartjs'], function (Output) {\n\n /**\n * Module level variables.\n */\n var ChartOutput = {};\n var aspectRatio = false;\n var rtLegendoptions = false;\n\n /**\n * Overrride the 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 // Override legend options with those provided at run time.\n if (rtLegendoptions) {\n config.options.legend = rtLegendoptions;\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 config.options.maintainAspectRatio = aspectRatio;\n\n return config;\n };\n\n /**\n * Get the aspect ratio setting and initialise the chart.\n */\n ChartOutput.init = function (chartImage, ChartInst, aspect, legend) {\n aspectRatio = aspect;\n rtLegendoptions = legend;\n new Output(chartImage, ChartInst);\n };\n\n return ChartOutput;\n\n});\n"],"names":["define","Output","ChartOutput","aspectRatio","rtLegendoptions","prototype","_makeConfig","config","type","this","_getChartType","data","labels","_cleanData","_chart","getLabels","datasets","_makeDatasetsConfig","options","title","display","getTitle","text","legendOptions","getLegendOptions","legend","getXAxes","forEach","axis","i","axisLabels","scales","xAxes","_makeAxisConfig","ticks","callback","value","index","stacked","_isStacked","bind","getYAxes","yAxes","parseInt","tooltips","callbacks","label","_makeTooltip","maintainAspectRatio","init","chartImage","ChartInst","aspect"],"mappings":";;;;;;;AAsBAA,+CAAO,CAAC,8BAA8B,SAAUC,YAKxCC,YAAc,GACdC,aAAc,EACdC,iBAAkB,SAStBH,OAAOI,UAAUC,YAAc,eACvBC,OAAS,CACTC,KAAMC,KAAKC,gBACXC,KAAM,CACFC,OAAQH,KAAKI,WAAWJ,KAAKK,OAAOC,aACpCC,SAAUP,KAAKQ,uBAEnBC,QAAS,CACLC,MAAO,CACHC,QAAoC,OAA3BX,KAAKK,OAAOO,WACrBC,KAAMb,KAAKI,WAAWJ,KAAKK,OAAOO,eAI1CE,cAAgBd,KAAKK,OAAOU,0BAC5BD,gBACAhB,OAAOW,QAAQO,OAASF,eAIxBnB,kBACAG,OAAOW,QAAQO,OAASrB,sBAGvBU,OAAOY,WAAWC,QAAQ,SAAUC,KAAMC,OACvCC,WAAaF,KAAKb,YAEtBR,OAAOW,QAAQa,OAASxB,OAAOW,QAAQa,QAAU,GACjDxB,OAAOW,QAAQa,OAAOC,MAAQzB,OAAOW,QAAQa,OAAOC,OAAS,GAC7DzB,OAAOW,QAAQa,OAAOC,MAAMH,GAAKpB,KAAKwB,gBAAgBL,KAAM,IAAKC,GAE9C,OAAfC,aACAvB,OAAOW,QAAQa,OAAOC,MAAMH,GAAGK,MAAMC,SAAW,SAAUC,MAAOC,cACtDP,WAAWO,QAAU,KAGpC9B,OAAOW,QAAQa,OAAOC,MAAMH,GAAGS,QAAU7B,KAAK8B,cAChDC,KAAK/B,YAEFK,OAAO2B,WAAWd,QAAQ,SAAUC,KAAMC,OACvCC,WAAaF,KAAKb,YAEtBR,OAAOW,QAAQa,OAASxB,OAAOW,QAAQa,QAAU,GACjDxB,OAAOW,QAAQa,OAAOW,MAAQnC,OAAOW,QAAQa,OAAOW,OAAS,GAC7DnC,OAAOW,QAAQa,OAAOW,MAAMb,GAAKpB,KAAKwB,gBAAgBL,KAAM,IAAKC,GAE9C,OAAfC,aACAvB,OAAOW,QAAQa,OAAOW,MAAMb,GAAGK,MAAMC,SAAW,SAAUC,cAC/CN,WAAWa,SAASP,MAAO,MAAQ,KAGlD7B,OAAOW,QAAQa,OAAOW,MAAMb,GAAGS,QAAU7B,KAAK8B,cAChDC,KAAK/B,OAEPF,OAAOW,QAAQ0B,SAAW,CACtBC,UAAW,CACPC,MAAOrC,KAAKsC,aAAaP,KAAK/B,QAItCF,OAAOW,QAAQ8B,oBAAsB7C,YAE9BI,QAMXL,YAAY+C,KAAO,SAAUC,WAAYC,UAAWC,OAAQ3B,QACxDtB,YAAciD,OACdhD,gBAAkBqB,WACdxB,OAAOiD,WAAYC,YAGpBjD"} \ No newline at end of file diff --git a/amd/build/course_selector.min.js b/amd/build/course_selector.min.js index 396c4f3..b3a9f75 100644 --- a/amd/build/course_selector.min.js +++ b/amd/build/course_selector.min.js @@ -1,2 +1,12 @@ -define ("local_assessfreq/course_selector",["core/ajax","core/notification"],function(a,b){return{transport:function(c,d,e){a.call([{methodname:"local_assessfreq_get_courses",args:{query:d}}])[0].then(function(a){var b=JSON.parse(a);e(b)}).fail(function(){b.exception(new Error("Failed to get events"))})},processResults:function(a,b){var c=[];b.forEach(function(a){c.push({value:a.id,label:a.fullname})});return c}}}); -//# sourceMappingURL=course_selector.min.js.map +/** + * Frameworks datasource. + * + * This module is compatible with core/form-autocomplete. + * + * @packagetool_lpmigrate + * @copyright2016 Frédéric Massart - FMCorz.net + * @licensehttp://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/course_selector",["core/ajax","core/notification"],(function(Ajax,Notification){var CourseSelector={transport:function(selector,query,callback){Ajax.call([{methodname:"local_assessfreq_get_courses",args:{query:query}}])[0].then((response=>{let courseArray=JSON.parse(response);callback(courseArray)})).fail((()=>{Notification.exception(new Error("Failed to get events"))}))},processResults:function(selector,results){let options=[];return results.forEach((element=>{options.push({value:element.id,label:element.fullname})})),options}};return CourseSelector})); + +//# sourceMappingURL=course_selector.min.js.map \ No newline at end of file diff --git a/amd/build/course_selector.min.js.map b/amd/build/course_selector.min.js.map index 935ac51..21d71eb 100644 --- a/amd/build/course_selector.min.js.map +++ b/amd/build/course_selector.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/course_selector.js"],"names":["define","Ajax","Notification","transport","selector","query","callback","call","methodname","args","then","response","courseArray","JSON","parse","fail","exception","Error","processResults","results","options","forEach","element","push","value","id","label","fullname"],"mappings":"AAyBAA,OAAM,oCAAC,CAAC,WAAD,CAAc,mBAAd,CAAD,CAAqC,SAASC,CAAT,CAAeC,CAAf,CAA6B,CAgDpE,MA3CqB,CAUNC,SAVM,CAUM,SAASC,CAAT,CAAmBC,CAAnB,CAA0BC,CAA1B,CAAoC,CAC3DL,CAAI,CAACM,IAAL,CAAU,CAAC,CACPC,UAAU,CAAE,8BADL,CAEPC,IAAI,CAAE,CACFJ,KAAK,CAAEA,CADL,CAFC,CAAD,CAAV,EAKI,CALJ,EAKOK,IALP,CAKY,SAACC,CAAD,CAAc,CACtB,GAAIC,CAAAA,CAAW,CAAGC,IAAI,CAACC,KAAL,CAAWH,CAAX,CAAlB,CACAL,CAAQ,CAACM,CAAD,CACX,CARD,EAQGG,IARH,CAQQ,UAAM,CACVb,CAAY,CAACc,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,sBAAV,CAAvB,CACH,CAVD,CAWH,CAtBoB,CA+BNC,cA/BM,CA+BW,SAASd,CAAT,CAAmBe,CAAnB,CAA4B,CACxD,GAAIC,CAAAA,CAAO,CAAG,EAAd,CACAD,CAAO,CAACE,OAAR,CAAgB,SAACC,CAAD,CAAa,CACzBF,CAAO,CAACG,IAAR,CAAa,CACTC,KAAK,CAAEF,CAAO,CAACG,EADN,CAETC,KAAK,CAAEJ,CAAO,CAACK,QAFN,CAAb,CAIH,CALD,EAOA,MAAOP,CAAAA,CACV,CAzCoB,CA4CxB,CAjDK,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 * Frameworks datasource.\n *\n * This module is compatible with core/form-autocomplete.\n *\n * @packagetool_lpmigrate\n * @copyright2016 Frédéric Massart - FMCorz.net\n * @licensehttp://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/ajax', 'core/notification'], function(Ajax, Notification) {\n\n /**\n * Module level variables.\n */\n var CourseSelector = {};\n\n /**\n * Source of data for Ajax element.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {String} query The query string.\n * @param {Function} callback A callback function receiving an array of results.\n * @return {Void}\n */\n CourseSelector.transport = function(selector, query, callback) {\n Ajax.call([{\n methodname: 'local_assessfreq_get_courses',\n args: {\n query: query\n },\n }])[0].then((response) => {\n let courseArray = JSON.parse(response);\n callback(courseArray);\n }).fail(() => {\n Notification.exception(new Error('Failed to get events'));\n });\n };\n\n /**\n * Process the results for auto complete elements.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {Array} results An array or results.\n * @return {Array} New array of results.\n */\n CourseSelector.processResults = function(selector, results) {\n let options = [];\n results.forEach((element) => {\n options.push({\n value: element.id,\n label: element.fullname\n });\n });\n\n return options;\n };\n\n return CourseSelector;\n});\n"],"file":"course_selector.min.js"} \ No newline at end of file +{"version":3,"file":"course_selector.min.js","sources":["../src/course_selector.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle.If not, see .\n\n/**\n * Frameworks datasource.\n *\n * This module is compatible with core/form-autocomplete.\n *\n * @packagetool_lpmigrate\n * @copyright2016 Frédéric Massart - FMCorz.net\n * @licensehttp://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/ajax', 'core/notification'], function (Ajax, Notification) {\n\n /**\n * Module level variables.\n */\n var CourseSelector = {};\n\n /**\n * Source of data for Ajax element.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {String} query The query string.\n * @param {Function} callback A callback function receiving an array of results.\n * @return {Void}\n */\n CourseSelector.transport = function (selector, query, callback) {\n Ajax.call([{\n methodname: 'local_assessfreq_get_courses',\n args: {\n query: query\n },\n }])[0].then((response) => {\n let courseArray = JSON.parse(response);\n callback(courseArray);\n }).fail(() => {\n Notification.exception(new Error('Failed to get events'));\n });\n };\n\n /**\n * Process the results for auto complete elements.\n *\n * @param {String} selector The selector of the auto complete element.\n * @param {Array} results An array or results.\n * @return {Array} New array of results.\n */\n CourseSelector.processResults = function (selector, results) {\n let options = [];\n results.forEach((element) => {\n options.push({\n value: element.id,\n label: element.fullname\n });\n });\n\n return options;\n };\n\n return CourseSelector;\n});\n"],"names":["define","Ajax","Notification","CourseSelector","selector","query","callback","call","methodname","args","then","response","courseArray","JSON","parse","fail","exception","Error","results","options","forEach","element","push","value","id","label","fullname"],"mappings":";;;;;;;;;AAyBAA,0CAAO,CAAC,YAAa,sBAAsB,SAAUC,KAAMC,kBAKnDC,eAAiB,CAUrBA,UAA2B,SAAUC,SAAUC,MAAOC,UAClDL,KAAKM,KAAK,CAAC,CACPC,WAAY,+BACZC,KAAM,CACFJ,MAAOA,UAEX,GAAGK,MAAMC,eACLC,YAAcC,KAAKC,MAAMH,UAC7BL,SAASM,gBACVG,MAAK,KACJb,aAAac,UAAU,IAAIC,MAAM,6BAWzCd,eAAgC,SAAUC,SAAUc,aAC5CC,QAAU,UACdD,QAAQE,SAASC,UACbF,QAAQG,KAAK,CACTC,MAAOF,QAAQG,GACfC,MAAOJ,QAAQK,cAIhBP,iBAGJhB"} \ No newline at end of file diff --git a/amd/build/dashboard_assessment.min.js b/amd/build/dashboard_assessment.min.js index 5747a61..835c060 100644 --- a/amd/build/dashboard_assessment.min.js +++ b/amd/build/dashboard_assessment.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/dashboard_assessment",["exports","core/notification","local_assessfreq/calendar","local_assessfreq/chart_data","local_assessfreq/dayview","local_assessfreq/user_preferences","local_assessfreq/zoom_modal"],function(a,b,c,d,e,f,g){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=void 0;b=j(b);c=j(c);d=i(d);e=j(e);f=i(f);g=j(g);function h(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;h=function(){return a};return a}function i(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=h();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;if(f&&(f.get||f.set)){Object.defineProperty(c,e,f)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function j(a){return a&&a.__esModule?a:{default:a}}var k,l,m,n,o,p="",q="",r=[{cardId:"local-assessfreq-assess-due-month",call:"assess_by_month"},{cardId:"local-assessfreq-assess-by-activity",call:"assess_by_activity"},{cardId:"local-assessfreq-assess-due-month-student",call:"assess_by_month_student"}],s=function(a){a.preventDefault();var b=a.target;if("a"===b.tagName.toLowerCase()&&b.dataset.year!==l){l=b.dataset.year;f.setUserPreference("local_assessfreq_overview_year_preference",l);var c=document.getElementById("local-assessfreq-report-overview").getElementsByClassName("local-assessfreq-year")[0];c.innerHTML=l;d.getCardCharts(0,null,l)}},t=function(){clearTimeout(o);o=setTimeout(x(),750)},u=function(a){var b=a.target;if("td"===b.tagName.toLowerCase()&&"true"===b.dataset.event){e.default.display(b.dataset.date)}},v=function(){var a=JSON.parse(q),d=parseInt(a.year),e=a.metric,f=a.modules,g=document.getElementById("local-assessfreq-report-heatmap"),h=g.getElementsByClassName("overlay-icon-container")[0];h.classList.remove("hide");c.default.generate(d,0,11,e,f).then(function(a){var b=document.getElementById("local-assessfreq-report-heatmap-months");b.innerHTML=a.innerHTML;b.addEventListener("click",u)}).then(c.default.createHeatScale).then(function(a){var b=document.getElementById("local-assessfreq-report-heatmap-scale");b.innerHTML=a.outerHTML;h.classList.add("hide")}).catch(function(){b.default.exception(new Error("Failed to calendar."))})},w=function(a){var b=a.year,c=a.metric,d=a.modules,e=document.getElementById("local-assessfreq-heatmap-form"),f=e.elements,g=[];if(0===d.length){d=["all"]}for(var l=0;l + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */var contextid,yearselect,yearselectheatmap,metricselectheatmap,timeout;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_notification=_interopRequireDefault(_notification),_calendar=_interopRequireDefault(_calendar),ChartData=_interopRequireWildcard(ChartData),_dayview=_interopRequireDefault(_dayview),UserPreference=_interopRequireWildcard(UserPreference),_zoom_modal=_interopRequireDefault(_zoom_modal);var modulesJson="",heatmapOptionsJson="";const cards=[{cardId:"local-assessfreq-assess-due-month",call:"assess_by_month"},{cardId:"local-assessfreq-assess-by-activity",call:"assess_by_activity"},{cardId:"local-assessfreq-assess-due-month-student",call:"assess_by_month_student"}],yearButtonAction=event=>{event.preventDefault();var element=event.target;"a"===element.tagName.toLowerCase()&&element.dataset.year!==yearselect&&(yearselect=element.dataset.year,UserPreference.setUserPreference("local_assessfreq_overview_year_preference",yearselect),document.getElementById("local-assessfreq-report-overview").getElementsByClassName("local-assessfreq-year")[0].innerHTML=yearselect,ChartData.getCardCharts(0,null,yearselect))},updateHeatmapDebounce=()=>{clearTimeout(timeout),timeout=setTimeout(updateHeatmap(),750)},detailView=event=>{let element=event.target;"td"===element.tagName.toLowerCase()&&"true"===element.dataset.event&&_dayview.default.display(element.dataset.date)},updateHeatmap=()=>{for(var links=document.getElementById("local-assessfreq-heatmap-modules").getElementsByTagName("a"),modules=[],i=0;i{let heatmapOptions=JSON.parse(heatmapOptionsJson),year=parseInt(heatmapOptions.year),metric=heatmapOptions.metric,modules=heatmapOptions.modules,spinner=document.getElementById("local-assessfreq-report-heatmap").getElementsByClassName("overlay-icon-container")[0];spinner.classList.remove("hide"),_calendar.default.generate(year,0,11,metric,modules).then((calendar=>{let calendarContainer=document.getElementById("local-assessfreq-report-heatmap-months");calendarContainer.innerHTML=calendar.innerHTML,calendarContainer.addEventListener("click",detailView)})).then(_calendar.default.createHeatScale).then((heatScale=>{document.getElementById("local-assessfreq-report-heatmap-scale").innerHTML=heatScale.outerHTML,spinner.classList.add("hide")})).catch((()=>{_notification.default.exception(new Error("Failed to calendar."))}))})(),(_ref=>{let{year:year,metric:metric,modules:modules}=_ref,downloadForm=document.getElementById("local-assessfreq-heatmap-form"),formElements=downloadForm.elements,toRemove=new Array;0===modules.length&&(modules=["all"]);for(let i=0;i{event.preventDefault();var element=event.target;"a"===element.tagName.toLowerCase()&&element.dataset.year!==yearselectheatmap&&(yearselectheatmap=element.dataset.year,UserPreference.setUserPreference("local_assessfreq_heatmap_year_preference",yearselectheatmap),document.getElementById("local-assessfreq-report-heatmap").getElementsByClassName("local-assessfreq-year")[0].innerHTML=yearselectheatmap,updateHeatmapDebounce())},metricHeatmapButtonAction=event=>{event.preventDefault();var element=event.target;"a"===element.tagName.toLowerCase()&&element.dataset.metric!==metricselectheatmap&&(metricselectheatmap=element.dataset.metric,UserPreference.setUserPreference("local_assessfreq_heatmap_metric_preference",metricselectheatmap),updateHeatmapDebounce())},triggerZoomGraph=event=>{let call=event.target.closest("div").dataset.call,params={data:JSON.stringify({year:yearselect,call:call})};_zoom_modal.default.zoomGraph(event,params,"get_chart")};_exports.init=context=>{contextid=context;let cardsYearSelectElement=document.getElementById("local-assessfreq-cards-year");yearselect=cardsYearSelectElement.getElementsByClassName("active")[0].dataset.year,cardsYearSelectElement.addEventListener("click",yearButtonAction);let cardsYearSelectHeatmapElement=document.getElementById("local-assessfreq-heatmap-year");yearselectheatmap=cardsYearSelectHeatmapElement.getElementsByClassName("active")[0].dataset.year,cardsYearSelectHeatmapElement.addEventListener("click",yearHeatmapButtonAction);let cardsMetricSelectHeatmapElement=document.getElementById("local-assessfreq-heatmap-metrics");metricselectheatmap=cardsMetricSelectHeatmapElement.getElementsByClassName("active")[0].dataset.metric,cardsMetricSelectHeatmapElement.addEventListener("click",metricHeatmapButtonAction),(element=>{for(var links=element.getElementsByTagName("a"),all=links[0],i=0;i.\n\n/**\n * Javascript for report card display and processing.\n *\n * @module local_assessfreq/dashboard_assessment\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Notification from 'core/notification';\nimport Calendar from 'local_assessfreq/calendar';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport Dayview from 'local_assessfreq/dayview';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport ZoomModal from 'local_assessfreq/zoom_modal';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar yearselect;\nvar yearselectheatmap;\nvar metricselectheatmap;\nvar timeout;\nvar modulesJson = '';\nvar heatmapOptionsJson = '';\n\nconst cards = [\n {cardId: 'local-assessfreq-assess-due-month', call: 'assess_by_month'},\n {cardId: 'local-assessfreq-assess-by-activity', call: 'assess_by_activity'},\n {cardId: 'local-assessfreq-assess-due-month-student', call: 'assess_by_month_student'}\n];\n\n/**\n * Get and process the selected year from the dropdown,\n * and update the corresponding user perference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst yearButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.year !== yearselect) { // Only act on certain elements.\n yearselect = element.dataset.year;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_overview_year_preference', yearselect);\n\n // Update card data based on selected year.\n var yeartitle = document.getElementById('local-assessfreq-report-overview')\n .getElementsByClassName('local-assessfreq-year')[0];\n yeartitle.innerHTML = yearselect;\n\n ChartData.getCardCharts(0, null, yearselect); // Process loading for the assessment cards.\n }\n};\n\n/**\n * Quick and dirty debounce method for the heatmap settings menu.\n * This stops the ajax method that updates the heatmap from being updated\n * while the user is still checking options.\n *\n */\nconst updateHeatmapDebounce = () => {\n clearTimeout(timeout);\n timeout = setTimeout(updateHeatmap(), 750);\n};\n\n/**\n * Display heatmap calendar.\n *\n * @param {event} event The triggered event for the element.\n */\nconst detailView = (event) => {\n let element = event.target;\n if (element.tagName.toLowerCase() === 'td' && element.dataset.event === 'true') { // Only act on certain elements.\n Dayview.display(element.dataset.date);\n }\n};\n\n/**\n * Start heatmap generation.\n *\n */\nconst generateHeatmap = () => {\n let heatmapOptions = JSON.parse(heatmapOptionsJson);\n let year = parseInt(heatmapOptions.year);\n let metric = heatmapOptions.metric;\n let modules = heatmapOptions.modules;\n let heatmapContainer = document.getElementById('local-assessfreq-report-heatmap');\n let spinner = heatmapContainer.getElementsByClassName('overlay-icon-container')[0];\n\n spinner.classList.remove('hide'); // Show spinner if not already shown.\n\n Calendar.generate(year, 0, 11, metric, modules)\n .then(calendar => {\n let calendarContainer = document.getElementById('local-assessfreq-report-heatmap-months');\n calendarContainer.innerHTML = calendar.innerHTML;\n calendarContainer.addEventListener('click', detailView);\n })\n .then(Calendar.createHeatScale)\n .then((heatScale) => {\n let heatScaleContainer = document.getElementById('local-assessfreq-report-heatmap-scale');\n heatScaleContainer.innerHTML = heatScale.outerHTML;\n spinner.classList.add('hide'); // Hide sinner if not already hidden.\n })\n .catch(() => {\n Notification.exception(new Error('Failed to calendar.'));\n return;\n });\n};\n\nconst updateDownload = ({year, metric, modules}) => {\n let downloadForm = document.getElementById('local-assessfreq-heatmap-form');\n let formElements = downloadForm.elements;\n let toRemove = new Array();\n\n if (modules.length === 0) {\n modules = ['all'];\n }\n\n for (let i = 0; i < formElements.length; i++) {\n if (formElements[i] === undefined) {\n continue;\n }\n // Update year field.\n if ((formElements[i].type === 'hidden') && (formElements[i].name === 'year')) {\n formElements[i].value = year;\n continue;\n }\n\n // Update metric field.\n if ((formElements[i].type === 'hidden') && (formElements[i].name === 'metric')) {\n formElements[i].value = metric;\n continue;\n }\n\n // Update module fields.\n if ((formElements[i].type === 'hidden') && (formElements[i].name.startsWith('modules'))) {\n toRemove.push(formElements[i]);\n continue;\n }\n }\n\n for (const element of toRemove) {\n element.remove();\n }\n\n for (let i = 0; i < modules.length; i++) {\n let input = document.createElement('input');\n input.type = 'hidden';\n input.name = 'modules[' + modules[i] + ']';\n input.value = modules[i];\n\n downloadForm.appendChild(input);\n }\n};\n\n/**\n * Update the heatmap based on the current filter settings.\n *\n */\nconst updateHeatmap = () => {\n // Get current state of select menu items.\n var cardsModulesSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-modules');\n var links = cardsModulesSelectHeatmapElement.getElementsByTagName('a');\n var modules = [];\n\n for (var i = 0; i < links.length; i++) {\n if (links[i].classList.contains('active')) {\n let module = links[i].dataset.module;\n modules.push(module);\n }\n }\n\n // Save selection as a user preference.\n if (modulesJson !== JSON.stringify(modules)) {\n modulesJson = JSON.stringify(modules);\n UserPreference.setUserPreference('local_assessfreq_heatmap_modules_preference', modulesJson);\n }\n\n // Build settings object.\n var optionsObj = {\n 'year': yearselectheatmap,\n 'metric': metricselectheatmap,\n 'modules': modules\n };\n\n var optionsJson = JSON.stringify(optionsObj);\n\n if (optionsJson !== heatmapOptionsJson) { // Compare to global to see if there are any changes.\n // If list has changed fetch heatmap and update user preference.\n heatmapOptionsJson = optionsJson;\n generateHeatmap();\n\n // Update the download options.\n updateDownload(optionsObj);\n }\n};\n\n/**\n * Get and process the selected year from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst yearHeatmapButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.year !== yearselectheatmap) { // Only act on certain elements.\n yearselectheatmap = element.dataset.year;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_heatmap_year_preference', yearselectheatmap);\n\n // Update card data based on selected year.\n var yeartitle = document.getElementById('local-assessfreq-report-heatmap')\n .getElementsByClassName('local-assessfreq-year')[0];\n yeartitle.innerHTML = yearselectheatmap;\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n }\n};\n\n/**\n * Get and process the selected assessment metric from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst metricHeatmapButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.metric !== metricselectheatmap) {\n metricselectheatmap = element.dataset.metric;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_heatmap_metric_preference', metricselectheatmap);\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n }\n};\n\n/**\n * Add the event listeners to the modules in the module select dropdown.\n *\n * @param {Object} element The dropdown HTML element that contains the list of modules as links.\n */\nconst moduleListChildrenEvents = (element) => {\n var links = element.getElementsByTagName('a');\n var all = links[0];\n\n for (var i = 0; i < links.length; i++) {\n let module = links[i].dataset.module;\n\n if (module.toLowerCase() === 'all') {\n links[i].addEventListener('click', function(event){\n event.preventDefault();\n // Remove active class from all other links.\n for (var j = 0; j < links.length; j++) {\n links[j].classList.remove('active');\n }\n updateHeatmapDebounce(); // Call function to update heatmap.\n });\n } else if (module.toLowerCase() === 'close') {\n links[i].addEventListener('click', function(event){\n event.preventDefault();\n event.stopPropagation();\n\n var dropdownmenu = document.getElementById('local-assessfreq-heatmap-modules-filter');\n dropdownmenu.classList.remove('show');\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n });\n\n } else {\n links[i].addEventListener('click', function(event){\n event.preventDefault();\n event.stopPropagation();\n\n all.classList.remove('active');\n\n event.target.classList.toggle('active');\n updateHeatmapDebounce();\n });\n }\n\n }\n};\n\n/**\n * Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'year': yearselect, 'call': call})};\n let method = 'get_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Initialise method for report card rendering.\n *\n * @param {integer} context The current context id.\n */\nexport const init = (context) => {\n contextid = context;\n\n // Set up event listener and related actions for year dropdown on report cards.\n let cardsYearSelectElement = document.getElementById('local-assessfreq-cards-year');\n yearselect = cardsYearSelectElement.getElementsByClassName('active')[0].dataset.year;\n cardsYearSelectElement.addEventListener('click', yearButtonAction);\n\n // Set up event listener and related actions for year dropdown on heatmp.\n let cardsYearSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-year');\n yearselectheatmap = cardsYearSelectHeatmapElement.getElementsByClassName('active')[0].dataset.year;\n cardsYearSelectHeatmapElement.addEventListener('click', yearHeatmapButtonAction);\n\n // Set up event listener and related actions for metric dropdown on heatmp.\n let cardsMetricSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-metrics');\n metricselectheatmap = cardsMetricSelectHeatmapElement.getElementsByClassName('active')[0].dataset.metric;\n cardsMetricSelectHeatmapElement.addEventListener('click', metricHeatmapButtonAction);\n\n // Set up event listener and related actions for module dropdown on heatmp.\n let cardsModulesSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-modules');\n moduleListChildrenEvents(cardsModulesSelectHeatmapElement);\n\n // Set up zoom event listeners.\n let dueMonthZoom = document.getElementById('local-assessfreq-assess-due-month-zoom');\n dueMonthZoom.addEventListener('click', triggerZoomGraph);\n\n let dueActivityZoom = document.getElementById('local-assessfreq-assess-by-activity-zoom');\n dueActivityZoom.addEventListener('click', triggerZoomGraph);\n\n let dueStudentZoom = document.getElementById('local-assessfreq-assess-due-month-student-zoom');\n dueStudentZoom.addEventListener('click', triggerZoomGraph);\n\n // Create the zoom modal.\n ZoomModal.init(context);\n\n // Setup the dayview modal.\n Dayview.init();\n\n // Setup the chart data for each card.\n ChartData.init(cards, contextid, 'get_chart', 'core/chart');\n\n // Process loading for the assessment cards.\n ChartData.getCardCharts(0, null, yearselect);\n\n // Get the data for the heatmap.\n updateHeatmap();\n\n};\n"],"file":"dashboard_assessment.min.js"} \ No newline at end of file +{"version":3,"file":"dashboard_assessment.min.js","sources":["../src/dashboard_assessment.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for report card display and processing.\n *\n * @module local_assessfreq/dashboard_assessment\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Notification from 'core/notification';\nimport Calendar from 'local_assessfreq/calendar';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport Dayview from 'local_assessfreq/dayview';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport ZoomModal from 'local_assessfreq/zoom_modal';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar yearselect;\nvar yearselectheatmap;\nvar metricselectheatmap;\nvar timeout;\nvar modulesJson = '';\nvar heatmapOptionsJson = '';\n\nconst cards = [\n {cardId: 'local-assessfreq-assess-due-month', call: 'assess_by_month'},\n {cardId: 'local-assessfreq-assess-by-activity', call: 'assess_by_activity'},\n {cardId: 'local-assessfreq-assess-due-month-student', call: 'assess_by_month_student'}\n];\n\n/**\n * Get and process the selected year from the dropdown,\n * and update the corresponding user perference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst yearButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.year !== yearselect) { // Only act on certain elements.\n yearselect = element.dataset.year;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_overview_year_preference', yearselect);\n\n // Update card data based on selected year.\n var yeartitle = document.getElementById('local-assessfreq-report-overview')\n .getElementsByClassName('local-assessfreq-year')[0];\n yeartitle.innerHTML = yearselect;\n\n ChartData.getCardCharts(0, null, yearselect); // Process loading for the assessment cards.\n }\n};\n\n/**\n * Quick and dirty debounce method for the heatmap settings menu.\n * This stops the ajax method that updates the heatmap from being updated\n * while the user is still checking options.\n *\n */\nconst updateHeatmapDebounce = () => {\n clearTimeout(timeout);\n timeout = setTimeout(updateHeatmap(), 750);\n};\n\n/**\n * Display heatmap calendar.\n *\n * @param {event} event The triggered event for the element.\n */\nconst detailView = (event) => {\n let element = event.target;\n if (element.tagName.toLowerCase() === 'td' && element.dataset.event === 'true') { // Only act on certain elements.\n Dayview.display(element.dataset.date);\n }\n};\n\n/**\n * Start heatmap generation.\n *\n */\nconst generateHeatmap = () => {\n let heatmapOptions = JSON.parse(heatmapOptionsJson);\n let year = parseInt(heatmapOptions.year);\n let metric = heatmapOptions.metric;\n let modules = heatmapOptions.modules;\n let heatmapContainer = document.getElementById('local-assessfreq-report-heatmap');\n let spinner = heatmapContainer.getElementsByClassName('overlay-icon-container')[0];\n\n spinner.classList.remove('hide'); // Show spinner if not already shown.\n\n Calendar.generate(year, 0, 11, metric, modules)\n .then(calendar => {\n let calendarContainer = document.getElementById('local-assessfreq-report-heatmap-months');\n calendarContainer.innerHTML = calendar.innerHTML;\n calendarContainer.addEventListener('click', detailView);\n })\n .then(Calendar.createHeatScale)\n .then((heatScale) => {\n let heatScaleContainer = document.getElementById('local-assessfreq-report-heatmap-scale');\n heatScaleContainer.innerHTML = heatScale.outerHTML;\n spinner.classList.add('hide'); // Hide sinner if not already hidden.\n })\n .catch(() => {\n Notification.exception(new Error('Failed to calendar.'));\n return;\n });\n};\n\nconst updateDownload = ({year, metric, modules}) => {\n let downloadForm = document.getElementById('local-assessfreq-heatmap-form');\n let formElements = downloadForm.elements;\n let toRemove = new Array();\n\n if (modules.length === 0) {\n modules = ['all'];\n }\n\n for (let i = 0; i < formElements.length; i++) {\n if (formElements[i] === undefined) {\n continue;\n }\n // Update year field.\n if ((formElements[i].type === 'hidden') && (formElements[i].name === 'year')) {\n formElements[i].value = year;\n continue;\n }\n\n // Update metric field.\n if ((formElements[i].type === 'hidden') && (formElements[i].name === 'metric')) {\n formElements[i].value = metric;\n continue;\n }\n\n // Update module fields.\n if ((formElements[i].type === 'hidden') && (formElements[i].name.startsWith('modules'))) {\n toRemove.push(formElements[i]);\n continue;\n }\n }\n\n for (const element of toRemove) {\n element.remove();\n }\n\n for (let i = 0; i < modules.length; i++) {\n let input = document.createElement('input');\n input.type = 'hidden';\n input.name = 'modules[' + modules[i] + ']';\n input.value = modules[i];\n\n downloadForm.appendChild(input);\n }\n};\n\n/**\n * Update the heatmap based on the current filter settings.\n *\n */\nconst updateHeatmap = () => {\n // Get current state of select menu items.\n var cardsModulesSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-modules');\n var links = cardsModulesSelectHeatmapElement.getElementsByTagName('a');\n var modules = [];\n\n for (var i = 0; i < links.length; i++) {\n if (links[i].classList.contains('active')) {\n let module = links[i].dataset.module;\n modules.push(module);\n }\n }\n\n // Save selection as a user preference.\n if (modulesJson !== JSON.stringify(modules)) {\n modulesJson = JSON.stringify(modules);\n UserPreference.setUserPreference('local_assessfreq_heatmap_modules_preference', modulesJson);\n }\n\n // Build settings object.\n var optionsObj = {\n 'year': yearselectheatmap,\n 'metric': metricselectheatmap,\n 'modules': modules\n };\n\n var optionsJson = JSON.stringify(optionsObj);\n\n if (optionsJson !== heatmapOptionsJson) { // Compare to global to see if there are any changes.\n // If list has changed fetch heatmap and update user preference.\n heatmapOptionsJson = optionsJson;\n generateHeatmap();\n\n // Update the download options.\n updateDownload(optionsObj);\n }\n};\n\n/**\n * Get and process the selected year from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst yearHeatmapButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.year !== yearselectheatmap) { // Only act on certain elements.\n yearselectheatmap = element.dataset.year;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_heatmap_year_preference', yearselectheatmap);\n\n // Update card data based on selected year.\n var yeartitle = document.getElementById('local-assessfreq-report-heatmap')\n .getElementsByClassName('local-assessfreq-year')[0];\n yeartitle.innerHTML = yearselectheatmap;\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n }\n};\n\n/**\n * Get and process the selected assessment metric from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {event} event The triggered event for the element.\n */\nconst metricHeatmapButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.metric !== metricselectheatmap) {\n metricselectheatmap = element.dataset.metric;\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_heatmap_metric_preference', metricselectheatmap);\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n }\n};\n\n/**\n * Add the event listeners to the modules in the module select dropdown.\n *\n * @param {Object} element The dropdown HTML element that contains the list of modules as links.\n */\nconst moduleListChildrenEvents = (element) => {\n var links = element.getElementsByTagName('a');\n var all = links[0];\n\n for (var i = 0; i < links.length; i++) {\n let module = links[i].dataset.module;\n\n if (module.toLowerCase() === 'all') {\n links[i].addEventListener('click', function (event) {\n event.preventDefault();\n // Remove active class from all other links.\n for (var j = 0; j < links.length; j++) {\n links[j].classList.remove('active');\n }\n updateHeatmapDebounce(); // Call function to update heatmap.\n });\n } else if (module.toLowerCase() === 'close') {\n links[i].addEventListener('click', function (event) {\n event.preventDefault();\n event.stopPropagation();\n\n var dropdownmenu = document.getElementById('local-assessfreq-heatmap-modules-filter');\n dropdownmenu.classList.remove('show');\n\n updateHeatmapDebounce(); // Call function to update heatmap.\n });\n } else {\n links[i].addEventListener('click', function (event) {\n event.preventDefault();\n event.stopPropagation();\n\n all.classList.remove('active');\n\n event.target.classList.toggle('active');\n updateHeatmapDebounce();\n });\n }\n }\n};\n\n/**\n * Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'year': yearselect, 'call': call})};\n let method = 'get_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Initialise method for report card rendering.\n *\n * @param {integer} context The current context id.\n */\nexport const init = (context) => {\n contextid = context;\n\n // Set up event listener and related actions for year dropdown on report cards.\n let cardsYearSelectElement = document.getElementById('local-assessfreq-cards-year');\n yearselect = cardsYearSelectElement.getElementsByClassName('active')[0].dataset.year;\n cardsYearSelectElement.addEventListener('click', yearButtonAction);\n\n // Set up event listener and related actions for year dropdown on heatmp.\n let cardsYearSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-year');\n yearselectheatmap = cardsYearSelectHeatmapElement.getElementsByClassName('active')[0].dataset.year;\n cardsYearSelectHeatmapElement.addEventListener('click', yearHeatmapButtonAction);\n\n // Set up event listener and related actions for metric dropdown on heatmp.\n let cardsMetricSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-metrics');\n metricselectheatmap = cardsMetricSelectHeatmapElement.getElementsByClassName('active')[0].dataset.metric;\n cardsMetricSelectHeatmapElement.addEventListener('click', metricHeatmapButtonAction);\n\n // Set up event listener and related actions for module dropdown on heatmp.\n let cardsModulesSelectHeatmapElement = document.getElementById('local-assessfreq-heatmap-modules');\n moduleListChildrenEvents(cardsModulesSelectHeatmapElement);\n\n // Set up zoom event listeners.\n let dueMonthZoom = document.getElementById('local-assessfreq-assess-due-month-zoom');\n dueMonthZoom.addEventListener('click', triggerZoomGraph);\n\n let dueActivityZoom = document.getElementById('local-assessfreq-assess-by-activity-zoom');\n dueActivityZoom.addEventListener('click', triggerZoomGraph);\n\n let dueStudentZoom = document.getElementById('local-assessfreq-assess-due-month-student-zoom');\n dueStudentZoom.addEventListener('click', triggerZoomGraph);\n\n // Create the zoom modal.\n ZoomModal.init(context);\n\n // Setup the dayview modal.\n Dayview.init();\n\n // Setup the chart data for each card.\n ChartData.init(cards, contextid, 'get_chart', 'core/chart');\n\n // Process loading for the assessment cards.\n ChartData.getCardCharts(0, null, yearselect);\n\n // Get the data for the heatmap.\n updateHeatmap();\n\n};\n"],"names":["contextid","yearselect","yearselectheatmap","metricselectheatmap","timeout","modulesJson","heatmapOptionsJson","cards","cardId","call","yearButtonAction","event","preventDefault","element","target","tagName","toLowerCase","dataset","year","UserPreference","setUserPreference","document","getElementById","getElementsByClassName","innerHTML","ChartData","getCardCharts","updateHeatmapDebounce","clearTimeout","setTimeout","updateHeatmap","detailView","display","date","links","getElementsByTagName","modules","i","length","classList","contains","module","push","JSON","stringify","optionsObj","optionsJson","heatmapOptions","parse","parseInt","metric","spinner","remove","generate","then","calendar","calendarContainer","addEventListener","Calendar","createHeatScale","heatScale","outerHTML","add","catch","exception","Error","generateHeatmap","_ref","downloadForm","formElements","elements","toRemove","Array","undefined","type","name","startsWith","value","input","createElement","appendChild","updateDownload","yearHeatmapButtonAction","metricHeatmapButtonAction","triggerZoomGraph","closest","params","zoomGraph","context","cardsYearSelectElement","cardsYearSelectHeatmapElement","cardsMetricSelectHeatmapElement","all","j","stopPropagation","toggle","moduleListChildrenEvents","init"],"mappings":";;;;;;;;SAkCIA,UACAC,WACAC,kBACAC,oBACAC,uXACAC,YAAc,GACdC,mBAAqB,SAEnBC,MAAQ,CACV,CAACC,OAAQ,oCAAqCC,KAAM,mBACpD,CAACD,OAAQ,sCAAuCC,KAAM,sBACtD,CAACD,OAAQ,4CAA6CC,KAAM,4BAS1DC,iBAAoBC,QACtBA,MAAMC,qBACFC,QAAUF,MAAMG,OAEkB,MAAlCD,QAAQE,QAAQC,eAAyBH,QAAQI,QAAQC,OAASjB,aAClEA,WAAaY,QAAQI,QAAQC,KAG7BC,eAAeC,kBAAkB,4CAA6CnB,YAG9DoB,SAASC,eAAe,oCACnCC,uBAAuB,yBAAyB,GAC3CC,UAAYvB,WAEtBwB,UAAUC,cAAc,EAAG,KAAMzB,cAUnC0B,sBAAwB,KAC1BC,aAAaxB,SACbA,QAAUyB,WAAWC,gBAAiB,MAQpCC,WAAcpB,YACZE,QAAUF,MAAMG,OACkB,OAAlCD,QAAQE,QAAQC,eAAoD,SAA1BH,QAAQI,QAAQN,wBAClDqB,QAAQnB,QAAQI,QAAQgB,OAsFlCH,cAAgB,aAGdI,MADmCb,SAASC,eAAe,oCAClBa,qBAAqB,KAC9DC,QAAU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board_quiz.min.js b/amd/build/dashboard_quiz.min.js index 544d244..85e7f24 100644 --- a/amd/build/dashboard_quiz.min.js +++ b/amd/build/dashboard_quiz.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/dashboard_quiz",["exports","core/ajax","core/notification","core/str","core/templates","local_assessfreq/chart_data","local_assessfreq/form_modal","local_assessfreq/override_modal","local_assessfreq/table_handler","local_assessfreq/user_preferences","local_assessfreq/zoom_modal"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=void 0;b=n(b);c=n(c);d=m(d);e=n(e);f=m(f);g=m(g);h=n(h);i=m(i);j=m(j);k=m(k);function l(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;l=function(){return a};return a}function m(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=l();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;if(f&&(f.get||f.set)){Object.defineProperty(c,e,f)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function n(a){return a&&a.__esModule?a:{default:a}}var o="",p,q=0,r=60,s,t=[{cardId:"local-assessfreq-quiz-summary-graph",call:"participant_summary",aspect:!0},{cardId:"local-assessfreq-quiz-summary-trend",call:"participant_trend",aspect:!1}],u=function(){var a=0";g.innerHTML=b.name+" ";g.appendChild(s);var t=new URL(window.location.href),v=t.origin+t.pathname+"?id="+q;history.pushState({},"",v);d.get_string("dashboard:quiztitle","local_assessfreq",{quiz:b.name,course:b.courseshortname}).then(function(a){document.title=a}).catch(function(){c.default.exception(new Error("Failed to load string: dashboard:quiztitle"))});e.default.render("local_assessfreq/quiz-summary-card-content",b).done(function(a){l.classList.add("hide");var b=document.getElementById("local-assessfreq-quiz-summary-card-content");e.default.replaceNodeContents(b,a,"")}).fail(function(){c.default.exception(new Error("Failed to load quiz summary template."))});h.classList.remove("hide");j.classList.remove("hide");m.classList.remove("hide");n.classList.remove("hide");f.getCardCharts(q);i.getTable(q);u();o.addEventListener("keyup",i.tableSearch);o.addEventListener("paste",i.tableSearch);p.addEventListener("click",i.tableSearchReset);r.addEventListener("click",i.tableSearchRowSet)}).fail(function(){c.default.exception(new Error("Failed to get quiz data"))})},w=function(a){a.preventDefault();var b=a.target;if(null!==b.closest("button")&&"local-assessfreq-refresh-quiz-dashboard"===b.closest("button").id){u(!0);v(q)}else if("a"===b.tagName.toLowerCase()){r=b.dataset.period;u(!0);j.setUserPreference("local_assessfreq_quiz_refresh_preference",r)}},x=function(a){var b=a.target.closest("div").dataset.call,c={data:JSON.stringify({quiz:q,call:b})};k.zoomGraph(a,c,"get_quiz_chart")},y=function(a,b){p=a;g.init(a,v);k.init(a);h.default.init(a,v);i.init(q,p,"local-assessfreq-quiz-student-table","local-assessfreq-quiz-table","get_student_table","local_assessfreq_quiz_table_rows_preference","local-assessfreq-quiz-student-table-search","local_assessfreq_student_table","local_assessfreq_set_table_preference");f.init(t,a,"get_quiz_chart","local_assessfreq/chart");d.get_string("loadingquiztitle","local_assessfreq").then(function(a){o=a}).catch(function(){c.default.exception(new Error("Failed to load string: loadingquiz"))}).then(function(){if(0 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification),Str=_interopRequireWildcard(Str),_templates=_interopRequireDefault(_templates),ChartData=_interopRequireWildcard(ChartData),FormModal=_interopRequireWildcard(FormModal),_override_modal=_interopRequireDefault(_override_modal),TableHandler=_interopRequireWildcard(TableHandler),UserPreference=_interopRequireWildcard(UserPreference),ZoomModal=_interopRequireWildcard(ZoomModal);var contextid,counterid,selectQuizStr="",quizId=0,refreshPeriod=60;const cards=[{cardId:"local-assessfreq-quiz-summary-graph",call:"participant_summary",aspect:!0},{cardId:"local-assessfreq-quiz-summary-trend",call:"participant_trend",aspect:!1}],refreshCounter=function(){let reset=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],progressElement=document.getElementById("local-assessfreq-period-progress");!0===reset&&(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100)),counterid||(counterid=setInterval((()=>{let progressWidthAria=progressElement.getAttribute("aria-valuenow");const progressStep=100/refreshPeriod;progressWidthAria-progressStep>0?(progressElement.setAttribute("style","width: "+(progressWidthAria-progressStep)+"%"),progressElement.setAttribute("aria-valuenow",progressWidthAria-progressStep)):(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100),processDashboard(quizId),refreshCounter())}),1e3))},processDashboard=quiz=>{quizId=quiz;let titleElement=document.getElementById("local-assessfreq-quiz-title");titleElement.innerHTML=selectQuizStr,_ajax.default.call([{methodname:"local_assessfreq_get_quiz_data",args:{quizid:quiz}}])[0].then((response=>{let quizArray=JSON.parse(response),cardsElement=document.getElementById("local-assessfreq-quiz-dashboard-cards-deck"),trendElement=document.getElementById("local-assessfreq-quiz-dashboard-participant-trend-deck"),summarySpinner=document.getElementById("local-assessfreq-quiz-summary-card").getElementsByClassName("overlay-icon-container")[0],tableElement=document.getElementById("local-assessfreq-quiz-table"),periodElement=document.getElementById("local-assessfreq-period-container"),tableSearchInputElement=document.getElementById("local-assessfreq-quiz-student-table-search"),tableSearchResetElement=document.getElementById("local-assessfreq-quiz-student-table-search-reset"),tableSearchRowsElement=document.getElementById("local-assessfreq-quiz-student-table-rows"),quizLink=document.createElement("a");quizLink.href=quizArray.url,quizLink.innerHTML='',titleElement.innerHTML=quizArray.name+" ",titleElement.appendChild(quizLink);const currentdUrl=new URL(window.location.href),newUrl=currentdUrl.origin+currentdUrl.pathname+"?id="+quizId;history.pushState({},"",newUrl),Str.get_string("dashboard:quiztitle","local_assessfreq",{quiz:quizArray.name,course:quizArray.courseshortname}).then((str=>{document.title=str})),_templates.default.render("local_assessfreq/quiz-summary-card-content",quizArray).done((html=>{summarySpinner.classList.add("hide");let contentcontainer=document.getElementById("local-assessfreq-quiz-summary-card-content");_templates.default.replaceNodeContents(contentcontainer,html,"")})).fail((()=>{_notification.default.exception(new Error("Failed to load quiz summary template."))})),cardsElement.classList.remove("hide"),trendElement.classList.remove("hide"),tableElement.classList.remove("hide"),periodElement.classList.remove("hide"),ChartData.getCardCharts(quizId),TableHandler.getTable(quizId),refreshCounter(),tableSearchInputElement.addEventListener("keyup",TableHandler.tableSearch),tableSearchInputElement.addEventListener("paste",TableHandler.tableSearch),tableSearchResetElement.addEventListener("click",TableHandler.tableSearchReset),tableSearchRowsElement.addEventListener("click",TableHandler.tableSearchRowSet)})).fail((()=>{_notification.default.exception(new Error("Failed to get quiz data"))}))},refreshAction=event=>{event.preventDefault();var element=event.target;null!==element.closest("button")&&"local-assessfreq-refresh-quiz-dashboard"===element.closest("button").id?(refreshCounter(!0),processDashboard(quizId)):"a"===element.tagName.toLowerCase()&&(refreshPeriod=element.dataset.period,refreshCounter(!0),UserPreference.setUserPreference("local_assessfreq_quiz_refresh_preference",refreshPeriod))},triggerZoomGraph=event=>{let call=event.target.closest("div").dataset.call,params={data:JSON.stringify({quiz:quizId,call:call})};ZoomModal.zoomGraph(event,params,"get_quiz_chart")};_exports.init=(context,quiz)=>{contextid=context,FormModal.init(context,processDashboard),ZoomModal.init(context),_override_modal.default.init(context,processDashboard),TableHandler.init(quizId,contextid,"local-assessfreq-quiz-student-table","local-assessfreq-quiz-table","get_student_table","local_assessfreq_quiz_table_rows_preference","local-assessfreq-quiz-student-table-search","local_assessfreq_student_table","local_assessfreq_set_table_preference"),ChartData.init(cards,context,"get_quiz_chart","local_assessfreq/chart"),Str.get_string("loadingquiztitle","local_assessfreq").then((str=>{selectQuizStr=str})).then((()=>{quiz>0&&(quizId=quiz,processDashboard(quiz))})),UserPreference.getUserPreference("local_assessfreq_quiz_refresh_preference").then((response=>{refreshPeriod=response.preferences[0].value?response.preferences[0].value:60})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: refresh"))})),document.getElementById("local-assessfreq-period-container").addEventListener("click",refreshAction),document.getElementById("local-assessfreq-quiz-summary-graph-zoom").addEventListener("click",triggerZoomGraph),document.getElementById("local-assessfreq-quiz-summary-trend-zoom").addEventListener("click",triggerZoomGraph)}})); + +//# sourceMappingURL=dashboard_quiz.min.js.map \ No newline at end of file diff --git a/amd/build/dashboard_quiz.min.js.map b/amd/build/dashboard_quiz.min.js.map index ea27c05..2036763 100644 --- a/amd/build/dashboard_quiz.min.js.map +++ b/amd/build/dashboard_quiz.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/dashboard_quiz.js"],"names":["selectQuizStr","contextid","quizId","refreshPeriod","counterid","cards","cardId","call","aspect","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","processDashboard","quiz","titleElement","innerHTML","Ajax","methodname","args","quizid","then","response","quizArray","JSON","parse","cardsElement","trendElement","summaryElement","summarySpinner","getElementsByClassName","tableElement","periodElement","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","quizLink","createElement","href","url","name","appendChild","currentdUrl","URL","window","location","newUrl","origin","pathname","history","pushState","Str","get_string","courseshortname","str","title","catch","Notification","exception","Error","Templates","render","done","html","classList","add","contentcontainer","replaceNodeContents","fail","remove","ChartData","getCardCharts","TableHandler","getTable","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","refreshAction","event","preventDefault","element","target","closest","id","tagName","toLowerCase","dataset","period","UserPreference","setUserPreference","triggerZoomGraph","params","stringify","ZoomModal","zoomGraph","init","context","FormModal","OverrideModal","getUserPreference","preferences","value","refreshElement","summaryZoom","trendZoom"],"mappings":"ksBAwBA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,O,4lBAKIA,CAAAA,CAAa,CAAG,E,CAChBC,C,CACAC,CAAM,CAAG,C,CACTC,CAAa,CAAG,E,CAChBC,C,CAEEC,CAAK,CAAG,CACV,CAACC,MAAM,CAAE,qCAAT,CAAgDC,IAAI,CAAE,qBAAtD,CAA6EC,MAAM,GAAnF,CADU,CAEV,CAACF,MAAM,CAAE,qCAAT,CAAgDC,IAAI,CAAE,mBAAtD,CAA2EC,MAAM,GAAjF,CAFU,C,CAURC,CAAc,CAAG,UAAkB,IAAjBC,CAAAA,CAAiB,2DACjCC,CAAe,CAAGC,QAAQ,CAACC,cAAT,CAAwB,kCAAxB,CADe,CAIrC,GAAI,KAAAH,CAAJ,CAAoB,CAChBI,aAAa,CAACV,CAAD,CAAb,CACAA,CAAS,CAAG,IAAZ,CACAO,CAAe,CAACI,YAAhB,CAA6B,OAA7B,CAAsC,aAAtC,EACAJ,CAAe,CAACI,YAAhB,CAA6B,eAA7B,CAA8C,GAA9C,CACH,CAGD,GAAIX,CAAJ,CAAe,CACX,MACH,CAEDA,CAAS,CAAGY,WAAW,CAAC,UAAM,IACtBC,CAAAA,CAAiB,CAAGN,CAAe,CAACO,YAAhB,CAA6B,eAA7B,CADE,CAEpBC,CAAY,CAAG,IAAMhB,CAFD,CAI1B,GAAyC,CAArC,CAACc,CAAiB,CAAGE,CAAzB,CAA4C,CACxCR,CAAe,CAACI,YAAhB,CAA6B,OAA7B,CAAsC,WAAaE,CAAiB,CAAGE,CAAjC,EAAiD,GAAvF,EACAR,CAAe,CAACI,YAAhB,CAA6B,eAA7B,CAA+CE,CAAiB,CAAGE,CAAnE,CACH,CAHD,IAGO,CACHL,aAAa,CAACV,CAAD,CAAb,CACAA,CAAS,CAAG,IAAZ,CACAO,CAAe,CAACI,YAAhB,CAA6B,OAA7B,CAAsC,aAAt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EAWA2E,CAAc,CAACW,iBAAf,CAAiC,0CAAjC,EACC/E,IADD,CACM,SAACC,CAAD,CAAc,CAChB1B,CAAa,CAAG0B,CAAQ,CAAC+E,WAAT,CAAqB,CAArB,EAAwBC,KAAxB,CAAgChF,CAAQ,CAAC+E,WAAT,CAAqB,CAArB,EAAwBC,KAAxD,CAAgE,EACnF,CAHD,EAIClC,IAJD,CAIM,UAAM,CACRX,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,uCAAV,CAAvB,CACH,CAND,EASA,GAAI4C,CAAAA,CAAc,CAAGlG,QAAQ,CAACC,cAAT,CAAwB,mCAAxB,CAArB,CACAiG,CAAc,CAAC7B,gBAAf,CAAgC,OAAhC,CAAyCI,CAAzC,EAGA,GAAI0B,CAAAA,CAAW,CAAGnG,QAAQ,CAACC,cAAT,CAAwB,0CAAxB,CAAlB,CACAkG,CAAW,CAAC9B,gBAAZ,CAA6B,OAA7B,CAAsCiB,CAAtC,EAEA,GAAIc,CAAAA,CAAS,CAAGpG,QAAQ,CAACC,cAAT,CAAwB,0CAAxB,CAAhB,CACAmG,CAAS,CAAC/B,gBAAV,CAA2B,OAA3B,CAAoCiB,CAApC,CAEH,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 for report card display and processing.\n *\n * @module local_assessfreq/dashboard_quiz\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport * as Str from 'core/str';\nimport Templates from 'core/templates';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport * as FormModal from 'local_assessfreq/form_modal';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport * as ZoomModal from 'local_assessfreq/zoom_modal';\n\n/**\n * Module level variables.\n */\nvar selectQuizStr = '';\nvar contextid;\nvar quizId = 0;\nvar refreshPeriod = 60;\nvar counterid;\n\nconst cards = [\n {cardId: 'local-assessfreq-quiz-summary-graph', call: 'participant_summary', aspect: true},\n {cardId: 'local-assessfreq-quiz-summary-trend', call: 'participant_trend', aspect: false}\n];\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n processDashboard(quizId);\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Callback function that is called when a quiz is selected from the form.\n * Starts the processing of the dashboard.\n *\n * @param {int} quiz The quiz Id.\n */\nconst processDashboard = (quiz) => {\n quizId = quiz;\n let titleElement = document.getElementById('local-assessfreq-quiz-title');\n titleElement.innerHTML = selectQuizStr;\n // Get quiz data.\n Ajax.call([{\n methodname: 'local_assessfreq_get_quiz_data',\n args: {\n quizid: quiz\n },\n }])[0].then((response) => {\n\n let quizArray = JSON.parse(response);\n let cardsElement = document.getElementById('local-assessfreq-quiz-dashboard-cards-deck');\n let trendElement = document.getElementById('local-assessfreq-quiz-dashboard-participant-trend-deck');\n let summaryElement = document.getElementById('local-assessfreq-quiz-summary-card');\n let summarySpinner = summaryElement.getElementsByClassName('overlay-icon-container')[0];\n let tableElement = document.getElementById('local-assessfreq-quiz-table');\n let periodElement = document.getElementById('local-assessfreq-period-container');\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-student-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-student-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-student-table-rows');\n\n let quizLink = document.createElement('a');\n quizLink.href = quizArray.url;\n quizLink.innerHTML = '';\n titleElement.innerHTML = quizArray.name + ' ';\n titleElement.appendChild(quizLink);\n\n // Update page URL with quiz ID, without reloading page so that page navigation and bookmarking works.\n const currentdUrl = new URL(window.location.href);\n const newUrl = currentdUrl.origin + currentdUrl.pathname + '?id=' + quizId;\n history.pushState({}, '', newUrl);\n\n // Update page title with quiz name.\n Str.get_string('dashboard:quiztitle', 'local_assessfreq', {'quiz': quizArray.name, 'course': quizArray.courseshortname})\n .then((str) => {\n document.title = str;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: dashboard:quiztitle'));\n });\n\n // Populate quiz summary card with details.\n Templates.render('local_assessfreq/quiz-summary-card-content', quizArray).done((html) => {\n summarySpinner.classList.add('hide');\n let contentcontainer = document.getElementById('local-assessfreq-quiz-summary-card-content');\n Templates.replaceNodeContents(contentcontainer, html, '');\n }).fail(() => {\n Notification.exception(new Error('Failed to load quiz summary template.'));\n return;\n });\n\n // Show the cards.\n cardsElement.classList.remove('hide');\n trendElement.classList.remove('hide');\n tableElement.classList.remove('hide');\n periodElement.classList.remove('hide');\n\n ChartData.getCardCharts(quizId);\n TableHandler.getTable(quizId);\n refreshCounter();\n\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get quiz data'));\n });\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n processDashboard(quizId);\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Trigger the zoom graph. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'quiz': quizId, 'call': call})};\n let method = 'get_quiz_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Initialise method for quiz dashboard rendering.\n *\n * @param {int} context The context id.\n * @param {int} quiz The quiz id.\n */\nexport const init = (context, quiz) => {\n contextid = context;\n FormModal.init(context, processDashboard); // Create modal for quiz selection modal.\n ZoomModal.init(context); // Create the zoom modal.\n OverrideModal.init(context, processDashboard);\n TableHandler.init(\n quizId,\n contextid,\n 'local-assessfreq-quiz-student-table',\n 'local-assessfreq-quiz-table',\n 'get_student_table',\n 'local_assessfreq_quiz_table_rows_preference',\n 'local-assessfreq-quiz-student-table-search',\n 'local_assessfreq_student_table',\n 'local_assessfreq_set_table_preference'\n );\n ChartData.init(cards, context, 'get_quiz_chart', 'local_assessfreq/chart');\n Str.get_string('loadingquiztitle', 'local_assessfreq').then((str) => {\n selectQuizStr = str;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: loadingquiz'));\n }).then(() => {\n if (quiz > 0) {\n quizId = quiz;\n processDashboard(quiz);\n }\n });\n\n UserPreference.getUserPreference('local_assessfreq_quiz_refresh_preference')\n .then((response) => {\n refreshPeriod = response.preferences[0].value ? response.preferences[0].value : 60;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: refresh'));\n });\n\n // Event handling for refresh and period buttons.\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n refreshElement.addEventListener('click', refreshAction);\n\n // Set up zoom event listeners.\n let summaryZoom = document.getElementById('local-assessfreq-quiz-summary-graph-zoom');\n summaryZoom.addEventListener('click', triggerZoomGraph);\n\n let trendZoom = document.getElementById('local-assessfreq-quiz-summary-trend-zoom');\n trendZoom.addEventListener('click', triggerZoomGraph);\n\n};\n"],"file":"dashboard_quiz.min.js"} \ No newline at end of file +{"version":3,"file":"dashboard_quiz.min.js","sources":["../src/dashboard_quiz.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for report card display and processing.\n *\n * @module local_assessfreq/dashboard_quiz\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport * as Str from 'core/str';\nimport Templates from 'core/templates';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport * as FormModal from 'local_assessfreq/form_modal';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport * as ZoomModal from 'local_assessfreq/zoom_modal';\n\n// Module level variables.\n\nvar selectQuizStr = '';\nvar contextid;\nvar quizId = 0;\nvar refreshPeriod = 60;\nvar counterid;\n\nconst cards = [\n {cardId: 'local-assessfreq-quiz-summary-graph', call: 'participant_summary', aspect: true},\n {cardId: 'local-assessfreq-quiz-summary-trend', call: 'participant_trend', aspect: false}\n];\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n processDashboard(quizId);\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Callback function that is called when a quiz is selected from the form.\n * Starts the processing of the dashboard.\n *\n * @param {int} quiz The quiz Id.\n */\nconst processDashboard = (quiz) => {\n quizId = quiz;\n let titleElement = document.getElementById('local-assessfreq-quiz-title');\n titleElement.innerHTML = selectQuizStr;\n // Get quiz data.\n Ajax.call([{\n methodname: 'local_assessfreq_get_quiz_data',\n args: {\n quizid: quiz\n },\n }])[0].then((response) => {\n\n let quizArray = JSON.parse(response);\n let cardsElement = document.getElementById('local-assessfreq-quiz-dashboard-cards-deck');\n let trendElement = document.getElementById('local-assessfreq-quiz-dashboard-participant-trend-deck');\n let summaryElement = document.getElementById('local-assessfreq-quiz-summary-card');\n let summarySpinner = summaryElement.getElementsByClassName('overlay-icon-container')[0];\n let tableElement = document.getElementById('local-assessfreq-quiz-table');\n let periodElement = document.getElementById('local-assessfreq-period-container');\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-student-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-student-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-student-table-rows');\n\n let quizLink = document.createElement('a');\n quizLink.href = quizArray.url;\n quizLink.innerHTML = '';\n titleElement.innerHTML = quizArray.name + ' ';\n titleElement.appendChild(quizLink);\n\n // Update page URL with quiz ID, without reloading page so that page navigation and bookmarking works.\n const currentdUrl = new URL(window.location.href);\n const newUrl = currentdUrl.origin + currentdUrl.pathname + '?id=' + quizId;\n history.pushState({}, '', newUrl);\n\n // Update page title with quiz name.\n Str.get_string('dashboard:quiztitle', 'local_assessfreq', {'quiz': quizArray.name, 'course': quizArray.courseshortname})\n .then((str) => {\n document.title = str;\n });\n\n // Populate quiz summary card with details.\n Templates.render('local_assessfreq/quiz-summary-card-content', quizArray).done((html) => {\n summarySpinner.classList.add('hide');\n let contentcontainer = document.getElementById('local-assessfreq-quiz-summary-card-content');\n Templates.replaceNodeContents(contentcontainer, html, '');\n }).fail(() => {\n Notification.exception(new Error('Failed to load quiz summary template.'));\n return;\n });\n\n // Show the cards.\n cardsElement.classList.remove('hide');\n trendElement.classList.remove('hide');\n tableElement.classList.remove('hide');\n periodElement.classList.remove('hide');\n\n ChartData.getCardCharts(quizId);\n TableHandler.getTable(quizId);\n refreshCounter();\n\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get quiz data'));\n });\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n processDashboard(quizId);\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Trigger the zoom graph. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'quiz': quizId, 'call': call})};\n let method = 'get_quiz_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Initialise method for quiz dashboard rendering.\n *\n * @param {int} context The context id.\n * @param {int} quiz The quiz id.\n */\nexport const init = (context, quiz) => {\n contextid = context;\n FormModal.init(context, processDashboard); // Create modal for quiz selection modal.\n ZoomModal.init(context); // Create the zoom modal.\n OverrideModal.init(context, processDashboard);\n TableHandler.init(\n quizId,\n contextid,\n 'local-assessfreq-quiz-student-table',\n 'local-assessfreq-quiz-table',\n 'get_student_table',\n 'local_assessfreq_quiz_table_rows_preference',\n 'local-assessfreq-quiz-student-table-search',\n 'local_assessfreq_student_table',\n 'local_assessfreq_set_table_preference'\n );\n ChartData.init(cards, context, 'get_quiz_chart', 'local_assessfreq/chart');\n Str.get_string('loadingquiztitle', 'local_assessfreq').then((str) => {\n selectQuizStr = str;\n }).then(() => {\n if (quiz > 0) {\n quizId = quiz;\n processDashboard(quiz);\n }\n });\n\n UserPreference.getUserPreference('local_assessfreq_quiz_refresh_preference')\n .then((response) => {\n refreshPeriod = response.preferences[0].value ? response.preferences[0].value : 60;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: refresh'));\n });\n\n // Event handling for refresh and period buttons.\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n refreshElement.addEventListener('click', refreshAction);\n\n // Set up zoom event listeners.\n let summaryZoom = document.getElementById('local-assessfreq-quiz-summary-graph-zoom');\n summaryZoom.addEventListener('click', triggerZoomGraph);\n\n let trendZoom = document.getElementById('local-assessfreq-quiz-summary-trend-zoom');\n trendZoom.addEventListener('click', triggerZoomGraph);\n\n};\n"],"names":["contextid","counterid","selectQuizStr","quizId","refreshPeriod","cards","cardId","call","aspect","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","processDashboard","quiz","titleElement","innerHTML","methodname","args","quizid","then","response","quizArray","JSON","parse","cardsElement","trendElement","summarySpinner","getElementsByClassName","tableElement","periodElement","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","quizLink","createElement","href","url","name","appendChild","currentdUrl","URL","window","location","newUrl","origin","pathname","history","pushState","Str","get_string","courseshortname","str","title","render","done","html","classList","add","contentcontainer","replaceNodeContents","fail","exception","Error","remove","ChartData","getCardCharts","TableHandler","getTable","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","refreshAction","event","preventDefault","element","target","closest","id","tagName","toLowerCase","dataset","period","UserPreference","setUserPreference","triggerZoomGraph","params","stringify","ZoomModal","zoomGraph","context","FormModal","init","getUserPreference","preferences","value"],"mappings":";;;;;;;;siBAsCIA,UAGAC,UAJAC,cAAgB,GAEhBC,OAAS,EACTC,cAAgB,SAGdC,MAAQ,CACV,CAACC,OAAQ,sCAAuCC,KAAM,sBAAuBC,QAAQ,GACrF,CAACF,OAAQ,sCAAuCC,KAAM,oBAAqBC,QAAQ,IAQjFC,eAAiB,eAACC,iEAChBC,gBAAkBC,SAASC,eAAe,qCAGhC,IAAVH,QACAI,cAAcb,WACdA,UAAY,KACZU,gBAAgBI,aAAa,QAAS,eACtCJ,gBAAgBI,aAAa,gBAAiB,MAI9Cd,YAIJA,UAAYe,aAA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AK,KACAN,KAAO,IACPlB,OAASkB,KACTD,iBAAiBC,UAIzBsE,eAAeU,kBAAkB,4CAChC1E,MAAMC,WACHxB,cAAgBwB,SAAS0E,YAAY,GAAGC,MAAQ3E,SAAS0E,YAAY,GAAGC,MAAQ,MAEnFnC,MAAK,2BACWC,UAAU,IAAIC,MAAM,6CAIhB1D,SAASC,eAAe,qCAC9B+D,iBAAiB,QAASI,eAGvBpE,SAASC,eAAe,4CAC9B+D,iBAAiB,QAASiB,kBAEtBjF,SAASC,eAAe,4CAC9B+D,iBAAiB,QAASiB"} \ No newline at end of file diff --git a/amd/build/dashboard_quiz_inprogress.min.js b/amd/build/dashboard_quiz_inprogress.min.js index 394c423..b5e9f3d 100644 --- a/amd/build/dashboard_quiz_inprogress.min.js +++ b/amd/build/dashboard_quiz_inprogress.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/dashboard_quiz_inprogress",["exports","core/ajax","core/notification","core/templates","local_assessfreq/chart_data","local_assessfreq/table_handler","local_assessfreq/user_preferences","local_assessfreq/zoom_modal"],function(a,b,c,d,e,f,g,h){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=void 0;b=k(b);c=k(c);d=k(d);e=j(e);f=j(f);g=j(g);h=j(h);function i(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;i=function(){return a};return a}function j(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=i();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;if(f&&(f.get||f.set)){Object.defineProperty(c,e,f)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function k(a){return a&&a.__esModule?a:{default:a}}var l,m=60,n,o="name_asc",p=0,q=0,r,s=[{cardId:"local-assessfreq-quiz-summary-upcomming-graph",call:"upcomming_quizzes",aspect:!0},{cardId:"local-assessfreq-quiz-summary-inprogress-graph",call:"all_participants_inprogress",aspect:!0}],t=function(){var a=0 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */var contextid;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates),ChartData=_interopRequireWildcard(ChartData),TableHandler=_interopRequireWildcard(TableHandler),UserPreference=_interopRequireWildcard(UserPreference),ZoomModal=_interopRequireWildcard(ZoomModal);var counterid,hoursFilter,refreshPeriod=60,tablesort="name_asc",hoursAhead=0,hoursBehind=0;const cards=[{cardId:"local-assessfreq-quiz-summary-upcomming-graph",call:"upcomming_quizzes",aspect:!0},{cardId:"local-assessfreq-quiz-summary-inprogress-graph",call:"all_participants_inprogress",aspect:!0}],refreshCounter=function(){let reset=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],progressElement=document.getElementById("local-assessfreq-period-progress");!0===reset&&(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100)),counterid||(counterid=setInterval((()=>{let progressWidthAria=progressElement.getAttribute("aria-valuenow");const progressStep=100/refreshPeriod;progressWidthAria-progressStep>0?(progressElement.setAttribute("style","width: "+(progressWidthAria-progressStep)+"%"),progressElement.setAttribute("aria-valuenow",progressWidthAria-progressStep)):(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100),processDashboard(),refreshCounter())}),1e3))},processDashboard=()=>{_ajax.default.call([{methodname:"local_assessfreq_get_inprogress_counts",args:{}}])[0].then((response=>{let quizSummary=JSON.parse(response),summaryElement=document.getElementById("local-assessfreq-quiz-dashboard-inprogress-summary-card"),summarySpinner=summaryElement.getElementsByClassName("overlay-icon-container")[0],tableSearchInputElement=document.getElementById("local-assessfreq-quiz-inprogress-table-search"),tableSearchResetElement=document.getElementById("local-assessfreq-quiz-inprogress-table-search-reset"),tableSearchRowsElement=document.getElementById("local-assessfreq-quiz-inprogress-table-rows"),tableSortElement=document.getElementById("local-assessfreq-inprogress-table-sort");summaryElement.classList.remove("hide"),_templates.default.render("local_assessfreq/quiz-dashboard-inprogress-summary-card-content",quizSummary).done((html=>{summarySpinner.classList.add("hide");let contentcontainer=document.getElementById("local-assessfreq-quiz-dashboard-inprogress-summary-card-content");_templates.default.replaceNodeContents(contentcontainer,html,"")})).fail((()=>{_notification.default.exception(new Error("Failed to load quiz counts template."))})),hoursFilter=[hoursAhead,hoursBehind],ChartData.getCardCharts(0,hoursFilter),TableHandler.getTable(0,hoursFilter,tablesort),refreshCounter(),tableSearchInputElement.addEventListener("keyup",TableHandler.tableSearch),tableSearchInputElement.addEventListener("paste",TableHandler.tableSearch),tableSearchResetElement.addEventListener("click",TableHandler.tableSearchReset),tableSearchRowsElement.addEventListener("click",TableHandler.tableSearchRowSet),tableSortElement.addEventListener("click",TableHandler.tableSortButtonAction)})).fail((()=>{_notification.default.exception(new Error("Failed to get quiz summary counts"))}))},refreshAction=event=>{event.preventDefault();var element=event.target;null!==element.closest("button")&&"local-assessfreq-refresh-quiz-dashboard"===element.closest("button").id?(refreshCounter(!0),processDashboard()):"a"===element.tagName.toLowerCase()&&(refreshPeriod=element.dataset.period,refreshCounter(!0),UserPreference.setUserPreference("local_assessfreq_quiz_refresh_preference",refreshPeriod))},triggerZoomGraph=event=>{let call=event.target.closest("div").dataset.call,params={data:JSON.stringify({call:call,hoursahead:hoursAhead,hoursbehind:hoursBehind})};ZoomModal.zoomGraph(event,params,"get_quiz_inprogress_chart")},quizzesAheadSet=event=>{if(event.preventDefault(),"a"===event.target.tagName.toLowerCase()){let hours=event.target.dataset.metric;UserPreference.setUserPreference("local_assessfreq_quizzes_inprogress_table_hoursahead_preference",hours).then((()=>{hoursAhead=hours,processDashboard()})).fail((()=>{_notification.default.exception(new Error("Failed to update user preference: hours ahead"))}))}},quizzesBehindSet=event=>{if(event.preventDefault(),"a"===event.target.tagName.toLowerCase()){let hours=event.target.dataset.metric;UserPreference.setUserPreference("local_assessfreq_quizzes_inprogress_table_hoursbehind_preference",hours).then((()=>{hoursBehind=hours,processDashboard()})).fail((()=>{_notification.default.exception(new Error("Failed to update user preference: hours behind"))}))}};_exports.init=context=>{contextid=context,ZoomModal.init(context),TableHandler.init(0,contextid,null,"local-assessfreq-quiz-inprogress-table","get_quizzes_inprogress_table","local_assessfreq_quiz_table_inprogress_preference","local-assessfreq-quiz-inprogress-table-search"),ChartData.init(cards,context,"get_quiz_inprogress_chart","local_assessfreq/chart"),UserPreference.getUserPreference("local_assessfreq_quiz_refresh_preference").then((response=>{refreshPeriod=response.preferences[0].value?response.preferences[0].value:60})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: refresh"))})),UserPreference.getUserPreference("local_assessfreq_quiz_table_inprogress_sort_preference").then((response=>{tablesort=response.preferences[0].value?response.preferences[0].value:"name_asc"})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: tablesort"))})),UserPreference.getUserPreference("local_assessfreq_quizzes_inprogress_table_hoursahead_preference").then((response=>{hoursAhead=response.preferences[0].value?response.preferences[0].value:0})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: hoursahead"))})),UserPreference.getUserPreference("local_assessfreq_quizzes_inprogress_table_hoursbehind_preference").then((response=>{hoursBehind=response.preferences[0].value?response.preferences[0].value:0})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: hoursbehind"))})),document.getElementById("local-assessfreq-period-container").addEventListener("click",refreshAction),document.getElementById("local-assessfreq-quiz-summary-inprogress-graph-zoom").addEventListener("click",triggerZoomGraph),document.getElementById("local-assessfreq-quiz-summary-upcomming-graph-zoom").addEventListener("click",triggerZoomGraph),document.getElementById("local-assessfreq-quiz-student-table-hoursahead").addEventListener("click",quizzesAheadSet),document.getElementById("local-assessfreq-quiz-student-table-hoursbehind").addEventListener("click",quizzesBehindSet),processDashboard()}})); + +//# sourceMappingURL=dashboard_quiz_inprogress.min.js.map \ No newline at end of file diff --git a/amd/build/dashboard_quiz_inprogress.min.js.map b/amd/build/dashboard_quiz_inprogress.min.js.map index 867767e..ca4bf69 100644 --- a/amd/build/dashboard_quiz_inprogress.min.js.map +++ b/amd/build/dashboard_quiz_inprogress.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/dashboard_quiz_inprogress.js"],"names":["contextid","refreshPeriod","counterid","tablesort","hoursAhead","hoursBehind","hoursFilter","cards","cardId","call","aspect","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","processDashboard","Ajax","methodname","args","then","response","quizSummary","JSON","parse","summaryElement","summarySpinner","getElementsByClassName","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","tableSortElement","classList","remove","Templates","render","done","html","add","contentcontainer","replaceNodeContents","fail","Notification","exception","Error","ChartData","getCardCharts","TableHandler","getTable","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","tableSortButtonAction","refreshAction","event","preventDefault","element","target","closest","id","tagName","toLowerCase","dataset","period","UserPreference","setUserPreference","triggerZoomGraph","params","stringify","ZoomModal","zoomGraph","quizzesAheadSet","hours","metric","quizzesBehindSet","init","context","getUserPreference","preferences","value","refreshElement","summaryZoom","upcommingZoom","quizzesAheadElement","quizzesBehindElement"],"mappings":"4nBAwBA,OACA,OACA,OACA,OACA,OACA,OACA,O,4lBAKIA,CAAAA,C,CACAC,CAAa,CAAG,E,CAChBC,C,CACAC,CAAS,CAAG,U,CACZC,CAAU,CAAG,C,CACbC,CAAW,CAAG,C,CAOdC,C,CAEEC,CAAK,CAAG,CACV,CAACC,MAAM,CAAE,+CAAT,CAA0DC,IAAI,CAAE,mBAAhE,CAAqF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AC0D,WAAT,CAAqB,CAArB,EAAwBC,KAAxB,CAAgC3D,CAAQ,CAAC0D,WAAT,CAAqB,CAArB,EAAwBC,KAAxD,CAAgE,CACjF,CAHL,EAIKvC,IAJL,CAIU,UAAM,CACRC,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,2CAAV,CAAvB,CACH,CANL,EASA,GAAIqC,CAAAA,CAAc,CAAGzE,QAAQ,CAACC,cAAT,CAAwB,mCAAxB,CAArB,CACAwE,CAAc,CAAChC,gBAAf,CAAgC,OAAhC,CAAyCK,CAAzC,EAGA,GAAI4B,CAAAA,CAAW,CAAG1E,QAAQ,CAACC,cAAT,CAAwB,qDAAxB,CAAlB,CACAyE,CAAW,CAACjC,gBAAZ,CAA6B,OAA7B,CAAsCkB,CAAtC,EAEA,GAAIgB,CAAAA,CAAa,CAAG3E,QAAQ,CAACC,cAAT,CAAwB,oDAAxB,CAApB,CACA0E,CAAa,CAAClC,gBAAd,CAA+B,OAA/B,CAAwCkB,CAAxC,EAGA,GAAIiB,CAAAA,CAAmB,CAAG5E,QAAQ,CAACC,cAAT,CAAwB,gDAAxB,CAA1B,CACA2E,CAAmB,CAACnC,gBAApB,CAAqC,OAArC,CAA8CuB,CAA9C,EAEA,GAAIa,CAAAA,CAAoB,CAAG7E,QAAQ,CAACC,cAAT,CAAwB,iDAAxB,CAA3B,CACA4E,CAAoB,CAACpC,gBAArB,CAAsC,OAAtC,CAA+C0B,CAA/C,EAEA3D,CAAgB,EAEnB,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 for quizzes in progress display and processing.\n *\n * @module local_assessfreq/dashboard_quiz_inprogress\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport Templates from 'core/templates';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport * as ZoomModal from 'local_assessfreq/zoom_modal';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar refreshPeriod = 60;\nvar counterid;\nvar tablesort = 'name_asc';\nvar hoursAhead = 0;\nvar hoursBehind = 0;\n\n/**\n * Hours filter array.\n *\n * @type {array} Title to display on modal.\n */\nvar hoursFilter;\n\nconst cards = [\n {cardId: 'local-assessfreq-quiz-summary-upcomming-graph', call: 'upcomming_quizzes', aspect: true},\n {cardId: 'local-assessfreq-quiz-summary-inprogress-graph', call: 'all_participants_inprogress', aspect: true}\n];\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n processDashboard();\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Starts the processing of the dashboard.\n */\nconst processDashboard = () => {\n // Get summary quiz data.\n Ajax.call([{\n methodname: 'local_assessfreq_get_inprogress_counts',\n args: {},\n }])[0].then((response) => {\n let quizSummary = JSON.parse(response);\n let summaryElement = document.getElementById('local-assessfreq-quiz-dashboard-inprogress-summary-card');\n let summarySpinner = summaryElement.getElementsByClassName('overlay-icon-container')[0];\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-inprogress-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-inprogress-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-inprogress-table-rows');\n let tableSortElement = document.getElementById('local-assessfreq-inprogress-table-sort');\n\n summaryElement.classList.remove('hide'); // Show the card.\n\n // Populate summary card with details.\n Templates.render('local_assessfreq/quiz-dashboard-inprogress-summary-card-content', quizSummary)\n .done((html) => {\n summarySpinner.classList.add('hide');\n\n let contentcontainer = document.getElementById('local-assessfreq-quiz-dashboard-inprogress-summary-card-content');\n Templates.replaceNodeContents(contentcontainer, html, '');\n }).fail(() => {\n Notification.exception(new Error('Failed to load quiz counts template.'));\n return;\n });\n\n hoursFilter = [hoursAhead, hoursBehind];\n ChartData.getCardCharts(0, hoursFilter);\n TableHandler.getTable(0, hoursFilter, tablesort);\n refreshCounter();\n\n // Table event listeners.\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n tableSortElement.addEventListener('click', TableHandler.tableSortButtonAction);\n\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get quiz summary counts'));\n });\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n processDashboard();\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Trigger the zoom graph. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'call': call, 'hoursahead': hoursAhead, 'hoursbehind': hoursBehind})};\n let method = 'get_quiz_inprogress_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Process the hours ahead event from the in progress quizzes table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst quizzesAheadSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_quizzes_inprogress_table_hoursahead_preference', hours)\n .then(() => {\n hoursAhead = hours;\n processDashboard(); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours ahead'));\n });\n }\n};\n\n/**\n * Process the hours behind event from the in progress quizzes table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst quizzesBehindSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_quizzes_inprogress_table_hoursbehind_preference', hours)\n .then(() => {\n hoursBehind = hours;\n processDashboard(); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours behind'));\n });\n }\n};\n\n/**\n * Initialise method for quizzes in progress dashboard rendering.\n *\n * @param {int} context The context id.\n */\nexport const init = (context) => {\n contextid = context;\n ZoomModal.init(context); // Create the zoom modal.\n TableHandler.init(\n 0,\n contextid,\n null,\n 'local-assessfreq-quiz-inprogress-table',\n 'get_quizzes_inprogress_table',\n 'local_assessfreq_quiz_table_inprogress_preference',\n 'local-assessfreq-quiz-inprogress-table-search'\n );\n ChartData.init(cards, context, 'get_quiz_inprogress_chart', 'local_assessfreq/chart');\n\n UserPreference.getUserPreference('local_assessfreq_quiz_refresh_preference')\n .then((response) => {\n refreshPeriod = response.preferences[0].value ? response.preferences[0].value : 60;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: refresh'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quiz_table_inprogress_sort_preference')\n .then((response) => {\n tablesort = response.preferences[0].value ? response.preferences[0].value : 'name_asc';\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: tablesort'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quizzes_inprogress_table_hoursahead_preference')\n .then((response) => {\n hoursAhead = response.preferences[0].value ? response.preferences[0].value : 0;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quizzes_inprogress_table_hoursbehind_preference')\n .then((response) => {\n hoursBehind = response.preferences[0].value ? response.preferences[0].value : 0;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursbehind'));\n });\n\n // Event handling for refresh and period buttons.\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n refreshElement.addEventListener('click', refreshAction);\n\n // Set up zoom event listeners.\n let summaryZoom = document.getElementById('local-assessfreq-quiz-summary-inprogress-graph-zoom');\n summaryZoom.addEventListener('click', triggerZoomGraph);\n\n let upcommingZoom = document.getElementById('local-assessfreq-quiz-summary-upcomming-graph-zoom');\n upcommingZoom.addEventListener('click', triggerZoomGraph);\n\n // Set up behind and ahead quizzes event listeners.\n let quizzesAheadElement = document.getElementById('local-assessfreq-quiz-student-table-hoursahead');\n quizzesAheadElement.addEventListener('click', quizzesAheadSet);\n\n let quizzesBehindElement = document.getElementById('local-assessfreq-quiz-student-table-hoursbehind');\n quizzesBehindElement.addEventListener('click', quizzesBehindSet);\n\n processDashboard();\n\n};\n"],"file":"dashboard_quiz_inprogress.min.js"} \ No newline at end of file +{"version":3,"file":"dashboard_quiz_inprogress.min.js","sources":["../src/dashboard_quiz_inprogress.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for quizzes in progress display and processing.\n *\n * @module local_assessfreq/dashboard_quiz_inprogress\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\nimport Templates from 'core/templates';\nimport * as ChartData from 'local_assessfreq/chart_data';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\nimport * as ZoomModal from 'local_assessfreq/zoom_modal';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar refreshPeriod = 60;\nvar counterid;\nvar tablesort = 'name_asc';\nvar hoursAhead = 0;\nvar hoursBehind = 0;\n\n/**\n * Hours filter array.\n *\n * @type {array} Title to display on modal.\n */\nvar hoursFilter;\n\nconst cards = [\n {cardId: 'local-assessfreq-quiz-summary-upcomming-graph', call: 'upcomming_quizzes', aspect: true},\n {cardId: 'local-assessfreq-quiz-summary-inprogress-graph', call: 'all_participants_inprogress', aspect: true}\n];\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n processDashboard();\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Starts the processing of the dashboard.\n */\nconst processDashboard = () => {\n // Get summary quiz data.\n Ajax.call([{\n methodname: 'local_assessfreq_get_inprogress_counts',\n args: {},\n }])[0].then((response) => {\n let quizSummary = JSON.parse(response);\n let summaryElement = document.getElementById('local-assessfreq-quiz-dashboard-inprogress-summary-card');\n let summarySpinner = summaryElement.getElementsByClassName('overlay-icon-container')[0];\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-inprogress-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-inprogress-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-inprogress-table-rows');\n let tableSortElement = document.getElementById('local-assessfreq-inprogress-table-sort');\n\n summaryElement.classList.remove('hide'); // Show the card.\n\n // Populate summary card with details.\n Templates.render('local_assessfreq/quiz-dashboard-inprogress-summary-card-content', quizSummary)\n .done((html) => {\n summarySpinner.classList.add('hide');\n\n let contentcontainer = document.getElementById('local-assessfreq-quiz-dashboard-inprogress-summary-card-content');\n Templates.replaceNodeContents(contentcontainer, html, '');\n }).fail(() => {\n Notification.exception(new Error('Failed to load quiz counts template.'));\n return;\n });\n\n hoursFilter = [hoursAhead, hoursBehind];\n ChartData.getCardCharts(0, hoursFilter);\n TableHandler.getTable(0, hoursFilter, tablesort);\n refreshCounter();\n\n // Table event listeners.\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n tableSortElement.addEventListener('click', TableHandler.tableSortButtonAction);\n\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get quiz summary counts'));\n });\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n processDashboard();\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Trigger the zoom graph. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerZoomGraph = (event) => {\n let call = event.target.closest('div').dataset.call;\n let params = {'data': JSON.stringify({'call': call, 'hoursahead': hoursAhead, 'hoursbehind': hoursBehind})};\n let method = 'get_quiz_inprogress_chart';\n\n ZoomModal.zoomGraph(event, params, method);\n};\n\n/**\n * Process the hours ahead event from the in progress quizzes table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst quizzesAheadSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_quizzes_inprogress_table_hoursahead_preference', hours)\n .then(() => {\n hoursAhead = hours;\n processDashboard(); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours ahead'));\n });\n }\n};\n\n/**\n * Process the hours behind event from the in progress quizzes table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst quizzesBehindSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_quizzes_inprogress_table_hoursbehind_preference', hours)\n .then(() => {\n hoursBehind = hours;\n processDashboard(); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours behind'));\n });\n }\n};\n\n/**\n * Initialise method for quizzes in progress dashboard rendering.\n *\n * @param {int} context The context id.\n */\nexport const init = (context) => {\n contextid = context;\n ZoomModal.init(context); // Create the zoom modal.\n TableHandler.init(\n 0,\n contextid,\n null,\n 'local-assessfreq-quiz-inprogress-table',\n 'get_quizzes_inprogress_table',\n 'local_assessfreq_quiz_table_inprogress_preference',\n 'local-assessfreq-quiz-inprogress-table-search'\n );\n ChartData.init(cards, context, 'get_quiz_inprogress_chart', 'local_assessfreq/chart');\n\n UserPreference.getUserPreference('local_assessfreq_quiz_refresh_preference')\n .then((response) => {\n refreshPeriod = response.preferences[0].value ? response.preferences[0].value : 60;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: refresh'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quiz_table_inprogress_sort_preference')\n .then((response) => {\n tablesort = response.preferences[0].value ? response.preferences[0].value : 'name_asc';\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: tablesort'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quizzes_inprogress_table_hoursahead_preference')\n .then((response) => {\n hoursAhead = response.preferences[0].value ? response.preferences[0].value : 0;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n });\n\n UserPreference.getUserPreference('local_assessfreq_quizzes_inprogress_table_hoursbehind_preference')\n .then((response) => {\n hoursBehind = response.preferences[0].value ? response.preferences[0].value : 0;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursbehind'));\n });\n\n // Event handling for refresh and period buttons.\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n refreshElement.addEventListener('click', refreshAction);\n\n // Set up zoom event listeners.\n let summaryZoom = document.getElementById('local-assessfreq-quiz-summary-inprogress-graph-zoom');\n summaryZoom.addEventListener('click', triggerZoomGraph);\n\n let upcommingZoom = document.getElementById('local-assessfreq-quiz-summary-upcomming-graph-zoom');\n upcommingZoom.addEventListener('click', triggerZoomGraph);\n\n // Set up behind and ahead quizzes event listeners.\n let quizzesAheadElement = document.getElementById('local-assessfreq-quiz-student-table-hoursahead');\n quizzesAheadElement.addEventListener('click', quizzesAheadSet);\n\n let quizzesBehindElement = document.getElementById('local-assessfreq-quiz-student-table-hoursbehind');\n quizzesBehindElement.addEventListener('click', quizzesBehindSet);\n\n processDashboard();\n\n};\n"],"names":["contextid","counterid","hoursFilter","refreshPeriod","tablesort","hoursAhead","hoursBehind","cards","cardId","call","aspect","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","processDashboard","methodname","args","then","response","quizSummary","JSON","parse","summaryElement","summarySpinner","getElementsByClassName","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","tableSortElement","classList","remove","render","done","html","add","contentcontainer","replaceNodeContents","fail","exception","Error","ChartData","getCardCharts","TableHandler","getTable","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","tableSortButtonAction","refreshAction","event","preventDefault","element","target","closest","id","tagName","toLowerCase","dataset","period","UserPreference","setUserPreference","triggerZoomGraph","params","stringify","ZoomModal","zoomGraph","quizzesAheadSet","hours","metric","quizzesBehindSet","context","init","getUserPreference","preferences","value"],"mappings":";;;;;;;;SAmCIA,qaAEAC,UAUAC,YAXAC,cAAgB,GAEhBC,UAAY,WACZC,WAAa,EACbC,YAAc,QASZC,MAAQ,CACV,CAACC,OAAQ,gDAAiDC,KAAM,oBAAqBC,QAAQ,GAC7F,CAACF,OAAQ,iDAAkDC,KAAM,8BAA+BC,QAAQ,IAQtGC,eAAiB,eAACC,iEAChBC,gBAAkBC,SAASC,eAAe,qCAGhC,IAAVH,QACAI,cAAc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AIC,MAAM,6CAGrCqB,eAAea,kBAAkB,0DAChCxD,MAAMC,WACHtB,UAAYsB,SAASwD,YAAY,GAAGC,MAAQzD,SAASwD,YAAY,GAAGC,MAAQ,cAE/EtC,MAAK,2BACWC,UAAU,IAAIC,MAAM,+CAGrCqB,eAAea,kBAAkB,mEAC5BxD,MAAMC,WACHrB,WAAaqB,SAASwD,YAAY,GAAGC,MAAQzD,SAASwD,YAAY,GAAGC,MAAQ,KAEhFtC,MAAK,2BACWC,UAAU,IAAIC,MAAM,gDAGzCqB,eAAea,kBAAkB,oEAC5BxD,MAAMC,WACHpB,YAAcoB,SAASwD,YAAY,GAAGC,MAAQzD,SAASwD,YAAY,GAAGC,MAAQ,KAEjFtC,MAAK,2BACWC,UAAU,IAAIC,MAAM,iDAIpBjC,SAASC,eAAe,qCAC9BqC,iBAAiB,QAASK,eAGvB3C,SAASC,eAAe,uDAC9BqC,iBAAiB,QAASkB,kBAElBxD,SAASC,eAAe,sDAC9BqC,iBAAiB,QAASkB,kBAGdxD,SAASC,eAAe,kDAC9BqC,iBAAiB,QAASuB,iBAEnB7D,SAASC,eAAe,mDAC9BqC,iBAAiB,QAAS0B,kBAE/CxD"} \ No newline at end of file diff --git a/amd/build/dayview.min.js b/amd/build/dayview.min.js index 7538d45..064ec2a 100644 --- a/amd/build/dayview.min.js +++ b/amd/build/dayview.min.js @@ -1,2 +1,10 @@ -function asyncGeneratorStep(a,b,c,d,e,f,g){try{var h=a[f](g),i=h.value}catch(a){c(a);return}if(h.done){b(i)}else{Promise.resolve(i).then(d,e)}}function _asyncToGenerator(a){return function(){var b=this,c=arguments;return new Promise(function(d,e){var h=a.apply(b,c);function f(a){asyncGeneratorStep(h,d,e,f,g,"next",a)}function g(a){asyncGeneratorStep(h,d,e,f,g,"throw",a)}f(void 0)})}}define ("local_assessfreq/dayview",["core/str","core/notification","core/modal_factory","local_assessfreq/modal_large","core/templates","core/ajax"],function(a,b,c,d,e,f){var g={},h,i="

",j=[{key:"sun",component:"calendar"},{key:"mon",component:"calendar"},{key:"tue",component:"calendar"},{key:"wed",component:"calendar"},{key:"thu",component:"calendar"},{key:"fri",component:"calendar"},{key:"sat",component:"calendar"},{key:"jan",component:"local_assessfreq"},{key:"feb",component:"local_assessfreq"},{key:"mar",component:"local_assessfreq"},{key:"apr",component:"local_assessfreq"},{key:"may",component:"local_assessfreq"},{key:"jun",component:"local_assessfreq"},{key:"jul",component:"local_assessfreq"},{key:"aug",component:"local_assessfreq"},{key:"sep",component:"local_assessfreq"},{key:"oct",component:"local_assessfreq"},{key:"nov",component:"local_assessfreq"},{key:"dec",component:"local_assessfreq"}],k,l="Australia/Melbourne",m="",n=function(a,b){return new Promise(function(c){var d=new Date(1e3*a).toLocaleString("en-US",{timeZone:l}),e=new Date(d),f=e.getFullYear(),g=k[7+e.getMonth()],h=e.getDate(),i=e.getHours(),j="0"+e.getMinutes(),m=i+":"+j.substr(-2);if("strftimetime"===b){c(m)}else{c(h+" "+g+" "+f+", "+m)}})},o=function(){var a=_asyncToGenerator(regeneratorRuntime.mark(function a(b){var c,d,e,f,g,h,j,k,m,o,p,q,r,s;return regeneratorRuntime.wrap(function(a){while(1){switch(a.prev=a.next){case 0:c=JSON.parse(b);d=5/72;e=0;case 3:if(!(e=q)){a.next=23;break}q=0;s=(p-j)/60*d;a.next=20;return n(c[e].timestart,"strftimedatetime");case 20:c[e].start=a.sent;a.next=28;break;case 23:r=q/60*d;s=(p-m)/60*d;a.next=27;return n(c[e].timestart,"strftimetime");case 27:c[e].start=a.sent;case 28:if(100 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/dayview",["core/str","core/notification","core/modal_factory","local_assessfreq/modal_large","core/templates","core/ajax"],(function(Str,Notification,ModalFactory,ModalLarge,Templates,Ajax){var modalObj,Dayview={};const spinner='

',stringArr=[{key:"sun",component:"calendar"},{key:"mon",component:"calendar"},{key:"tue",component:"calendar"},{key:"wed",component:"calendar"},{key:"thu",component:"calendar"},{key:"fri",component:"calendar"},{key:"sat",component:"calendar"},{key:"jan",component:"local_assessfreq"},{key:"feb",component:"local_assessfreq"},{key:"mar",component:"local_assessfreq"},{key:"apr",component:"local_assessfreq"},{key:"may",component:"local_assessfreq"},{key:"jun",component:"local_assessfreq"},{key:"jul",component:"local_assessfreq"},{key:"aug",component:"local_assessfreq"},{key:"sep",component:"local_assessfreq"},{key:"oct",component:"local_assessfreq"},{key:"nov",component:"local_assessfreq"},{key:"dec",component:"local_assessfreq"}];var stringResult,systemTimezone="Australia/Melbourne",dayViewTitle="";const getUserDate=function(timestamp,format){return new Promise((resolve=>{const systemTimezoneTime=new Date(1e3*timestamp).toLocaleString("en-US",{timeZone:systemTimezone});let date=new Date(systemTimezoneTime);const year=date.getFullYear(),month=stringResult[7+date.getMonth()],day=date.getDate(),strftimetime=date.getHours()+":"+("0"+date.getMinutes()).substr(-2);resolve("strftimetime"===format?strftimetime:day+" "+month+" "+year+", "+strftimetime)}))},formatData=async function(response){let responseArr=JSON.parse(response),scaler=5/72;for(let i=0;i100&&(width=100-leftMargin),responseArr[i].leftmargin=leftMargin,responseArr[i].width=width,responseArr[i].end=await getUserDate(responseArr[i].timeend,"strftimetime")}return new Promise((resolve=>{resolve(responseArr)}))};return Dayview.display=function(date){modalObj.setBody(spinner),modalObj.show();let args={date:date,modules:["all"]},jsonArgs=JSON.stringify(args);Ajax.call([{methodname:"local_assessfreq_get_day_events",args:{jsondata:jsonArgs}}])[0].then(formatData).then((responseArr=>{let context={rows:responseArr};const year=responseArr[0].endyear,dayDate=responseArr[0].endday+" "+stringResult[6+parseInt(responseArr[0].endmonth)]+" "+year;modalObj.setTitle(dayViewTitle+" "+dayDate),modalObj.setBody(Templates.render("local_assessfreq/dayview",context))})).fail((()=>{Notification.exception(new Error("Failed to load day view"))}))},Dayview.init=function(){Str.get_strings(stringArr).then((stringReturn=>{stringResult=stringReturn})),Ajax.call([{methodname:"local_assessfreq_get_system_timezone",args:{}}],!0,!1)[0].then((response=>{systemTimezone=response})).fail((()=>{Notification.exception(new Error("Failed to get system timezone"))})),Str.get_string("schedule","local_assessfreq").then((title=>{dayViewTitle=title,ModalFactory.create({type:ModalLarge.TYPE,title:title,body:spinner}).done((modal=>{modalObj=modal}))}))},Dayview})); + +//# sourceMappingURL=dayview.min.js.map \ No newline at end of file diff --git a/amd/build/dayview.min.js.map b/amd/build/dayview.min.js.map index 7aa4e08..d767b60 100644 --- a/amd/build/dayview.min.js.map +++ b/amd/build/dayview.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/dayview.js"],"names":["define","Str","Notification","ModalFactory","ModalLarge","Templates","Ajax","Dayview","modalObj","spinner","stringArr","key","component","stringResult","systemTimezone","dayViewTitle","getUserDate","timestamp","format","Promise","resolve","systemTimezoneTime","Date","toLocaleString","timeZone","date","year","getFullYear","month","getMonth","day","getDate","hours","getHours","minutes","getMinutes","strftimetime","substr","formatData","response","responseArr","JSON","parse","scaler","i","length","endyear","endmonth","endday","dayStart","getTime","timeStart","timestart","timeStartTimestamp","timeEnd","timeend","timeEndTimestamp","secondsSinceDayStart","leftMargin","width","start","leftmargin","end","display","setBody","show","jsonArgs","stringify","modules","call","methodname","args","jsondata","then","parseInt","setTitle","render","rows","fail","exception","Error","init","get_strings","catch","stringReturn","get_string","title","create","type","TYPE","body","done","modal"],"mappings":"kYAuBAA,OAAM,4BAAC,CAAC,UAAD,CAAa,mBAAb,CAAkC,oBAAlC,CAAwD,8BAAxD,CAAwF,gBAAxF,CAA0G,WAA1G,CAAD,CACN,SAASC,CAAT,CAAcC,CAAd,CAA4BC,CAA5B,CAA0CC,CAA1C,CAAsDC,CAAtD,CAAiEC,CAAjE,CAAuE,IAK/DC,CAAAA,CAAO,CAAG,EALqD,CAM/DC,CAN+D,CAO7DC,CAAO,0FAPsD,CAW7DC,CAAS,CAAG,CACd,CAACC,GAAG,CAAE,KAAN,CAAaC,SAAS,CAAE,UAAxB,CADc,CAEd,CAACD,GAAG,CAAE,KAAN,CAAaC,SA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CAGAnF,CAAY,CAACoF,MAAb,CAAoB,CAChBC,IAAI,CAAEpF,CAAU,CAACqF,IADD,CAEhBH,KAAK,CAAEA,CAFS,CAGhBI,IAAI,CAAEjF,CAHU,CAApB,EAKCkF,IALD,CAKM,SAACC,CAAD,CAAW,CACbpF,CAAQ,CAAGoF,CAEd,CARD,CASH,CAbD,EAaGT,KAbH,CAaS,UAAM,CACXjF,CAAY,CAAC6E,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,gCAAV,CAAvB,CACH,CAfD,CAiBH,CArCD,CAuCA,MAAOzE,CAAAA,CACV,CAvLK,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 * Javascript for heatmap calendar generation and display.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/str', 'core/notification', 'core/modal_factory', 'local_assessfreq/modal_large', 'core/templates', 'core/ajax'],\nfunction(Str, Notification, ModalFactory, ModalLarge, Templates, Ajax) {\n\n /**\n * Module level variables.\n */\n var Dayview = {};\n var modalObj;\n const spinner = '

'\n + ''\n + '

';\n\n const stringArr = [\n {key: 'sun', component: 'calendar'},\n {key: 'mon', component: 'calendar'},\n {key: 'tue', component: 'calendar'},\n {key: 'wed', component: 'calendar'},\n {key: 'thu', component: 'calendar'},\n {key: 'fri', component: 'calendar'},\n {key: 'sat', component: 'calendar'},\n {key: 'jan', component: 'local_assessfreq'},\n {key: 'feb', component: 'local_assessfreq'},\n {key: 'mar', component: 'local_assessfreq'},\n {key: 'apr', component: 'local_assessfreq'},\n {key: 'may', component: 'local_assessfreq'},\n {key: 'jun', component: 'local_assessfreq'},\n {key: 'jul', component: 'local_assessfreq'},\n {key: 'aug', component: 'local_assessfreq'},\n {key: 'sep', component: 'local_assessfreq'},\n {key: 'oct', component: 'local_assessfreq'},\n {key: 'nov', component: 'local_assessfreq'},\n {key: 'dec', component: 'local_assessfreq'},\n ];\n var stringResult;\n var systemTimezone = 'Australia/Melbourne';\n var dayViewTitle = '';\n\n const getUserDate = function (timestamp, format) {\n return new Promise((resolve) => {\n const systemTimezoneTime = new Date(timestamp * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n let date = new Date(systemTimezoneTime);\n const year = date.getFullYear();\n const month = stringResult[(7 + date.getMonth())];\n const day = date.getDate();\n const hours = date.getHours();\n const minutes = '0' + date.getMinutes();\n\n const strftimetime = hours + ':' + minutes.substr(-2); // Will display time in 10:30 format.\n const strftimedatetime = day + ' ' + month + ' ' + year + ', ' + strftimetime;\n\n if (format === 'strftimetime') {\n resolve(strftimetime);\n } else {\n resolve(strftimedatetime);\n }\n\n });\n };\n\n const formatData = async function(response) {\n let responseArr = JSON.parse(response);\n\n // We are displaying the event as a bar whose width represents the start and end time of the event.\n // We need to scale the width of the bar to match the width of the container. Therefore 100% width of the container\n // equals 24 hours (one day).\n // There are 1440 mins per day. 1440 mins equals 100%, therefore 1 min = (100/1440)%. 5/72 == 100/1440.\n let scaler = 5 / 72;\n\n for (let i = 0; i < responseArr.length; i++) {\n const year = responseArr[i].endyear;\n const month = (responseArr[i].endmonth) - 1; // Minus 1 for difference between months in PHP and JS.\n const day = responseArr[i].endday;\n const dayStart = (new Date(year, month, day).getTime()) / 1000;\n const timeStart = new Date(responseArr[i].timestart * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n const timeStartTimestamp = (new Date(timeStart).getTime()) / 1000;\n const timeEnd = new Date(responseArr[i].timeend * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n const timeEndTimestamp = (new Date(timeEnd).getTime()) / 1000;\n let secondsSinceDayStart = timeStartTimestamp - dayStart;\n let leftMargin = 0;\n let width = 0;\n\n if (secondsSinceDayStart <= 0) {\n secondsSinceDayStart = 0;\n width = ((timeEndTimestamp - dayStart) / 60) * scaler;\n responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimedatetime');\n } else {\n leftMargin = (secondsSinceDayStart / 60) * scaler;\n width = ((timeEndTimestamp - timeStartTimestamp) / 60) * scaler;\n responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimetime');\n }\n\n if (leftMargin + width > 100) {\n width = 100 - leftMargin;\n }\n\n responseArr[i].leftmargin = leftMargin;\n responseArr[i].width = width;\n responseArr[i].end = await getUserDate(responseArr[i].timeend, 'strftimetime');\n }\n\n return new Promise((resolve) => {\n resolve(responseArr);\n });\n };\n\n /**\n * Initialise the base modal to be used.\n *\n */\n Dayview.display = function(date) {\n modalObj.setBody(spinner);\n modalObj.show();\n let args = {\n date: date,\n modules: ['all']\n };\n let jsonArgs = JSON.stringify(args);\n Ajax.call([{\n methodname: 'local_assessfreq_get_day_events',\n args: {jsondata: jsonArgs},\n }])[0]\n .then(formatData)\n .then((responseArr) => {\n\n let context = {rows: responseArr};\n const year = responseArr[0].endyear;\n const day = responseArr[0].endday;\n const month = stringResult[(6 + parseInt(responseArr[0].endmonth))];\n const dayDate = day + ' ' + month + ' ' + year;\n\n modalObj.setTitle(dayViewTitle + ' ' + dayDate);\n modalObj.setBody(Templates.render('local_assessfreq/dayview', context));\n\n }).fail(() => {\n Notification.exception(new Error('Failed to load day view'));\n });\n };\n\n /**\n * Initialise the base modal to be used.\n *\n * @param {integer} context The current context id.\n */\n Dayview.init = function() {\n // Load the strings we'll need later.\n Str.get_strings(stringArr).catch(() => { // Get required strings.\n Notification.exception(new Error('Failed to load strings'));\n return;\n }).then(stringReturn => { // Save string to global to be used later.\n stringResult = stringReturn;\n });\n\n // Get the system timzone.\n Ajax.call([{\n methodname: 'local_assessfreq_get_system_timezone',\n args: {},\n }], true, false)[0].then((response) => {\n systemTimezone = response;\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get system timezone'));\n });\n\n Str.get_string('schedule', 'local_assessfreq').then((title) => {\n dayViewTitle = title;\n\n // Create the Modal.\n ModalFactory.create({\n type: ModalLarge.TYPE,\n title: title,\n body: spinner\n })\n .done((modal) => {\n modalObj = modal;\n\n });\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: loading'));\n });\n\n };\n\n return Dayview;\n});\n"],"file":"dayview.min.js"} \ No newline at end of file +{"version":3,"file":"dayview.min.js","sources":["../src/dayview.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for heatmap calendar generation and display.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['core/str', 'core/notification', 'core/modal_factory', 'local_assessfreq/modal_large', 'core/templates', 'core/ajax'],\n function (Str, Notification, ModalFactory, ModalLarge, Templates, Ajax) {\n\n /**\n * Module level variables.\n */\n var Dayview = {};\n var modalObj;\n const spinner = '

'\n + ''\n + '

';\n\n const stringArr = [\n {key: 'sun', component: 'calendar'},\n {key: 'mon', component: 'calendar'},\n {key: 'tue', component: 'calendar'},\n {key: 'wed', component: 'calendar'},\n {key: 'thu', component: 'calendar'},\n {key: 'fri', component: 'calendar'},\n {key: 'sat', component: 'calendar'},\n {key: 'jan', component: 'local_assessfreq'},\n {key: 'feb', component: 'local_assessfreq'},\n {key: 'mar', component: 'local_assessfreq'},\n {key: 'apr', component: 'local_assessfreq'},\n {key: 'may', component: 'local_assessfreq'},\n {key: 'jun', component: 'local_assessfreq'},\n {key: 'jul', component: 'local_assessfreq'},\n {key: 'aug', component: 'local_assessfreq'},\n {key: 'sep', component: 'local_assessfreq'},\n {key: 'oct', component: 'local_assessfreq'},\n {key: 'nov', component: 'local_assessfreq'},\n {key: 'dec', component: 'local_assessfreq'},\n ];\n var stringResult;\n var systemTimezone = 'Australia/Melbourne';\n var dayViewTitle = '';\n\n const getUserDate = function (timestamp, format) {\n return new Promise((resolve) => {\n const systemTimezoneTime = new Date(timestamp * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n let date = new Date(systemTimezoneTime);\n const year = date.getFullYear();\n const month = stringResult[(7 + date.getMonth())];\n const day = date.getDate();\n const hours = date.getHours();\n const minutes = '0' + date.getMinutes();\n\n const strftimetime = hours + ':' + minutes.substr(-2); // Will display time in 10:30 format.\n const strftimedatetime = day + ' ' + month + ' ' + year + ', ' + strftimetime;\n\n if (format === 'strftimetime') {\n resolve(strftimetime);\n } else {\n resolve(strftimedatetime);\n }\n\n });\n };\n\n const formatData = async function (response) {\n let responseArr = JSON.parse(response);\n\n // We are displaying the event as a bar whose width represents the start and end time of the event.\n // We need to scale the width of the bar to match the width of the container. Therefore 100% width of the container\n // equals 24 hours (one day).\n // There are 1440 mins per day. 1440 mins equals 100%, therefore 1 min = (100/1440)%. 5/72 == 100/1440.\n let scaler = 5 / 72;\n\n for (let i = 0; i < responseArr.length; i++) {\n const year = responseArr[i].endyear;\n const month = (responseArr[i].endmonth) - 1; // Minus 1 for difference between months in PHP and JS.\n const day = responseArr[i].endday;\n const dayStart = (new Date(year, month, day).getTime()) / 1000;\n const timeStart = new Date(responseArr[i].timestart * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n const timeStartTimestamp = (new Date(timeStart).getTime()) / 1000;\n const timeEnd = new Date(responseArr[i].timeend * 1000).toLocaleString('en-US', {timeZone: systemTimezone});\n const timeEndTimestamp = (new Date(timeEnd).getTime()) / 1000;\n let secondsSinceDayStart = timeStartTimestamp - dayStart;\n let leftMargin = 0;\n let width = 0;\n\n if (secondsSinceDayStart <= 0) {\n secondsSinceDayStart = 0;\n width = ((timeEndTimestamp - dayStart) / 60) * scaler;\n responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimedatetime');\n } else {\n leftMargin = (secondsSinceDayStart / 60) * scaler;\n width = ((timeEndTimestamp - timeStartTimestamp) / 60) * scaler;\n responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimetime');\n }\n\n if (leftMargin + width > 100) {\n width = 100 - leftMargin;\n }\n\n responseArr[i].leftmargin = leftMargin;\n responseArr[i].width = width;\n responseArr[i].end = await getUserDate(responseArr[i].timeend, 'strftimetime');\n }\n\n return new Promise((resolve) => {\n resolve(responseArr);\n });\n };\n\n /**\n * Initialise the base modal to be used.\n *\n */\n Dayview.display = function (date) {\n modalObj.setBody(spinner);\n modalObj.show();\n let args = {\n date: date,\n modules: ['all']\n };\n let jsonArgs = JSON.stringify(args);\n Ajax.call([{\n methodname: 'local_assessfreq_get_day_events',\n args: {jsondata: jsonArgs},\n }])[0]\n .then(formatData)\n .then((responseArr) => {\n\n let context = {rows: responseArr};\n const year = responseArr[0].endyear;\n const day = responseArr[0].endday;\n const month = stringResult[(6 + parseInt(responseArr[0].endmonth))];\n const dayDate = day + ' ' + month + ' ' + year;\n\n modalObj.setTitle(dayViewTitle + ' ' + dayDate);\n modalObj.setBody(Templates.render('local_assessfreq/dayview', context));\n\n }).fail(() => {\n Notification.exception(new Error('Failed to load day view'));\n });\n };\n\n /**\n * Initialise the base modal to be used.\n *\n * @param {integer} context The current context id.\n */\n Dayview.init = function () {\n // Load the strings we'll need later.\n Str.get_strings(stringArr).then(stringReturn => { // Save string to global to be used later.\n stringResult = stringReturn;\n });\n\n // Get the system timzone.\n Ajax.call([{\n methodname: 'local_assessfreq_get_system_timezone',\n args: {},\n }], true, false)[0].then((response) => {\n systemTimezone = response;\n return;\n }).fail(() => {\n Notification.exception(new Error('Failed to get system timezone'));\n });\n\n Str.get_string('schedule', 'local_assessfreq').then((title) => {\n dayViewTitle = title;\n\n // Create the Modal.\n ModalFactory.create({\n type: ModalLarge.TYPE,\n title: title,\n body: spinner\n })\n .done((modal) => {\n modalObj = modal;\n\n });\n });\n\n };\n\n return Dayview;\n }\n);\n"],"names":["define","Str","Notification","ModalFactory","ModalLarge","Templates","Ajax","modalObj","Dayview","spinner","stringArr","key","component","stringResult","systemTimezone","dayViewTitle","getUserDate","timestamp","format","Promise","resolve","systemTimezoneTime","Date","toLocaleString","timeZone","date","year","getFullYear","month","getMonth","day","getDate","strftimetime","getHours","getMinutes","substr","formatData","async","response","responseArr","JSON","parse","scaler","i","length","endyear","endmonth","endday","dayStart","getTime","timeStart","timestart","timeStartTimestamp","timeEnd","timeend","timeEndTimestamp","secondsSinceDayStart","leftMargin","width","start","leftmargin","end","display","setBody","show","args","modules","jsonArgs","stringify","call","methodname","jsondata","then","context","rows","dayDate","parseInt","setTitle","render","fail","exception","Error","init","get_strings","stringReturn","get_string","title","create","type","TYPE","body","done","modal"],"mappings":";;;;;;;AAuBAA,kCACI,CAAC,WAAY,oBAAqB,qBAAsB,+BAAgC,iBAAkB,cAC1G,SAAUC,IAAKC,aAAcC,aAAcC,WAAYC,UAAWC,UAM1DC,SADAC,QAAU,SAERC,QAAU,sFAIVC,UAAY,CACd,CAACC,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,YACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,IAAK,MAAOC,UAAW,oBACxB,CAACD,I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GAAO,GAAGO,MAAMlC,WACtBxB,eAAiBwB,YAElByC,MAAK,KACJ7E,aAAa8E,UAAU,IAAIC,MAAM,qCAGrChF,IAAIoF,WAAW,WAAY,oBAAoBb,MAAMc,QACjDvE,aAAeuE,MAGfnF,aAAaoF,OAAO,CAChBC,KAAMpF,WAAWqF,KACjBH,MAAOA,MACPI,KAAMjF,UAETkF,MAAMC,QACHrF,SAAWqF,aAOhBpF"} \ No newline at end of file diff --git a/amd/build/debouncer.min.js b/amd/build/debouncer.min.js index 20d1b83..1fca9c8 100644 --- a/amd/build/debouncer.min.js +++ b/amd/build/debouncer.min.js @@ -1,2 +1,3 @@ -define ("local_assessfreq/debouncer",["exports"],function(a){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.debouncer=void 0;a.debouncer=function debouncer(a,b){var c;return function(){for(var d=arguments.length,e=Array(d),f=0;f{let timeout;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];const later=()=>{clearTimeout(timeout),func(...args)};clearTimeout(timeout),timeout=setTimeout(later,wait)}}})); + +//# sourceMappingURL=debouncer.min.js.map \ No newline at end of file diff --git a/amd/build/debouncer.min.js.map b/amd/build/debouncer.min.js.map index 7668fcb..9479d9c 100644 --- a/amd/build/debouncer.min.js.map +++ b/amd/build/debouncer.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/debouncer.js"],"names":["debouncer","func","wait","timeout","args","later","clearTimeout","setTimeout"],"mappings":"0JAmCyB,QAAZA,CAAAA,SAAY,CAACC,CAAD,CAAOC,CAAP,CAAgB,CACrC,GAAIC,CAAAA,CAAJ,CAEA,MAAO,WAAmC,4BAANC,CAAM,uBAANA,CAAM,iBACtC,GAAMC,CAAAA,CAAK,CAAG,UAAM,CAChBC,YAAY,CAACH,CAAD,CAAZ,CACAF,CAAI,MAAJ,QAAQG,CAAR,CACH,CAHD,CAKAE,YAAY,CAACH,CAAD,CAAZ,CACAA,CAAO,CAAGI,UAAU,CAACF,CAAD,CAAQH,CAAR,CACvB,CACJ,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 * Debounce JS module.\n *\n * @module local_assessfreq/debouncer\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n *\n */\n\n/**\n * Quick and dirty debounce method for the settings.\n * This stops the ajax method that updates the table from being updated\n * while the user is still checking options.\n *\n * @method debouncer\n * @param {function} func The function we want to keep calling.\n * @param {number} wait Our timeout.\n * @return {function}\n */\nexport const debouncer = (func, wait) => {\n let timeout;\n\n return function executedFunction(...args) {\n const later = () => {\n clearTimeout(timeout);\n func(...args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n};\n"],"file":"debouncer.min.js"} \ No newline at end of file +{"version":3,"file":"debouncer.min.js","sources":["../src/debouncer.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Debounce JS module.\n *\n * @module local_assessfreq/debouncer\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n *\n */\n\n/**\n * Quick and dirty debounce method for the settings.\n * This stops the ajax method that updates the table from being updated\n * while the user is still checking options.\n *\n * @method debouncer\n * @param {function} func The function we want to keep calling.\n * @param {number} wait Our timeout.\n * @return {function}\n */\nexport const debouncer = (func, wait) => {\n let timeout;\n\n return function executedFunction(...args) {\n const later = () => {\n clearTimeout(timeout);\n func(...args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n};\n"],"names":["func","wait","timeout","args","later","clearTimeout","setTimeout"],"mappings":"yKAmCyB,CAACA,KAAMC,YACxBC,eAEG,yCAA6BC,6CAAAA,iCAC1BC,MAAQ,KACVC,aAAaH,SACbF,QAAQG,OAGZE,aAAaH,SACbA,QAAUI,WAAWF,MAAOH"} \ No newline at end of file diff --git a/amd/build/form_modal.min.js b/amd/build/form_modal.min.js index 63bcb0f..8a132d9 100644 --- a/amd/build/form_modal.min.js +++ b/amd/build/form_modal.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/form_modal",["core/str","core/modal_factory","core/fragment","core/ajax"],function(a,b,c,d){var e={},f,g,h=[],i,j="

",k={attributes:!0,childList:!1,subtree:!0},l=new MutationObserver(function ObserverCallback(a){for(var b=0,c;bd){if(null===document.getElementById("noquizwarning")){a.get_string("noquizselected","local_assessfreq").then(function(a){var b=document.createElement("div");b.innerHTML=a;b.id="noquizwarning";b.classList.add("alert","alert-danger");g.getBody().prepend(b)}).catch(function(){Notification.exception(new Error("Failed to load string: searchquiz"))})}}else{g.hide();g.setBody("");l.disconnect();i(d,e)}},q=function(){o();g.show()};e.init=function(a,b){f=a;i=b;m();var c=document.getElementById("local-assessfreq-find-quiz");c.addEventListener("click",q)};return e}); -//# sourceMappingURL=form_modal.min.js.map +/** + * Javascript for report card display and processing. + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/form_modal",["core/str","core/modal_factory","core/fragment","core/ajax"],(function(Str,ModalFactory,Fragment,Ajax){var contextid,modalObj,callback,FormModal={},resetOptions=[];const spinner='

',observerConfig={attributes:!0,childList:!1,subtree:!0},observer=new MutationObserver((function(mutationsList){for(let i=0;i{let quizArray=JSON.parse(response),selectElement=document.getElementById("id_quiz"),selectElementLength=selectElement.options.length;null!==document.getElementById("noquizwarning")&&document.getElementById("noquizwarning").remove();for(let j=selectElementLength-1;j>=0;j--)selectElement.options[j]=null;if(quizArray.length>0){for(let k=0;k{selectElement.appendChild(option)})),document.getElementById("id_quiz").value=0,selectElement.disabled=!0})).fail((()=>{Notification.exception(new Error("Failed to get quizzes"))}));break}}})),updateModalBody=function(formdata){void 0===formdata&&(formdata={});let params={jsonformdata:JSON.stringify(formdata)};new Promise(((resolve,reject)=>{Str.get_strings([{key:"selectcourse",component:"local_assessfreq"},{key:"loadingquiz",component:"local_assessfreq"}]).catch((()=>{reject(new Error("Failed to load strings"))})).then((stringReturn=>{for(let i=0;i{Str.get_string("searchquiz","local_assessfreq").then((title=>{modalObj.setTitle(title),modalObj.setBody(Fragment.loadFragment("local_assessfreq","new_base_form",contextid,params));let modalContainer=document.querySelectorAll('[data-region*="modal-container"]')[0];observer.observe(modalContainer,observerConfig)}))}))},processModalForm=function(e){e.preventDefault();let quizElement=document.getElementById("id_quiz"),quizId=quizElement.options[quizElement.selectedIndex].value,courseId=document.getElementById("id_courses").dataset.course;void 0===courseId||quizId<1?null===document.getElementById("noquizwarning")&&Str.get_string("noquizselected","local_assessfreq").then((warning=>{let element=document.createElement("div");element.innerHTML=warning,element.id="noquizwarning",element.classList.add("alert","alert-danger"),modalObj.getBody().prepend(element)})):(modalObj.hide(),modalObj.setBody(""),observer.disconnect(),callback(quizId,courseId))},displayModalForm=function(){updateModalBody(),modalObj.show()};return FormModal.init=function(context,processDashboard){contextid=context,callback=processDashboard,Str.get_string("loading","local_assessfreq").then((title=>{ModalFactory.create({type:ModalFactory.types.DEFAULT,title:title,body:spinner,large:!0}).done((modal=>{(modalObj=modal).getRoot().on("click","#id_submitbutton",processModalForm),modalObj.getRoot().on("click","#id_cancel",(e=>{e.preventDefault(),modalObj.setBody(spinner),modalObj.hide()}))}))})),document.getElementById("local-assessfreq-find-quiz").addEventListener("click",displayModalForm)},FormModal})); + +//# sourceMappingURL=form_modal.min.js.map \ No newline at end of file diff --git a/amd/build/form_modal.min.js.map b/amd/build/form_modal.min.js.map index 7411e0b..2a29c5e 100644 --- a/amd/build/form_modal.min.js.map +++ b/amd/build/form_modal.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/form_modal.js"],"names":["define","Str","ModalFactory","Fragment","Ajax","FormModal","contextid","modalObj","resetOptions","callback","spinner","observerConfig","attributes","childList","subtree","observer","MutationObserver","ObserverCallback","mutationsList","i","element","length","target","tagName","toLowerCase","classList","contains","addEventListener","updateModalBody","document","getElementById","dataset","course","value","call","methodname","args","query","done","response","quizArray","JSON","parse","selectElement","selectElementLength","options","remove","j","k","opt","el","createElement","textContent","name","id","appendChild","removeAttribute","forEach","option","disabled","fail","Notification","exception","Error","createModal","get_string","then","title","create","type","types","DEFAULT","body","large","modal","getRoot","on","processModalForm","e","preventDefault","setBody","hide","catch","getOptionPlaceholders","Promise","resolve","reject","get_strings","key","component","stringReturn","push","formdata","params","stringify","setTitle","loadFragment","modalContainer","querySelectorAll","observe","quizElement","quizId","selectedIndex","courseId","warning","innerHTML","add","getBody","prepend","disconnect","displayModalForm","show","init","context","processDashboard","createBroadcastButton"],"mappings":"AAuBAA,OAAM,+BAAC,CAAC,UAAD,CAAa,oBAAb,CAAmC,eAAnC,CAAoD,WAApD,CAAD,CACN,SAASC,CAAT,CAAcC,CAAd,CAA4BC,CAA5B,CAAsCC,CAAtC,CAA4C,IAKpCC,CAAAA,CAAS,CAAG,EALwB,CAMpCC,CANoC,CAOpCC,CAPoC,CAQpCC,CAAY,CAAG,EARqB,CASpCC,CAToC,CAWlCC,CAAO,0FAX2B,CAelCC,CAAc,CAAG,CAAEC,UAAU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A3MuC,CAgNxC1G,CAAS,CAAC2G,IAAV,CAAiB,SAASC,CAAT,CAAkBC,CAAlB,CAAoC,CACjD5G,CAAS,CAAG2G,CAAZ,CACAxG,CAAQ,CAAGyG,CAAX,CACAlD,CAAW,GAEX,GAAImD,CAAAA,CAAqB,CAAGtF,QAAQ,CAACC,cAAT,CAAwB,4BAAxB,CAA5B,CACAqF,CAAqB,CAACxF,gBAAtB,CAAuC,OAAvC,CAAgDmF,CAAhD,CACH,CAPD,CASA,MAAOzG,CAAAA,CACV,CA3NK,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 * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax'],\nfunction(Str, ModalFactory, Fragment, Ajax) {\n\n /**\n * Module level variables.\n */\n var FormModal = {};\n var contextid;\n var modalObj;\n var resetOptions = [];\n var callback;\n\n const spinner = '

'\n + ''\n + '

';\n\n const observerConfig = { attributes: true, childList: false, subtree: true };\n\n const ObserverCallback = function(mutationsList) {\n for (let i = 0; i < mutationsList.length; i++) {\n let element = mutationsList[i].target;\n if(element.tagName.toLowerCase() === 'span' && element.classList.contains('badge')) {\n element.addEventListener('click', updateModalBody);\n document.getElementById('id_courses').dataset.course = element.dataset.value;\n\n document.getElementById('id_quiz').value = -1;\n Ajax.call([{\n methodname: 'local_assessfreq_get_quizzes',\n args: {\n query: mutationsList[i].target.dataset.value\n },\n }])[0].done((response) => {\n let quizArray = JSON.parse(response);\n let selectElement = document.getElementById('id_quiz');\n let selectElementLength = selectElement.options.length;\n if (document.getElementById('noquizwarning') !== null) {\n document.getElementById('noquizwarning').remove();\n }\n // Clear exisitng options.\n for (let j = selectElementLength - 1; j >= 0; j--) {\n selectElement.options[j] = null;\n }\n\n if (quizArray.length > 0) {\n\n // Add new options.\n for (let k = 0; k < quizArray.length; k++) {\n let opt = quizArray[k];\n let el = document.createElement('option');\n el.textContent = opt.name;\n el.value = opt.id;\n selectElement.appendChild(el);\n }\n selectElement.removeAttribute('disabled');\n if (document.getElementById('noquizwarning') !== null) {\n document.getElementById('noquizwarning').remove();\n }\n } else {\n resetOptions.forEach((option) => {\n selectElement.appendChild(option);\n });\n document.getElementById('id_quiz').value = 0;\n selectElement.disabled = true;\n }\n\n }).fail(() => {\n Notification.exception(new Error('Failed to get quizzes'));\n });\n\n break;\n }\n\n }\n };\n\n const observer = new MutationObserver(ObserverCallback);\n\n /**\n * Create the modal window.\n *\n * @private\n */\n const createModal = function() {\n Str.get_string('loading', 'local_assessfreq').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalFactory.types.DEFAULT,\n title: title,\n body: spinner,\n large: true\n })\n .done((modal) => {\n modalObj = modal;\n\n // Explicitly handle form click events.\n modalObj.getRoot().on('click', '#id_submitbutton', processModalForm);\n modalObj.getRoot().on('click', '#id_cancel', (e) => {\n e.preventDefault();\n modalObj.setBody(spinner);\n modalObj.hide();\n });\n });\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: loading'));\n });\n };\n\n const getOptionPlaceholders = function() {\n return new Promise((resolve, reject) => {\n const stringArr = [\n {key: 'selectcourse', component: 'local_assessfreq'},\n {key: 'loadingquiz', component: 'local_assessfreq'},\n ];\n\n Str.get_strings(stringArr).catch(() => { // Get required strings.\n reject(new Error('Failed to load strings'));\n return;\n }).then(stringReturn => { // Save string to global to be used later.\n for (let i = 0; i < stringReturn.length; i++) {\n let el = document.createElement('option');\n el.textContent = stringReturn[i];\n el.value = 0 - i;\n resetOptions.push(el);\n }\n resolve();\n });\n });\n };\n\n /**\n * Updates the body of the modal window.\n *\n * @param {Object} formdata\n * @private\n */\n const updateModalBody = function(formdata) {\n if (typeof formdata === \"undefined\") {\n formdata = {};\n }\n\n let params = {\n 'jsonformdata': JSON.stringify(formdata)\n };\n\n getOptionPlaceholders()\n .then(() => {\n Str.get_string('searchquiz', 'local_assessfreq').then((title) => {\n modalObj.setTitle(title);\n modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_base_form', contextid, params));\n let modalContainer = document.querySelectorAll('[data-region*=\"modal-container\"]')[0];\n observer.observe(modalContainer, observerConfig);\n\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: searchquiz'));\n });\n });\n };\n\n /**\n * Updates Moodle form with selected information.\n *\n * @param {Object} e\n * @private\n */\n const processModalForm = function(e) {\n e.preventDefault(); // Stop modal from closing.\n\n let quizElement = document.getElementById('id_quiz');\n let quizId = quizElement.options[quizElement.selectedIndex].value;\n let courseId = document.getElementById('id_courses').dataset.course;\n\n if (courseId === undefined || quizId < 1) {\n if (document.getElementById('noquizwarning') === null) {\n Str.get_string('noquizselected', 'local_assessfreq').then((warning) => {\n let element = document.createElement('div');\n element.innerHTML = warning;\n element.id = 'noquizwarning';\n element.classList.add('alert', 'alert-danger');\n modalObj.getBody().prepend(element);\n\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: searchquiz'));\n });\n\n }\n\n } else {\n modalObj.hide(); // Close modal.\n modalObj.setBody(''); // Cleaer form.\n observer.disconnect(); // Remove observer.\n callback(quizId, courseId); // Trigger dashboard update.\n }\n\n };\n\n /**\n * Display the Modal form.\n */\n const displayModalForm = function() {\n updateModalBody();\n modalObj.show();\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n FormModal.init = function(context, processDashboard) {\n contextid = context;\n callback = processDashboard;\n createModal();\n\n let createBroadcastButton = document.getElementById('local-assessfreq-find-quiz');\n createBroadcastButton.addEventListener('click', displayModalForm);\n };\n\n return FormModal;\n});\n"],"file":"form_modal.min.js"} \ No newline at end of file +{"version":3,"file":"form_modal.min.js","sources":["../src/form_modal.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax'],\n function (Str, ModalFactory, Fragment, Ajax) {\n\n /**\n * Module level variables.\n */\n var FormModal = {};\n var contextid;\n var modalObj;\n var resetOptions = [];\n var callback;\n\n const spinner = '

'\n + ''\n + '

';\n\n const observerConfig = { attributes: true, childList: false, subtree: true };\n\n const ObserverCallback = function (mutationsList) {\n for (let i = 0; i < mutationsList.length; i++) {\n let element = mutationsList[i].target;\n if (element.tagName.toLowerCase() === 'span' && element.classList.contains('badge')) {\n element.addEventListener('click', updateModalBody);\n document.getElementById('id_courses').dataset.course = element.dataset.value;\n\n document.getElementById('id_quiz').value = -1;\n Ajax.call([{\n methodname: 'local_assessfreq_get_quizzes',\n args: {\n query: mutationsList[i].target.dataset.value\n },\n }])[0].done((response) => {\n let quizArray = JSON.parse(response);\n let selectElement = document.getElementById('id_quiz');\n let selectElementLength = selectElement.options.length;\n if (document.getElementById('noquizwarning') !== null) {\n document.getElementById('noquizwarning').remove();\n }\n // Clear exisitng options.\n for (let j = selectElementLength - 1; j >= 0; j--) {\n selectElement.options[j] = null;\n }\n\n if (quizArray.length > 0) {\n // Add new options.\n for (let k = 0; k < quizArray.length; k++) {\n let opt = quizArray[k];\n let el = document.createElement('option');\n el.textContent = opt.name;\n el.value = opt.id;\n selectElement.appendChild(el);\n }\n selectElement.removeAttribute('disabled');\n if (document.getElementById('noquizwarning') !== null) {\n document.getElementById('noquizwarning').remove();\n }\n } else {\n resetOptions.forEach((option) => {\n selectElement.appendChild(option);\n });\n document.getElementById('id_quiz').value = 0;\n selectElement.disabled = true;\n }\n\n }).fail(() => {\n Notification.exception(new Error('Failed to get quizzes'));\n });\n\n break;\n }\n }\n };\n\n const observer = new MutationObserver(ObserverCallback);\n\n /**\n * Create the modal window.\n *\n * @private\n */\n const createModal = function () {\n Str.get_string('loading', 'local_assessfreq').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalFactory.types.DEFAULT,\n title: title,\n body: spinner,\n large: true\n })\n .done((modal) => {\n modalObj = modal;\n\n // Explicitly handle form click events.\n modalObj.getRoot().on('click', '#id_submitbutton', processModalForm);\n modalObj.getRoot().on('click', '#id_cancel', (e) => {\n e.preventDefault();\n modalObj.setBody(spinner);\n modalObj.hide();\n });\n });\n return;\n });\n };\n\n const getOptionPlaceholders = function () {\n return new Promise((resolve, reject) => {\n const stringArr = [\n {key: 'selectcourse', component: 'local_assessfreq'},\n {key: 'loadingquiz', component: 'local_assessfreq'},\n ];\n\n Str.get_strings(stringArr).catch(() => { // Get required strings.\n reject(new Error('Failed to load strings'));\n return;\n }).then(stringReturn => { // Save string to global to be used later.\n for (let i = 0; i < stringReturn.length; i++) {\n let el = document.createElement('option');\n el.textContent = stringReturn[i];\n el.value = 0 - i;\n resetOptions.push(el);\n }\n resolve();\n });\n });\n };\n\n /**\n * Updates the body of the modal window.\n *\n * @param {Object} formdata\n * @private\n */\n const updateModalBody = function (formdata) {\n if (typeof formdata === \"undefined\") {\n formdata = {};\n }\n\n let params = {\n 'jsonformdata': JSON.stringify(formdata)\n };\n\n getOptionPlaceholders()\n .then(() => {\n Str.get_string('searchquiz', 'local_assessfreq').then((title) => {\n modalObj.setTitle(title);\n modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_base_form', contextid, params));\n let modalContainer = document.querySelectorAll('[data-region*=\"modal-container\"]')[0];\n observer.observe(modalContainer, observerConfig);\n\n return;\n });\n });\n };\n\n /**\n * Updates Moodle form with selected information.\n *\n * @param {Object} e\n * @private\n */\n const processModalForm = function (e) {\n e.preventDefault(); // Stop modal from closing.\n\n let quizElement = document.getElementById('id_quiz');\n let quizId = quizElement.options[quizElement.selectedIndex].value;\n let courseId = document.getElementById('id_courses').dataset.course;\n\n if (courseId === undefined || quizId < 1) {\n if (document.getElementById('noquizwarning') === null) {\n Str.get_string('noquizselected', 'local_assessfreq').then((warning) => {\n let element = document.createElement('div');\n element.innerHTML = warning;\n element.id = 'noquizwarning';\n element.classList.add('alert', 'alert-danger');\n modalObj.getBody().prepend(element);\n\n return;\n });\n }\n } else {\n modalObj.hide(); // Close modal.\n modalObj.setBody(''); // Cleaer form.\n observer.disconnect(); // Remove observer.\n callback(quizId, courseId); // Trigger dashboard update.\n }\n\n };\n\n /**\n * Display the Modal form.\n */\n const displayModalForm = function () {\n updateModalBody();\n modalObj.show();\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n FormModal.init = function (context, processDashboard) {\n contextid = context;\n callback = processDashboard;\n createModal();\n\n let createBroadcastButton = document.getElementById('local-assessfreq-find-quiz');\n createBroadcastButton.addEventListener('click', displayModalForm);\n };\n\n return FormModal;\n }\n);\n"],"names":["define","Str","ModalFactory","Fragment","Ajax","contextid","modalObj","callback","FormModal","resetOptions","spinner","observerConfig","attributes","childList","subtree","observer","MutationObserver","mutationsList","i","length","element","target","tagName","toLowerCase","classList","contains","addEventListener","updateModalBody","document","getElementById","dataset","course","value","call","methodname","args","query","done","response","quizArray","JSON","parse","selectElement","selectElementLength","options","remove","j","k","opt","el","createElement","textContent","name","id","appendChild","removeAttribute","forEach","option","disabled","fail","Notification","exception","Error","formdata","params","stringify","Promise","resolve","reject","get_strings","key","component","catch","then","stringReturn","push","get_string","title","setTitle","setBody","loadFragment","modalContainer","querySelectorAll","observe","processModalForm","e","preventDefault","quizElement","quizId","selectedIndex","courseId","undefined","warning","innerHTML","add","getBody","prepend","hide","disconnect","displayModalForm","show","init","context","processDashboard","create","type","types","DEFAULT","body","large","modal","getRoot","on"],"mappings":";;;;;;;AAuBAA,qCACI,CAAC,WAAY,qBAAsB,gBAAiB,cACpD,SAAUC,IAAKC,aAAcC,SAAUC,UAM/BC,UACAC,SAEAC,SAJAC,UAAY,GAGZC,aAAe,SAGbC,QAAU,sFAIVC,eAAiB,CAAEC,YAAY,EAAMC,WAAW,EAAOC,SAAS,GAyDhEC,SAAW,IAAIC,kBAvDI,SAAUC,mBAC1B,IAAIC,EAAI,EAAGA,EAAID,cAAcE,OAAQD,IAAK,KACvCE,QAAUH,cAAcC,GAAGG,UACO,SAAlCD,QAAQE,QAAQC,eAA4BH,QAAQI,UAAUC,SAAS,SAAU,CACjFL,QAAQM,iBAAiB,QAASC,iBAClCC,SAASC,eAAe,cAAcC,QAAQC,OAASX,QAAQU,QAAQE,MAEvEJ,SAASC,eAAe,WAAWG,OAAS,EAC5C5B,KAAK6B,KAAK,CAAC,CACPC,WAAY,+BACZC,KAAM,CACFC,MAAOnB,cAAcC,GAAGG,OAAOS,QAAQE,UAE3C,GAAGK,MAAMC,eACLC,UAAYC,KAAKC,MAAMH,UACvBI,cAAgBd,SAASC,eAAe,WACxCc,oBAAsBD,cAAcE,QAAQzB,OACC,OAA7CS,SAASC,eAAe,kBACxBD,SAASC,eAAe,iBAAiBgB,aAGxC,IAAIC,EAAIH,oBAAsB,EAAGG,GAAK,EAAGA,IAC1CJ,cAAcE,QAAQE,GAAK,QAG3BP,UAAUpB,OAAS,EAAG,KAEjB,IAAI4B,EAAI,EAAGA,EAAIR,UAAUpB,OAAQ4B,IAAK,KACnCC,IAAMT,UAAUQ,GAChBE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B5B,IAAI2E,WAAW,iBAAkB,oBAAoBH,MAAMmB,cACnDxE,QAAUQ,SAASsB,cAAc,OACrC9B,QAAQyE,UAAYD,QACpBxE,QAAQiC,GAAK,gBACbjC,QAAQI,UAAUsE,IAAI,QAAS,gBAC/BxF,SAASyF,UAAUC,QAAQ5E,aAMnCd,SAAS2F,OACT3F,SAASyE,QAAQ,IACjBhE,SAASmF,aACT3F,SAASiF,OAAQE,YAQnBS,iBAAmB,WACrBxE,kBACArB,SAAS8F,eAMb5F,UAAU6F,KAAO,SAAUC,QAASC,kBAChClG,UAAYiG,QACZ/F,SAAWgG,iBAxHXtG,IAAI2E,WAAW,UAAW,oBAAoBH,MAAMI,QAEhD3E,aAAasG,OAAO,CAChBC,KAAMvG,aAAawG,MAAMC,QACzB9B,MAAOA,MACP+B,KAAMlG,QACNmG,OAAO,IAEVxE,MAAMyE,SACHxG,SAAWwG,OAGFC,UAAUC,GAAG,QAAS,mBAAoB5B,kBACnD9E,SAASyG,UAAUC,GAAG,QAAS,cAAe3B,IAC1CA,EAAEC,iBACFhF,SAASyE,QAAQrE,SACjBJ,SAAS2F,gBA2GOrE,SAASC,eAAe,8BAC9BH,iBAAiB,QAASyE,mBAG7C3F"} \ No newline at end of file diff --git a/amd/build/modal_large.min.js b/amd/build/modal_large.min.js index 122e248..b8eb94e 100644 --- a/amd/build/modal_large.min.js +++ b/amd/build/modal_large.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/modal_large",["jquery","core/notification","core/custom_interaction_events","core/modal","core/modal_registry"],function(a,b,c,d,e){var f=!1,g=function(a){d.call(this,a)};g.TYPE="local_assesfreq-large_modal";g.prototype=Object.create(d.prototype);g.prototype.constructor=g;g.prototype.registerEventListeners=function(){d.prototype.registerEventListeners.call(this)};if(!f){e.register(g.TYPE,g,"local_assessfreq/modal_large");f=!0}return g}); -//# sourceMappingURL=modal_large.min.js.map +/** + * Javascript for large modal . + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/modal_large",["jquery","core/notification","core/custom_interaction_events","core/modal","core/modal_registry"],(function($,Notification,CustomEvents,Modal,ModalRegistry){var registered=!1,ModalLarge=function(root){Modal.call(this,root)};return ModalLarge.TYPE="local_assesfreq-large_modal",(ModalLarge.prototype=Object.create(Modal.prototype)).constructor=ModalLarge,ModalLarge.prototype.registerEventListeners=function(){Modal.prototype.registerEventListeners.call(this)},registered||(ModalRegistry.register(ModalLarge.TYPE,ModalLarge,"local_assessfreq/modal_large"),registered=!0),ModalLarge})); + +//# sourceMappingURL=modal_large.min.js.map \ No newline at end of file diff --git a/amd/build/modal_large.min.js.map b/amd/build/modal_large.min.js.map index 60ee910..cc525a1 100644 --- a/amd/build/modal_large.min.js.map +++ b/amd/build/modal_large.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/modal_large.js"],"names":["define","$","Notification","CustomEvents","Modal","ModalRegistry","registered","ModalLarge","root","call","TYPE","prototype","Object","create","constructor","registerEventListeners","register"],"mappings":"AAuBAA,OAAM,gCAAC,CAAC,QAAD,CAAW,mBAAX,CAAgC,gCAAhC,CAAkE,YAAlE,CAAgF,qBAAhF,CAAD,CACN,SAASC,CAAT,CAAYC,CAAZ,CAA0BC,CAA1B,CAAwCC,CAAxC,CAA+CC,CAA/C,CAA8D,IAEtDC,CAAAA,CAAU,GAF4C,CAStDC,CAAU,CAAG,SAASC,CAAT,CAAe,CAC5BJ,CAAK,CAACK,IAAN,CAAW,IAAX,CAAiBD,CAAjB,CACH,CAXyD,CAa1DD,CAAU,CAACG,IAAX,CAAkB,6BAAlB,CACAH,CAAU,CAACI,SAAX,CAAuBC,MAAM,CAACC,MAAP,CAAcT,CAAK,CAACO,SAApB,CAAvB,CACAJ,CAAU,CAACI,SAAX,CAAqBG,WAArB,CAAmCP,CAAnC,CAOAA,CAAU,CAACI,SAAX,CAAqBI,sBAArB,CAA8C,UAAW,CAErDX,CAAK,CAACO,SAAN,CAAgBI,sBAAhB,CAAuCN,IAAvC,CAA4C,IAA5C,CACH,CAHD,CAOA,GAAI,CAACH,CAAL,CAAiB,CACbD,CAAa,CAACW,QAAd,CAAuBT,CAAU,CAACG,IAAlC,CAAwCH,CAAxC,CAAoD,8BAApD,EACAD,CAAU,GACb,CAED,MAAOC,CAAAA,CACV,CApCK,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 * Javascript for large modal .\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery', 'core/notification', 'core/custom_interaction_events', 'core/modal', 'core/modal_registry'],\nfunction($, Notification, CustomEvents, Modal, ModalRegistry) {\n\n var registered = false;\n\n /**\n * Constructor for the Modal.\n *\n * @param {object} root The root jQuery element for the modal\n */\n var ModalLarge = function(root) {\n Modal.call(this, root);\n };\n\n ModalLarge.TYPE = 'local_assesfreq-large_modal';\n ModalLarge.prototype = Object.create(Modal.prototype);\n ModalLarge.prototype.constructor = ModalLarge;\n\n /**\n * Set up all of the event handling for the modal.\n *\n * @method registerEventListeners\n */\n ModalLarge.prototype.registerEventListeners = function() {\n // Apply parent event listeners.\n Modal.prototype.registerEventListeners.call(this);\n };\n\n // Automatically register with the modal registry the first time this module is imported so that you can create modals\n // of this type using the modal factory.\n if (!registered) {\n ModalRegistry.register(ModalLarge.TYPE, ModalLarge, 'local_assessfreq/modal_large');\n registered = true;\n }\n\n return ModalLarge;\n});"],"file":"modal_large.min.js"} \ No newline at end of file +{"version":3,"file":"modal_large.min.js","sources":["../src/modal_large.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for large modal .\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['jquery', 'core/notification', 'core/custom_interaction_events', 'core/modal', 'core/modal_registry'],\n function ($, Notification, CustomEvents, Modal, ModalRegistry) {\n\n var registered = false;\n\n /**\n * Constructor for the Modal.\n *\n * @param {object} root The root jQuery element for the modal\n */\n var ModalLarge = function (root) {\n Modal.call(this, root);\n };\n\n ModalLarge.TYPE = 'local_assesfreq-large_modal';\n ModalLarge.prototype = Object.create(Modal.prototype);\n ModalLarge.prototype.constructor = ModalLarge;\n\n /**\n * Set up all of the event handling for the modal.\n *\n * @method registerEventListeners\n */\n ModalLarge.prototype.registerEventListeners = function () {\n // Apply parent event listeners.\n Modal.prototype.registerEventListeners.call(this);\n };\n\n // Automatically register with the modal registry the first time this module is imported so that you can create modals\n // of this type using the modal factory.\n if (!registered) {\n ModalRegistry.register(ModalLarge.TYPE, ModalLarge, 'local_assessfreq/modal_large');\n registered = true;\n }\n\n return ModalLarge;\n }\n);\n"],"names":["define","$","Notification","CustomEvents","Modal","ModalRegistry","registered","ModalLarge","root","call","this","TYPE","prototype","Object","create","constructor","registerEventListeners","register"],"mappings":";;;;;;;AAuBAA,sCACI,CAAC,SAAU,oBAAqB,iCAAkC,aAAc,wBAChF,SAAUC,EAAGC,aAAcC,aAAcC,MAAOC,mBAExCC,YAAa,EAObC,WAAa,SAAUC,MACvBJ,MAAMK,KAAKC,KAAMF,cAGrBD,WAAWI,KAAO,+BAClBJ,WAAWK,UAAYC,OAAOC,OAAOV,MAAMQ,YACtBG,YAAcR,WAOnCA,WAAWK,UAAUI,uBAAyB,WAE1CZ,MAAMQ,UAAUI,uBAAuBP,KAAKC,OAK3CJ,aACDD,cAAcY,SAASV,WAAWI,KAAMJ,WAAY,gCACpDD,YAAa,GAGVC"} \ No newline at end of file diff --git a/amd/build/override_modal.min.js b/amd/build/override_modal.min.js index 421b5ac..0665960 100644 --- a/amd/build/override_modal.min.js +++ b/amd/build/override_modal.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/override_modal",["jquery","core/str","core/modal_factory","core/modal_events","core/fragment","core/ajax"],function(a,b,c,d,e,f){var h={},i,j,k,l,m,n,o="

",p=function(){b.get_string("loading","local_assessfreq").then(function(a){c.create({type:c.types.DEFAULT,title:a,body:o,large:!0}).done(function(a){j=a;j.getRoot().on("click","#id_submitbutton",g);j.getRoot().on("click","#id_cancel",function(a){a.preventDefault();j.setBody(o);j.hide()})})}).catch(function(){Notification.exception(new Error("Failed to load string: loading"))})},q=function(a,c,d){if("undefined"==typeof d){d={}}var f={jsonformdata:JSON.stringify(d),quizid:a,userid:c};j.setBody(o);b.get_string("useroverride","local_assessfreq").then(function(a){j.setTitle(a);j.setBody(e.loadFragment("local_assessfreq","new_override_form",i,f))}).catch(function(){Notification.exception(new Error("Failed to load string: useroverride"))})};function g(b){b.preventDefault();var c=j.getRoot().find("form").serialize(),d=JSON.stringify(c),e=a.merge(j.getRoot().find("[aria-invalid=\"true\"]"),j.getRoot().find(".error"));if(e.length){e.first().focus();return}f.call([{methodname:"local_assessfreq_process_override_form",args:{jsonformdata:d,quizid:l}}])[0].done(function(){j.setBody(o);j.hide();if(n){k(l,n)}else{k(l)}}).fail(function(){q(l,m,c)})}h.displayModalForm=function(a,b){var c=2 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/override_modal",["jquery","core/str","core/modal_factory","core/modal_events","core/fragment","core/ajax"],(function($,Str,ModalFactory,ModalEvents,Fragment,Ajax){var contextid,modalObj,callback,quizid,userid,hoursFilter,OverrideModal={};const spinner='

',createModal=function(){Str.get_string("loading","local_assessfreq").then((title=>{ModalFactory.create({type:ModalFactory.types.DEFAULT,title:title,body:spinner,large:!0}).done((modal=>{(modalObj=modal).getRoot().on("click","#id_submitbutton",processModalForm),modalObj.getRoot().on("click","#id_cancel",(function(e){e.preventDefault(),modalObj.setBody(spinner),modalObj.hide()}))}))}))},updateModalBody=function(quiz,user,formdata){void 0===formdata&&(formdata={});let params={jsonformdata:JSON.stringify(formdata),quizid:quiz,userid:user};modalObj.setBody(spinner),Str.get_string("useroverride","local_assessfreq").then((title=>{modalObj.setTitle(title),modalObj.setBody(Fragment.loadFragment("local_assessfreq","new_override_form",contextid,params))}))};function processModalForm(e){e.preventDefault();let overrideform=modalObj.getRoot().find("form").serialize(),formjson=JSON.stringify(overrideform);var invalid=$.merge(modalObj.getRoot().find('[aria-invalid="true"]'),modalObj.getRoot().find(".error"));invalid.length?invalid.first().focus():Ajax.call([{methodname:"local_assessfreq_process_override_form",args:{jsonformdata:formjson,quizid:quizid}}])[0].done((()=>{modalObj.setBody(spinner),modalObj.hide(),hoursFilter?callback(quizid,hoursFilter):callback(quizid)})).fail((()=>{updateModalBody(quizid,userid,overrideform)}))}return OverrideModal.displayModalForm=function(quiz,user){let hours=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;quizid=quiz,userid=user,hoursFilter=hours,updateModalBody(quiz,user),modalObj.show()},OverrideModal.init=function(context,callbackFunction){let hours=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;contextid=context,callback=callbackFunction,hoursFilter=hours,createModal()},OverrideModal})); + +//# sourceMappingURL=override_modal.min.js.map \ No newline at end of file diff --git a/amd/build/override_modal.min.js.map b/amd/build/override_modal.min.js.map index 70e2a09..1ed1a04 100644 --- a/amd/build/override_modal.min.js.map +++ b/amd/build/override_modal.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/override_modal.js"],"names":["define","$","Str","ModalFactory","ModalEvents","Fragment","Ajax","OverrideModal","contextid","modalObj","callback","quizid","userid","hoursFilter","spinner","createModal","get_string","then","title","create","type","types","DEFAULT","body","large","done","modal","getRoot","on","processModalForm","e","preventDefault","setBody","hide","catch","Notification","exception","Error","updateModalBody","quiz","user","formdata","params","JSON","stringify","setTitle","loadFragment","overrideform","find","serialize","formjson","invalid","merge","length","first","focus","call","methodname","args","fail","displayModalForm","hours","show","init","context","callbackFunction"],"mappings":"AAuBAA,OAAM,mCAAC,CAAC,QAAD,CAAW,UAAX,CAAuB,oBAAvB,CAA6C,mBAA7C,CAAkE,eAAlE,CAAmF,WAAnF,CAAD,CACN,SAASC,CAAT,CAAWC,CAAX,CAAgBC,CAAhB,CAA8BC,CAA9B,CAA2CC,CAA3C,CAAqDC,CAArD,CAA2D,IAKnDC,CAAAA,CAAa,CAAG,EALmC,CAMnDC,CANmD,CAOnDC,CAPmD,CAQnDC,CARmD,CASnDC,CATmD,CAUnDC,CAVmD,CAWnDC,CAXmD,CAajDC,CAAO,0FAb0C,CAsBjDC,CAAW,CAAG,UAAW,CAC3Bb,CAAG,CAACc,UAAJ,CAAe,SAAf,CAA0B,kBAA1B,EAA8CC,IAA9C,CAAmD,SAACC,CAAD,CAAW,CAE1Df,CAAY,CAACgB,MAAb,CAAoB,CAChBC,IAAI,CAAEjB,CAAY,CAACkB,KAAb,CAAmBC,OADT,CAEhBJ,KAAK,CAAEA,CAFS,CAGhBK,IAAI,CAAET,CAHU,CAIhBU,KAAK,GAJW,CAApB,EAMCC,IAND,CAMM,SAACC,CAAD,CAAW,CACbjB,CAAQ,CAAGiB,CAAX,CAEAjB,CAAQ,CAACkB,OAAT,GAAmBC,EAAnB,CAAsB,OAAtB,CAA+B,kBAA/B,CAAmDC,CAAnD,EACApB,CAAQ,CAAC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AAGuD,CAAX,CACApD,CAAW,CAAGgD,CAAd,CACA9C,CAAW,EACd,CALD,CAOA,MAAOR,CAAAA,CACV,CAhJK,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 * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['jquery', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/fragment', 'core/ajax'],\nfunction($,Str, ModalFactory, ModalEvents, Fragment, Ajax) {\n\n /**\n * Module level variables.\n */\n var OverrideModal = {};\n var contextid;\n var modalObj;\n var callback;\n var quizid;\n var userid;\n var hoursFilter;\n\n const spinner = '

'\n + ''\n + '

';\n\n /**\n * Create the modal window.\n *\n * @private\n */\n const createModal = function() {\n Str.get_string('loading', 'local_assessfreq').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalFactory.types.DEFAULT,\n title: title,\n body: spinner,\n large: true\n })\n .done((modal) => {\n modalObj = modal;\n // Explicitly handle form click events.\n modalObj.getRoot().on('click', '#id_submitbutton', processModalForm);\n modalObj.getRoot().on('click', '#id_cancel', function(e) {\n e.preventDefault();\n modalObj.setBody(spinner);\n modalObj.hide();\n });\n });\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: loading'));\n });\n };\n\n /**\n * Updates the body of the modal window.\n *\n * @param {Object} formdata\n * @private\n */\n const updateModalBody = function(quiz, user, formdata) {\n if (typeof formdata === \"undefined\") {\n formdata = {};\n }\n\n let params = {\n 'jsonformdata': JSON.stringify(formdata),\n 'quizid': quiz,\n 'userid': user\n };\n\n modalObj.setBody(spinner);\n Str.get_string('useroverride', 'local_assessfreq').then((title) => {\n modalObj.setTitle(title);\n modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_override_form', contextid, params));\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: useroverride'));\n });\n };\n\n /**\n * Updates Moodle form with selected information.\n *\n * @param {Object} e\n * @private\n */\n function processModalForm(e) {\n e.preventDefault(); // Stop modal from closing.\n\n // Form data.\n let overrideform = modalObj.getRoot().find('form').serialize();\n let formjson = JSON.stringify(overrideform);\n\n // Handle invalid form fields for better UX.\n // I hate that I had to use JQuery for this.\n var invalid = $.merge(\n modalObj.getRoot().find('[aria-invalid=\"true\"]'),\n modalObj.getRoot().find('.error')\n );\n\n if (invalid.length) {\n invalid.first().focus();\n return;\n }\n\n // Submit form via ajax.\n Ajax.call([{\n methodname: 'local_assessfreq_process_override_form',\n args: {\n 'jsonformdata': formjson,\n 'quizid': quizid\n },\n }])[0].done(() => {\n // For submission succeeded.\n modalObj.setBody(spinner);\n modalObj.hide();\n if (hoursFilter) {\n callback(quizid, hoursFilter);\n } else {\n callback(quizid);\n }\n }).fail(() => {\n // Form submission failed server side, redisplay with errors.\n updateModalBody(quizid, userid, overrideform);\n });\n }\n\n /**\n * Display the Modal form.\n */\n OverrideModal.displayModalForm = function(quiz, user, hours = null) {\n quizid = quiz;\n userid = user;\n hoursFilter = hours;\n updateModalBody(quiz, user);\n modalObj.show();\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n OverrideModal.init = function(context, callbackFunction, hours = null) {\n contextid = context;\n callback = callbackFunction;\n hoursFilter = hours;\n createModal();\n };\n\n return OverrideModal;\n});\n"],"file":"override_modal.min.js"} \ No newline at end of file +{"version":3,"file":"override_modal.min.js","sources":["../src/override_modal.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['jquery', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/fragment', 'core/ajax'],\n function ($,Str, ModalFactory, ModalEvents, Fragment, Ajax) {\n\n /**\n * Module level variables.\n */\n var OverrideModal = {};\n var contextid;\n var modalObj;\n var callback;\n var quizid;\n var userid;\n var hoursFilter;\n\n const spinner = '

'\n + ''\n + '

';\n\n /**\n * Create the modal window.\n *\n * @private\n */\n const createModal = function () {\n Str.get_string('loading', 'local_assessfreq').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalFactory.types.DEFAULT,\n title: title,\n body: spinner,\n large: true\n })\n .done((modal) => {\n modalObj = modal;\n // Explicitly handle form click events.\n modalObj.getRoot().on('click', '#id_submitbutton', processModalForm);\n modalObj.getRoot().on('click', '#id_cancel', function (e) {\n e.preventDefault();\n modalObj.setBody(spinner);\n modalObj.hide();\n });\n });\n return;\n });\n };\n\n /**\n * Updates the body of the modal window.\n *\n * @param {Object} formdata\n * @private\n */\n const updateModalBody = function (quiz, user, formdata) {\n if (typeof formdata === \"undefined\") {\n formdata = {};\n }\n\n let params = {\n 'jsonformdata': JSON.stringify(formdata),\n 'quizid': quiz,\n 'userid': user\n };\n\n modalObj.setBody(spinner);\n Str.get_string('useroverride', 'local_assessfreq').then((title) => {\n modalObj.setTitle(title);\n modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_override_form', contextid, params));\n return;\n });\n };\n\n /**\n * Updates Moodle form with selected information.\n *\n * @param {Object} e\n * @private\n */\n function processModalForm(e) {\n e.preventDefault(); // Stop modal from closing.\n\n // Form data.\n let overrideform = modalObj.getRoot().find('form').serialize();\n let formjson = JSON.stringify(overrideform);\n\n // Handle invalid form fields for better UX.\n // I hate that I had to use JQuery for this.\n var invalid = $.merge(\n modalObj.getRoot().find('[aria-invalid=\"true\"]'),\n modalObj.getRoot().find('.error')\n );\n\n if (invalid.length) {\n invalid.first().focus();\n return;\n }\n\n // Submit form via ajax.\n Ajax.call([{\n methodname: 'local_assessfreq_process_override_form',\n args: {\n 'jsonformdata': formjson,\n 'quizid': quizid\n },\n }])[0].done(() => {\n // For submission succeeded.\n modalObj.setBody(spinner);\n modalObj.hide();\n if (hoursFilter) {\n callback(quizid, hoursFilter);\n } else {\n callback(quizid);\n }\n }).fail(() => {\n // Form submission failed server side, redisplay with errors.\n updateModalBody(quizid, userid, overrideform);\n });\n }\n\n /**\n * Display the Modal form.\n */\n OverrideModal.displayModalForm = function (quiz, user, hours = null) {\n quizid = quiz;\n userid = user;\n hoursFilter = hours;\n updateModalBody(quiz, user);\n modalObj.show();\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n OverrideModal.init = function (context, callbackFunction, hours = null) {\n contextid = context;\n callback = callbackFunction;\n hoursFilter = hours;\n createModal();\n };\n\n return OverrideModal;\n }\n);\n"],"names":["define","$","Str","ModalFactory","ModalEvents","Fragment","Ajax","contextid","modalObj","callback","quizid","userid","hoursFilter","OverrideModal","spinner","createModal","get_string","then","title","create","type","types","DEFAULT","body","large","done","modal","getRoot","on","processModalForm","e","preventDefault","setBody","hide","updateModalBody","quiz","user","formdata","params","JSON","stringify","setTitle","loadFragment","overrideform","find","serialize","formjson","invalid","merge","length","first","focus","call","methodname","args","fail","displayModalForm","hours","show","init","context","callbackFunction"],"mappings":";;;;;;;AAuBAA,yCACI,CAAC,SAAU,WAAY,qBAAsB,oBAAqB,gBAAiB,cACnF,SAAUC,E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YAAc6C,MACdvB,gBAAgBC,KAAMC,MACtB5B,SAASkD,QAMb7C,cAAc8C,KAAO,SAAUC,QAASC,sBAAkBJ,6DAAQ,KAC9DlD,UAAYqD,QACZnD,SAAWoD,iBACXjD,YAAc6C,MACd1C,eAGGF"} \ No newline at end of file diff --git a/amd/build/student_search.min.js b/amd/build/student_search.min.js index 5e70d3f..2d40135 100644 --- a/amd/build/student_search.min.js +++ b/amd/build/student_search.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/student_search",["exports","jquery","core/notification","local_assessfreq/override_modal","local_assessfreq/table_handler","local_assessfreq/user_preferences"],function(a,b,c,d,e,f){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=void 0;b=i(b);c=i(c);d=i(d);e=h(e);f=h(f);function g(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;g=function(){return a};return a}function h(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=g();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;if(f&&(f.get||f.set)){Object.defineProperty(c,e,f)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function i(a){return a&&a.__esModule?a:{default:a}}var j,k=4,l=1,m=60,n,o=function(){var a=0 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */var contextid;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_jquery=_interopRequireDefault(_jquery),_notification=_interopRequireDefault(_notification),_override_modal=_interopRequireDefault(_override_modal),TableHandler=_interopRequireWildcard(TableHandler),UserPreference=_interopRequireWildcard(UserPreference);var counterid,hoursAhead=4,hoursBehind=1,refreshPeriod=60;const refreshCounter=function(){let reset=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],progressElement=document.getElementById("local-assessfreq-period-progress");!0===reset&&(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100)),counterid||(counterid=setInterval((()=>{let progressWidthAria=progressElement.getAttribute("aria-valuenow");const progressStep=100/refreshPeriod;progressWidthAria-progressStep>0?(progressElement.setAttribute("style","width: "+(progressWidthAria-progressStep)+"%"),progressElement.setAttribute("aria-valuenow",progressWidthAria-progressStep)):(clearInterval(counterid),counterid=null,progressElement.setAttribute("style","width: 100%"),progressElement.setAttribute("aria-valuenow",100),TableHandler.getTable(0,[hoursAhead,hoursBehind],null),refreshCounter())}),1e3))},tableSearchAheadSet=event=>{if(event.preventDefault(),"a"===event.target.tagName.toLowerCase()){let hours=event.target.dataset.metric;UserPreference.setUserPreference("local_assessfreq_student_search_table_hoursahead_preference",hours).then((()=>{hoursAhead=hours,TableHandler.getTable(0,[hoursAhead,hoursBehind],null)})).fail((()=>{_notification.default.exception(new Error("Failed to update user preference: hours ahead"))}))}},tableSearchBehindSet=event=>{if(event.preventDefault(),"a"===event.target.tagName.toLowerCase()){let hours=event.target.dataset.metric;UserPreference.setUserPreference("local_assessfreq_student_search_table_hoursbehind_preference",hours).then((()=>{hoursBehind=hours,TableHandler.getTable(0,[hoursAhead,hoursBehind],null)})).fail((()=>{_notification.default.exception(new Error("Failed to update user preference: hours behind"))}))}},refreshAction=event=>{event.preventDefault();var element=event.target;null!==element.closest("button")&&"local-assessfreq-refresh-quiz-dashboard"===element.closest("button").id?(refreshCounter(!0),TableHandler.getTable(0,[hoursAhead,hoursBehind],null)):"a"===element.tagName.toLowerCase()&&(refreshPeriod=element.dataset.period,refreshCounter(!0),UserPreference.setUserPreference("local_assessfreq_quiz_refresh_preference",refreshPeriod))};_exports.init=context=>{contextid=context,TableHandler.init(0,contextid,"local-assessfreq-student-search-table","local-assessfreq-student-search","get_student_search_table","local_assessfreq_student_search_table_rows_preference","local-assessfreq-quiz-student-table-search","local_assessfreq_student_search_table","local_assessfreq_set_table_preference");let tableSearchInputElement=document.getElementById("local-assessfreq-quiz-student-table-search"),tableSearchResetElement=document.getElementById("local-assessfreq-quiz-student-table-search-reset"),tableSearchRowsElement=document.getElementById("local-assessfreq-quiz-student-table-rows"),tableSearchAheadElement=document.getElementById("local-assessfreq-quiz-student-table-hoursahead"),tableSearchBehindElement=document.getElementById("local-assessfreq-quiz-student-table-hoursbehind"),refreshElement=document.getElementById("local-assessfreq-period-container");tableSearchInputElement.addEventListener("keyup",TableHandler.tableSearch),tableSearchInputElement.addEventListener("paste",TableHandler.tableSearch),tableSearchResetElement.addEventListener("click",TableHandler.tableSearchReset),tableSearchRowsElement.addEventListener("click",TableHandler.tableSearchRowSet),tableSearchAheadElement.addEventListener("click",tableSearchAheadSet),tableSearchBehindElement.addEventListener("click",tableSearchBehindSet),refreshElement.addEventListener("click",refreshAction),_jquery.default.when(UserPreference.getUserPreference("local_assessfreq_student_search_table_hoursahead_preference").then((response=>{hoursAhead=response.preferences[0].value?response.preferences[0].value:4})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: hoursahead"))})),UserPreference.getUserPreference("local_assessfreq_student_search_table_hoursbehind_preference").then((response=>{hoursBehind=response.preferences[0].value?response.preferences[0].value:1})).fail((()=>{_notification.default.exception(new Error("Failed to get use preference: hoursahead"))}))).done((function(){TableHandler.getTable(0,[hoursAhead,hoursBehind],null),_override_modal.default.init(context,TableHandler.getTable,[hoursAhead,hoursBehind])}))}})); + +//# sourceMappingURL=student_search.min.js.map \ No newline at end of file diff --git a/amd/build/student_search.min.js.map b/amd/build/student_search.min.js.map index 40c291e..6a4a2b5 100644 --- a/amd/build/student_search.min.js.map +++ b/amd/build/student_search.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/student_search.js"],"names":["contextid","hoursAhead","hoursBehind","refreshPeriod","counterid","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","TableHandler","getTable","tableSearchAheadSet","event","preventDefault","target","tagName","toLowerCase","hours","dataset","metric","UserPreference","setUserPreference","then","fail","Notification","exception","Error","tableSearchBehindSet","refreshAction","element","closest","id","period","init","context","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","tableSearchAheadElement","tableSearchBehindElement","refreshElement","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","$","when","getUserPreference","response","preferences","value","done","OverrideModal"],"mappings":"+jBAwBA,OACA,OACA,OACA,OACA,O,4lBAKIA,CAAAA,C,CACAC,CAAU,CAAG,C,CACbC,CAAW,CAAG,C,CACdC,CAAa,CAAG,E,CAChBC,C,CAOEC,CAAc,CAAG,UAAkB,IAAjBC,CAAAA,CAAiB,2DACjCC,CAAe,CAAGC,QAAQ,CAACC,cAAT,CAAwB,kCAAxB,CADe,CAIrC,GAAI,KAAAH,CAAJ,CAAoB,CAChBI,aAAa,CAACN,CAAD,CAAb,CACAA,CAAS,CAAG,IAAZ,CACAG,CAAe,CAACI,YAAhB,CAA6B,OAA7B,CAAsC,aAAtC,EACAJ,CAAe,CAACI,YAAhB,CAA6B,eAA7B,CAA8C,GAA9C,CACH,CAGD,GAAIP,CAAJ,CAAe,CACX,MACH,CAEDA,CAAS,CAAGQ,WAAW,CAAC,UAAM,IACtBC,CAAAA,CAAiB,CAAGN,CAAe,CAACO,YAAhB,CAA6B,eAA7B,CADE,CAEpBC,CAAY,CAAG,IAAMZ,CAFD,CAI1B,GAAyC,CAArC,CAACU,CAAiB,CAAGE,CAAzB,CAA4C,CACxCR,CAAe,CAACI,YAAhB,CAA6B,OAA7B,CAAsC,WAAaE,CAAiB,CAAGE,CAAjC,EAAiD,GAAvF,EACAR,CAAe,CAACI,YAAhB,CAA6B,eAA7B,CAA+CE,CAAiB,CAAGE,CAAnE,CACH,C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AAT,CAAqB,CAArB,EAAwBC,KAAxD,CAAgE,CACjF,CAHD,EAIC3B,IAJD,CAIM,UAAM,CACRC,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,0CAAV,CAAvB,CACH,CAND,CARJ,EAeEyB,IAfF,CAeO,UAAW,CACd1C,CAAY,CAACC,QAAb,CAAsB,CAAtB,CAAyB,CAAChB,CAAD,CAAaC,CAAb,CAAzB,CAAoD,IAApD,EACAyD,UAAcnB,IAAd,CAAmBC,CAAnB,CAA4BzB,CAAY,CAACC,QAAzC,CAAmD,CAAChB,CAAD,CAAaC,CAAb,CAAnD,CACH,CAlBD,CAmBH,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 for student search display and processing.\n *\n * @module local_assessfreq/student_search\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport $ from 'jquery';\nimport Notification from 'core/notification';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar hoursAhead = 4;\nvar hoursBehind = 1;\nvar refreshPeriod = 60;\nvar counterid;\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Process the hours ahead event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSearchAheadSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_student_search_table_hoursahead_preference', hours)\n .then(() => {\n hoursAhead = hours;\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null); // Reload the table. // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours ahead'));\n });\n }\n};\n\n/**\n * Process the hours behind event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSearchBehindSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_student_search_table_hoursbehind_preference', hours)\n .then(() => {\n hoursBehind = hours;\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null); // Reload the table. // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours behind'));\n });\n }\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Initialise method for student search.\n *\n * @param {integer} context The current context id.\n */\nexport const init = (context) => {\n contextid = context;\n TableHandler.init(\n 0,\n contextid,\n 'local-assessfreq-student-search-table',\n 'local-assessfreq-student-search',\n 'get_student_search_table',\n 'local_assessfreq_student_search_table_rows_preference',\n 'local-assessfreq-quiz-student-table-search',\n 'local_assessfreq_student_search_table',\n 'local_assessfreq_set_table_preference'\n );\n\n // Add required initial event listeners.\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-student-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-student-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-student-table-rows');\n let tableSearchAheadElement = document.getElementById('local-assessfreq-quiz-student-table-hoursahead');\n let tableSearchBehindElement = document.getElementById('local-assessfreq-quiz-student-table-hoursbehind');\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n tableSearchAheadElement.addEventListener('click', tableSearchAheadSet);\n tableSearchBehindElement.addEventListener('click', tableSearchBehindSet);\n refreshElement.addEventListener('click', refreshAction);\n\n $.when(\n UserPreference.getUserPreference('local_assessfreq_student_search_table_hoursahead_preference')\n .then((response) => {\n hoursAhead = response.preferences[0].value ? response.preferences[0].value : 4;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n }),\n UserPreference.getUserPreference('local_assessfreq_student_search_table_hoursbehind_preference')\n .then((response) => {\n hoursBehind = response.preferences[0].value ? response.preferences[0].value : 1;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n })\n ).done(function() {\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n OverrideModal.init(context, TableHandler.getTable, [hoursAhead, hoursBehind]);\n });\n};\n"],"file":"student_search.min.js"} \ No newline at end of file +{"version":3,"file":"student_search.min.js","sources":["../src/student_search.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for student search display and processing.\n *\n * @module local_assessfreq/student_search\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport $ from 'jquery';\nimport Notification from 'core/notification';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as TableHandler from 'local_assessfreq/table_handler';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\n\n/**\n * Module level variables.\n */\nvar contextid;\nvar hoursAhead = 4;\nvar hoursBehind = 1;\nvar refreshPeriod = 60;\nvar counterid;\n\n/**\n * Function for refreshing the counter.\n *\n * @param {boolean} reset the current count process.\n */\nconst refreshCounter = (reset = true) => {\n let progressElement = document.getElementById('local-assessfreq-period-progress');\n\n // Reset the current count process.\n if (reset === true) {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n }\n\n // Exit early if there is already a counter running.\n if (counterid) {\n return;\n }\n\n counterid = setInterval(() => {\n let progressWidthAria = progressElement.getAttribute('aria-valuenow');\n const progressStep = 100 / refreshPeriod;\n\n if ((progressWidthAria - progressStep) > 0) {\n progressElement.setAttribute('style', 'width: ' + (progressWidthAria - progressStep) + '%');\n progressElement.setAttribute('aria-valuenow', (progressWidthAria - progressStep));\n } else {\n clearInterval(counterid);\n counterid = null;\n progressElement.setAttribute('style', 'width: 100%');\n progressElement.setAttribute('aria-valuenow', 100);\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n refreshCounter();\n }\n }, (1000));\n};\n\n/**\n * Process the hours ahead event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSearchAheadSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_student_search_table_hoursahead_preference', hours)\n .then(() => {\n hoursAhead = hours;\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null); // Reload the table. // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours ahead'));\n });\n }\n};\n\n/**\n * Process the hours behind event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSearchBehindSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let hours = event.target.dataset.metric;\n UserPreference.setUserPreference('local_assessfreq_student_search_table_hoursbehind_preference', hours)\n .then(() => {\n hoursBehind = hours;\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null); // Reload the table. // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: hours behind'));\n });\n }\n};\n\n/**\n * Handle processing of refresh and period button actions.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst refreshAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.closest('button') !== null && element.closest('button').id === 'local-assessfreq-refresh-quiz-dashboard') {\n refreshCounter(true);\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n } else if (element.tagName.toLowerCase() === 'a') {\n refreshPeriod = element.dataset.period;\n refreshCounter(true);\n UserPreference.setUserPreference('local_assessfreq_quiz_refresh_preference', refreshPeriod);\n }\n};\n\n/**\n * Initialise method for student search.\n *\n * @param {integer} context The current context id.\n */\nexport const init = (context) => {\n contextid = context;\n TableHandler.init(\n 0,\n contextid,\n 'local-assessfreq-student-search-table',\n 'local-assessfreq-student-search',\n 'get_student_search_table',\n 'local_assessfreq_student_search_table_rows_preference',\n 'local-assessfreq-quiz-student-table-search',\n 'local_assessfreq_student_search_table',\n 'local_assessfreq_set_table_preference'\n );\n\n // Add required initial event listeners.\n let tableSearchInputElement = document.getElementById('local-assessfreq-quiz-student-table-search');\n let tableSearchResetElement = document.getElementById('local-assessfreq-quiz-student-table-search-reset');\n let tableSearchRowsElement = document.getElementById('local-assessfreq-quiz-student-table-rows');\n let tableSearchAheadElement = document.getElementById('local-assessfreq-quiz-student-table-hoursahead');\n let tableSearchBehindElement = document.getElementById('local-assessfreq-quiz-student-table-hoursbehind');\n let refreshElement = document.getElementById('local-assessfreq-period-container');\n\n tableSearchInputElement.addEventListener('keyup', TableHandler.tableSearch);\n tableSearchInputElement.addEventListener('paste', TableHandler.tableSearch);\n tableSearchResetElement.addEventListener('click', TableHandler.tableSearchReset);\n tableSearchRowsElement.addEventListener('click', TableHandler.tableSearchRowSet);\n tableSearchAheadElement.addEventListener('click', tableSearchAheadSet);\n tableSearchBehindElement.addEventListener('click', tableSearchBehindSet);\n refreshElement.addEventListener('click', refreshAction);\n\n $.when(\n UserPreference.getUserPreference('local_assessfreq_student_search_table_hoursahead_preference')\n .then((response) => {\n hoursAhead = response.preferences[0].value ? response.preferences[0].value : 4;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n }),\n UserPreference.getUserPreference('local_assessfreq_student_search_table_hoursbehind_preference')\n .then((response) => {\n hoursBehind = response.preferences[0].value ? response.preferences[0].value : 1;\n })\n .fail(() => {\n Notification.exception(new Error('Failed to get use preference: hoursahead'));\n })\n ).done(function () {\n TableHandler.getTable(0, [hoursAhead, hoursBehind], null);\n OverrideModal.init(context, TableHandler.getTable, [hoursAhead, hoursBehind]);\n });\n};\n"],"names":["contextid","counterid","hoursAhead","hoursBehind","refreshPeriod","refreshCounter","reset","progressElement","document","getElementById","clearInterval","setAttribute","setInterval","progressWidthAria","getAttribute","progressStep","TableHandler","getTable","tableSearchAheadSet","event","preventDefault","target","tagName","toLowerCase","hours","dataset","metric","UserPreference","setUserPreference","then","fail","exception","Error","tableSearchBehindSet","refreshAction","element","closest","id","period","context","init","tableSearchInputElement","tableSearchResetElement","tableSearchRowsElement","tableSearchAheadElement","tableSearchBehindElement","refreshElement","addEventListener","tableSearch","tableSearchReset","tableSearchRowSet","when","getUserPreference","response","preferences","value","done"],"mappings":";;;;;;;;SAiCIA,yVAIAC,UAHAC,WAAa,EACbC,YAAc,EACdC,cAAgB,SAQdC,eAAiB,eAACC,iEAChBC,gBAAkBC,SAASC,eAAe,qCAGhC,IAAVH,QACAI,cAAcT,WACdA,UAAY,KACZM,gBAAgBI,aAAa,QAAS,eACtCJ,gBAAgBI,aAAa,gBAAiB,MAI9CV,YAIJA,UAAYW,aAAY,SAChBC,kBAAoBN,gBAAgBO,aAAa,uBAC/CC,aAAe,IAAMX,cAEtBS,kBAAoBE,aAAgB,GACrCR,gBAAgBI,aAAa,QAAS,WAAaE,kBAAoBE,cAAgB,KACvFR,gBAAgBI,aAAa,gBAAkBE,kBAAoBE,gBAEnEL,cAAcT,WACdA,UAAY,KACZM,gBAAgBI,aAAa,QAAS,eACtCJ,gBAAgBI,aAAa,gBAAiB,KAC9CK,aAAaC,SAAS,EAAG,CAACf,WAAYC,aAAc,MACpDE,oBAEJ,OAQFa,oBAAuBC,WACzBA,MAAMC,iBACqC,MAAvCD,MAAME,OAAOC,QAAQC,cAAuB,KACxCC,MAAQL,MAAME,OAAOI,QAAQC,OACjCC,eAAeC,kBAAkB,8DAA+DJ,OAC/FK,MAAK,KACF3B,WAAas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kBAAkB,+DAChCvB,MAAMwB,WACHnD,WAAamD,SAASC,YAAY,GAAGC,MAAQF,SAASC,YAAY,GAAGC,MAAQ,KAEhFzB,MAAK,2BACWC,UAAU,IAAIC,MAAM,gDAErCL,eAAeyB,kBAAkB,gEAChCvB,MAAMwB,WACHlD,YAAckD,SAASC,YAAY,GAAGC,MAAQF,SAASC,YAAY,GAAGC,MAAQ,KAEjFzB,MAAK,2BACWC,UAAU,IAAIC,MAAM,iDAEvCwB,MAAK,WACHxC,aAAaC,SAAS,EAAG,CAACf,WAAYC,aAAc,8BACtCqC,KAAKD,QAASvB,aAAaC,SAAU,CAACf,WAAYC"} \ No newline at end of file diff --git a/amd/build/summary_participants.min.js b/amd/build/summary_participants.min.js index 9106e76..b0cf1a2 100644 --- a/amd/build/summary_participants.min.js +++ b/amd/build/summary_participants.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/summary_participants",["core/fragment","core/templates","core/str","core/notification"],function(a,b,c,d){return{chart:function(e,f){e.forEach(function(e){var g=document.getElementById(e+"-summary-graph"),h={data:JSON.stringify({quiz:e,call:"participant_summary"})};a.loadFragment("local_assessfreq","get_quiz_chart",f,h).done(function(a){var e=JSON.parse(a);if(!0==e.hasdata){var f={withtable:!1,chartdata:JSON.stringify(e.chart),aspect:!1,legend:JSON.stringify({position:"left"})};b.render("local_assessfreq/chart",f).done(function(a,c){b.replaceNodeContents(g,a,c)}).fail(function(){d.exception(new Error("Failed to load chart template."))})}else{c.get_string("nodata","local_assessfreq").then(function(a){var b=document.createElement("h3");b.innerHTML=a;g.innerHTML=b.outerHTML}).catch(function(){d.exception(new Error("Failed to load string: nodata"))})}}).fail(function(){d.exception(new Error("Failed to load card."))})})}}}); -//# sourceMappingURL=summary_participants.min.js.map +/** + * Javascript for summary participants graph. + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/summary_participants",["core/fragment","core/templates","core/str","core/notification"],(function(Fragment,Templates,Str,Notification){var Summary={chart:function(assessids,contextid){assessids.forEach((assessid=>{let chartElement=document.getElementById(assessid+"-summary-graph"),params={data:JSON.stringify({quiz:assessid,call:"participant_summary"})};Fragment.loadFragment("local_assessfreq","get_quiz_chart",contextid,params).done((response=>{let resObj=JSON.parse(response);if(1!=resObj.hasdata)Str.get_string("nodata","local_assessfreq").then((str=>{const noDatastr=document.createElement("h3");noDatastr.innerHTML=str,chartElement.innerHTML=noDatastr.outerHTML}));else{let legend={position:"left"},context={withtable:!1,chartdata:JSON.stringify(resObj.chart),aspect:!1,legend:JSON.stringify(legend)};Templates.render("local_assessfreq/chart",context).done(((html,js)=>{Templates.replaceNodeContents(chartElement,html,js)})).fail((()=>{Notification.exception(new Error("Failed to load chart template."))}))}})).fail((()=>{Notification.exception(new Error("Failed to load card."))}))}))}};return Summary})); + +//# sourceMappingURL=summary_participants.min.js.map \ No newline at end of file diff --git a/amd/build/summary_participants.min.js.map b/amd/build/summary_participants.min.js.map index 491ab4e..94c0eaf 100644 --- a/amd/build/summary_participants.min.js.map +++ b/amd/build/summary_participants.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/summary_participants.js"],"names":["define","Fragment","Templates","Str","Notification","chart","assessids","contextid","forEach","assessid","chartElement","document","getElementById","params","JSON","stringify","loadFragment","done","response","resObj","parse","hasdata","context","position","render","html","js","replaceNodeContents","fail","exception","Error","get_string","then","str","noDatastr","createElement","innerHTML","outerHTML","catch"],"mappings":"AAuBAA,OAAM,yCAAC,CAAC,eAAD,CAAkB,gBAAlB,CAAoC,UAApC,CAAgD,mBAAhD,CAAD,CACN,SAASC,CAAT,CAAmBC,CAAnB,CAA8BC,CAA9B,CAAmCC,CAAnC,CAAiD,CAgD7C,MA3Cc,CAENC,KAFM,CAEE,SAASC,CAAT,CAAoBC,CAApB,CAA+B,CAC3CD,CAAS,CAACE,OAAV,CAAkB,SAACC,CAAD,CAAc,IACxBC,CAAAA,CAAY,CAAGC,QAAQ,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ACXlC,CAAY,CAACyB,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,+BAAV,CAAvB,CACH,CAPD,CAQH,CACJ,CA7BD,EA6BGF,IA7BH,CA6BQ,UAAM,CACVxB,CAAY,CAACyB,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,sBAAV,CAAvB,CAEH,CAhCD,CAiCH,CArCD,CAsCH,CAzCa,CA4CjB,CAlDK,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 * Javascript for summary participants graph.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/fragment', 'core/templates', 'core/str', 'core/notification'],\nfunction(Fragment, Templates, Str, Notification) {\n\n /**\n * Module level variables.\n */\n var Summary = {};\n\n Summary.chart = function(assessids, contextid) {\n assessids.forEach((assessid) => {\n let chartElement = document.getElementById(assessid + '-summary-graph');\n let params = {'data': JSON.stringify({'quiz' : assessid, 'call': 'participant_summary'})};\n\n Fragment.loadFragment('local_assessfreq', 'get_quiz_chart', contextid, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata == true) {\n let legend = {position: 'left'};\n let context = {\n 'withtable' : false,\n 'chartdata' : JSON.stringify(resObj.chart),\n 'aspect' : false,\n 'legend' : JSON.stringify(legend)\n };\n Templates.render('local_assessfreq/chart', context).done((html, js) => {\n // Load card body.\n Templates.replaceNodeContents(chartElement, html, js);\n }).fail(() => {\n Notification.exception(new Error('Failed to load chart template.'));\n return;\n });\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n chartElement.innerHTML = noDatastr.outerHTML;\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: nodata'));\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load card.'));\n return;\n });\n });\n };\n\n return Summary;\n});"],"file":"summary_participants.min.js"} \ No newline at end of file +{"version":3,"file":"summary_participants.min.js","sources":["../src/summary_participants.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for summary participants graph.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['core/fragment', 'core/templates', 'core/str', 'core/notification'],\n function (Fragment, Templates, Str, Notification) {\n\n /**\n * Module level variables.\n */\n var Summary = {};\n\n Summary.chart = function (assessids, contextid) {\n assessids.forEach((assessid) => {\n let chartElement = document.getElementById(assessid + '-summary-graph');\n let params = {'data': JSON.stringify({'quiz' : assessid, 'call': 'participant_summary'})};\n\n Fragment.loadFragment('local_assessfreq', 'get_quiz_chart', contextid, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata == true) {\n let legend = {position: 'left'};\n let context = {\n 'withtable' : false,\n 'chartdata' : JSON.stringify(resObj.chart),\n 'aspect' : false,\n 'legend' : JSON.stringify(legend)\n };\n Templates.render('local_assessfreq/chart', context).done((html, js) => {\n // Load card body.\n Templates.replaceNodeContents(chartElement, html, js);\n }).fail(() => {\n Notification.exception(new Error('Failed to load chart template.'));\n return;\n });\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n chartElement.innerHTML = noDatastr.outerHTML;\n return;\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load card.'));\n return;\n });\n });\n };\n\n return Summary;\n }\n);\n"],"names":["define","Fragment","Templates","Str","Notification","Summary","assessids","contextid","forEach","assessid","chartElement","document","getElementById","params","JSON","stringify","loadFragment","done","response","resObj","parse","hasdata","get_string","then","str","noDatastr","createElement","innerHTML","outerHTML","legend","position","context","chart","render","html","js","replaceNodeContents","fail","exception","Error"],"mappings":";;;;;;;AAuBAA,+CACI,CAAC,gBAAiB,iBAAkB,WAAY,sBAChD,SAAUC,SAAUC,UAAWC,IAAKC,kBAK5BC,QAAU,CAEdA,MAAgB,SAAUC,UAAWC,WACjCD,UAAUE,SAASC,eACXC,aAAeC,SAASC,eAAeH,SAAW,kBAClDI,OAAS,MAASC,KAAKC,UAAU,MAAUN,cAAkB,yBAEjER,SAASe,aAAa,mBAAoB,iBAAkBT,UAAWM,QACtEI,MAAMC,eACCC,OAASL,KAAKM,MAAMF,aACF,GAAlBC,OAAOE,QAiBPlB,IAAImB,WAAW,SAAU,oBAAoBC,MAAMC,YACzCC,UAAYd,SAASe,cAAc,MACzCD,UAAUE,UAAYH,IACtBd,aAAaiB,UAAYF,UAAUG,sBAnBnCC,OAAS,CAACC,SAAU,QACpBC,QAAU,YACI,YACAjB,KAAKC,UAAUI,OAAOa,eACzB,SACAlB,KAAKC,UAAUc,SAE9B3B,UAAU+B,OAAO,yBAA0BF,SAASd,MAAK,CAACiB,KAAMC,MAE5DjC,UAAUkC,oBAAoB1B,aAAcwB,KAAMC,OACnDE,MAAK,KACJjC,aAAakC,UAAU,IAAIC,MAAM,0CAY1CF,MAAK,KACJjC,aAAakC,UAAU,IAAIC,MAAM,wCAMtClC"} \ No newline at end of file diff --git a/amd/build/table_handler.min.js b/amd/build/table_handler.min.js index 59bb590..6e42ce2 100644 --- a/amd/build/table_handler.min.js +++ b/amd/build/table_handler.min.js @@ -1,2 +1,11 @@ -function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("local_assessfreq/table_handler",["exports","core/ajax","core/fragment","core/notification","core/templates","local_assessfreq/debouncer","local_assessfreq/override_modal","local_assessfreq/user_preferences"],function(a,b,c,d,e,f,g,h){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=a.tableSortButtonAction=a.tableSearchRowSet=a.tableSearchReset=a.tableSearch=a.getTable=void 0;b=k(b);c=k(c);d=k(d);e=k(e);f=j(f);g=k(g);h=j(h);function i(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;i=function(){return a};return a}function j(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=i();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var e in a){if(Object.prototype.hasOwnProperty.call(a,e)){var f=d?Object.getOwnPropertyDescriptor(a,e):null;if(f&&(f.get||f.set)){Object.defineProperty(c,e,f)}else{c[e]=a[e]}}}c.default=a;if(b){b.set(a,c)}return c}function k(a){return a&&a.__esModule?a:{default:a}}var l,m,n,o,p,q=0,r=!1,s,t,u,v,w,x=function(a){var b=1 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */let cardElement,contextId,elementId,fragmentValue,hoursFilter;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.tableSortButtonAction=_exports.tableSearchRowSet=_exports.tableSearchReset=_exports.tableSearch=_exports.init=_exports.getTable=void 0,_ajax=_interopRequireDefault(_ajax),_fragment=_interopRequireDefault(_fragment),_notification=_interopRequireDefault(_notification),_templates=_interopRequireDefault(_templates),Debouncer=_interopRequireWildcard(Debouncer),_override_modal=_interopRequireDefault(_override_modal),UserPreference=_interopRequireWildcard(UserPreference);let rowPreference,sortValue,searchElement,id,methodName,quizId=0,overridden=!1;const getTable=function(quiz){let hours=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,sortValueTable=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,page=arguments.length>3?arguments[3]:void 0;void 0!==page&&!0!==overridden||(page=0),overridden=!1;let search=document.getElementById(searchElement).value.trim(),tableElement=document.getElementById(elementId),spinner=tableElement.getElementsByClassName("overlay-icon-container")[0],tableBody=tableElement.getElementsByClassName("table-body")[0],values={search:search,page:page};if(quiz>0&&(quizId=quiz,values.quiz=quizId),hours&&(hoursFilter=hours,values.hoursahead=hoursFilter[0],values.hoursbehind=hoursFilter[1]),sortValueTable){sortValue=sortValueTable;let sortArray=sortValue.split("_"),sortOn=sortArray[0],direction=sortArray[1];values.sorton=sortOn,values.direction=direction}let params={data:JSON.stringify(values)};spinner.classList.remove("hide"),_fragment.default.loadFragment("local_assessfreq",fragmentValue,contextId,params).done(((response,js)=>{tableBody.innerHTML=response,js&&_templates.default.runTemplateJS(js),spinner.classList.add("hide"),tableEventListeners()})).fail((()=>{_notification.default.exception(new Error("Failed to update table."))}))};_exports.getTable=getTable;const debounceTable=Debouncer.debouncer((()=>{getTable(quizId,hoursFilter,sortValue)}),750),tableSort=event=>{event.preventDefault();let sortArray={};const linkUrl=new URL(event.target.closest("a").href),targetSortBy=linkUrl.searchParams.get("tsort");let targetSortOrder=linkUrl.searchParams.get("tdir");""===targetSortOrder&&(targetSortOrder="4"),sortArray[targetSortBy]=targetSortOrder,_ajax.default.call([{methodname:methodName,args:{tableid:id,preference:"sortby",values:JSON.stringify(sortArray)}}])[0].then((()=>{getTable(quizId,hoursFilter,sortValue)}))},tableHide=event=>{event.preventDefault();let hideArray={};const linkUrl=new URL(event.target.closest("a").href),links=document.getElementById(elementId).querySelectorAll("a");let targetAction,targetColumn,action,column;-1!==linkUrl.search.indexOf("thide")?(targetAction="hide",targetColumn=linkUrl.searchParams.get("thide")):(targetAction="show",targetColumn=linkUrl.searchParams.get("tshow"));for(let i=0;i{getTable(quizId,hoursFilter,sortValue)}))},tableReset=event=>{event.preventDefault(),_ajax.default.call([{methodname:methodName,args:{tableid:id,preference:"reset",values:JSON.stringify({})}}])[0].then((()=>{getTable(quizId,hoursFilter,sortValue)}))};_exports.tableSearch=event=>{if("Meta"===event.key||event.ctrlKey)return!1;(0===event.target.value.length||event.target.value.length>2)&&debounceTable()};_exports.tableSearchReset=()=>{let tableSearchInputElement=document.getElementById(searchElement);tableSearchInputElement.value="",tableSearchInputElement.focus(),getTable(quizId,hoursFilter,sortValue)};_exports.tableSearchRowSet=event=>{if(event.preventDefault(),"a"===event.target.tagName.toLowerCase()){let rows=event.target.dataset.metric;UserPreference.setUserPreference(rowPreference,rows).then((()=>{getTable(quizId,hoursFilter,sortValue)})).fail((()=>{_notification.default.exception(new Error("Failed to update user preference: rows"))}))}};const tableNav=event=>{event.preventDefault();const page=new URL(event.target.closest("a").href).searchParams.get("page");page&&getTable(quizId,hoursFilter,sortValue,page)};_exports.tableSortButtonAction=event=>{event.preventDefault();var element=event.target;if("a"===element.tagName.toLowerCase()&&element.dataset.sort!==sortValue){sortValue=element.dataset.sort;let links=element.parentNode.getElementsByTagName("a");for(let i=0;i{const tableElement=document.getElementById(elementId);let tableNavElement;if(cardElement){const tableCardElement=document.getElementById(cardElement),links=tableElement.querySelectorAll("a"),resetLink=tableElement.getElementsByClassName("resettable"),overrideLinks=tableElement.getElementsByClassName("action-icon override"),disabledLinks=tableElement.getElementsByClassName("action-icon disabled");tableNavElement=tableCardElement.querySelectorAll("nav");for(let i=0;i0&&resetLink[0].addEventListener("click",tableReset);for(let i=0;i{event.preventDefault()}))}else tableNavElement=tableElement.querySelectorAll("nav");tableNavElement.forEach((navElement=>{navElement.addEventListener("click",tableNav)}))},triggerOverrideModal=event=>{event.preventDefault();let userid=event.target.closest("a").id.substring(25);if(userid.includes("-")){let elements=userid.split("-");quizId=elements.pop(),userid=elements.pop()}_override_modal.default.displayModalForm(quizId,userid,hoursFilter)};_exports.init=function(quiz,context,tableCardElement,tableElementId,tableFragmentValue,tableRowPreference,tableSearchElement){let tableId=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,tableMethodName=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null;quizId=quiz,contextId=context,cardElement=tableCardElement,elementId=tableElementId,fragmentValue=tableFragmentValue,rowPreference=tableRowPreference,searchElement=tableSearchElement,id=tableId,methodName=tableMethodName}})); + +//# sourceMappingURL=table_handler.min.js.map \ No newline at end of file diff --git a/amd/build/table_handler.min.js.map b/amd/build/table_handler.min.js.map index 4b50485..79e834c 100644 --- a/amd/build/table_handler.min.js.map +++ b/amd/build/table_handler.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/table_handler.js"],"names":["cardElement","contextId","elementId","fragmentValue","hoursFilter","quizId","overridden","rowPreference","sortValue","searchElement","id","methodName","getTable","quiz","hours","sortValueTable","page","search","document","getElementById","value","trim","tableElement","spinner","getElementsByClassName","tableBody","values","hoursahead","hoursbehind","sortArray","split","sortOn","direction","sorton","params","JSON","stringify","classList","remove","Fragment","loadFragment","done","response","js","innerHTML","Templates","runTemplateJS","add","tableEventListeners","fail","Notification","exception","Error","debounceTable","Debouncer","debouncer","tableSort","event","preventDefault","linkUrl","URL","target","closest","href","targetSortBy","searchParams","get","targetSortOrder","Ajax","call","methodname","args","tableid","preference","then","tableHide","hideArray","links","querySelectorAll","targetAction","targetColumn","action","column","indexOf","i","hideLinkUrl","length","tableReset","tableSearch","key","ctrlKey","tableSearchReset","tableSearchInputElement","focus","tableSearchRowSet","tagName","toLowerCase","rows","dataset","metric","UserPreference","setUserPreference","tableNav","tableSortButtonAction","element","sort","parentNode","getElementsByTagName","tableNavElement","tableCardElement","resetLink","overrideLinks","disabledLinks","addEventListener","triggerOverrideModal","forEach","navElement","userid","substring","includes","elements","pop","OverrideModal","displayModalForm","init","context","tableElementId","tableFragmentValue","tableRowPreference","tableSearchElement","tableId","tableMethodName"],"mappings":"0rBAwBA,OACA,OACA,OACA,OACA,OACA,OACA,O,4lBAKIA,CAAAA,C,CACAC,C,CACAC,C,CACAC,C,CACAC,C,CACAC,CAAM,CAAG,C,CACTC,CAAU,G,CACVC,C,CACAC,C,CACAC,C,CAOAC,C,CAOAC,C,CAUSC,CAAQ,CAAG,SAACC,CAAD,CAAqD,IAA9CC,CAAAA,CAA8C,wDAAtC,IAAsC,CAAhCC,CAAgC,wDAAf,IAAe,CAATC,CAAS,wCACzE,GAAoB,WAAhB,QAAOA,CAAAA,CAAP,EAA+B,KAAAV,CAAnC,CAAwD,CACpDU,CAAI,CAAG,CACV,CAEDV,CAAU,GAAV,CALyE,GAOrEW,CAAAA,CAAM,CAAGC,QAAQ,CAACC,cAAT,CAAwBV,CAAxB,EAAuCW,KAAvC,CAA6CC,IAA7C,EAP4D,CAQrEC,CAAY,CAAGJ,QAAQ,CAACC,cAAT,CAAwBjB,CAAxB,CARsD,CASrEqB,CAAO,CAAGD,CAAY,CAACE,sBAAb,CAAoC,wBAApC,EAA8D,CAA9D,CAT2D,CAUrEC,CAAS,CAAGH,CAAY,CAACE,sBAAb,CAAoC,YAApC,EAAkD,CAAlD,CAVyD,CAWrEE,CAAM,CAAG,CAAC,OAAUT,CAAX,CAAmB,KAAQD,CAA3B,CAX4D,CAczE,GAAW,CAAP,CAAAH,CAAJ,CAAc,CACVR,CAAM,CAAGQ,CAAT,CACAa,CAAM,CAACb,IAAP,CAAcR,CACjB,CACD,GAAIS,CAAJ,CAAW,CACPV,CAAW,CAAGU,CAAd,CACAY,CAAM,CAACC,UAAP,CAAoBvB,CAAW,CAAC,CAAD,CAA/B,CACAsB,CAAM,CAACE,WAAP,CAAqBxB,CAAW,CAAC,CAAD,CACnC,CACD,GAAIW,CAAJ,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BtH,CAA/B,CAAuCgH,CAAvC,CAA+CjH,CAA/C,CACH,C,QAemB,QAAPwH,CAAAA,IAAO,CAAC/G,CAAD,CACCgH,CADD,CAEChB,CAFD,CAGCiB,CAHD,CAICC,CAJD,CAKCC,CALD,CAMCC,CAND,CAQ4B,IAD3BC,CAAAA,CAC2B,wDADjB,IACiB,CAA3BC,CAA2B,wDAAT,IAAS,CAC5C9H,CAAM,CAAGQ,CAAT,CACAZ,CAAS,CAAG4H,CAAZ,CACA7H,CAAW,CAAG6G,CAAd,CACA3G,CAAS,CAAG4H,CAAZ,CACA3H,CAAa,CAAG4H,CAAhB,CACAxH,CAAa,CAAGyH,CAAhB,CACAvH,CAAa,CAAGwH,CAAhB,CACAvH,CAAE,CAAGwH,CAAL,CACAvH,CAAU,CAAGwH,CAChB,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 * Table handler JS module.\n *\n * @module local_assessfreq/table_handler\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Fragment from 'core/fragment';\nimport Notification from 'core/notification';\nimport Templates from 'core/templates';\nimport * as Debouncer from 'local_assessfreq/debouncer';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\n\n/**\n * Module level variables.\n */\nlet cardElement;\nlet contextId;\nlet elementId;\nlet fragmentValue;\nlet hoursFilter;\nlet quizId = 0;\nlet overridden = false;\nlet rowPreference;\nlet sortValue;\nlet searchElement;\n\n/**\n * Table id variable.\n *\n * @type {string}\n */\nlet id;\n\n/**\n * Table method name variable.\n *\n * @type {string}\n */\nlet methodName;\n\n/**\n * Display the table that contains all the students in the exam as well as their attempts.\n *\n * @param {int} quiz The Quiz Id.\n * @param {array|null} hours Array with hour ahead or behind preference.\n * @param {string|null} sortValueTable Sort preference.\n * @param {int|string|null} page Page number.\n */\nexport const getTable = (quiz, hours = null, sortValueTable = null, page) => {\n if (typeof page === \"undefined\" || overridden === true) {\n page = 0;\n }\n\n overridden = false;\n\n let search = document.getElementById(searchElement).value.trim();\n let tableElement = document.getElementById(elementId);\n let spinner = tableElement.getElementsByClassName('overlay-icon-container')[0];\n let tableBody = tableElement.getElementsByClassName('table-body')[0];\n let values = {'search': search, 'page': page};\n\n // Add values to Object depending on dashboard type.\n if (quiz > 0) {\n quizId = quiz;\n values.quiz = quizId;\n }\n if (hours) {\n hoursFilter = hours;\n values.hoursahead = hoursFilter[0];\n values.hoursbehind = hoursFilter[1];\n }\n if (sortValueTable) {\n sortValue = sortValueTable;\n let sortArray = sortValue.split('_');\n let sortOn = sortArray[0];\n let direction = sortArray[1];\n values.sorton = sortOn;\n values.direction = direction;\n }\n\n let params = {'data': JSON.stringify(values)};\n\n spinner.classList.remove('hide'); // Show spinner if not already shown.\n Fragment.loadFragment('local_assessfreq', fragmentValue, contextId, params)\n .done((response, js) => {\n tableBody.innerHTML = response;\n if (js) {\n Templates.runTemplateJS(js); // Magic call the initialises JS from template included in response template HTML.\n }\n spinner.classList.add('hide');\n tableEventListeners(); // Re-add table event listeners.\n\n }).fail(() => {\n Notification.exception(new Error('Failed to update table.'));\n });\n};\n\n/**\n * This stops the ajax method that updates the table from being updated\n * while the user is still checking options.\n *\n */\nconst debounceTable = Debouncer.debouncer(() => {\n getTable(quizId, hoursFilter, sortValue);\n}, 750);\n\n/**\n * Process the sort click events from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSort = (event) => {\n event.preventDefault();\n\n let sortArray = {};\n const linkUrl = new URL(event.target.closest('a').href);\n const targetSortBy = linkUrl.searchParams.get('tsort');\n let targetSortOrder = linkUrl.searchParams.get('tdir');\n\n // We want to flip the clicked column.\n if (targetSortOrder === '') {\n targetSortOrder = \"4\";\n }\n\n sortArray[targetSortBy] = targetSortOrder;\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'sortby',\n values: JSON.stringify(sortArray)\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the sort click events from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableHide = (event) => {\n event.preventDefault();\n\n let hideArray = {};\n const linkUrl = new URL(event.target.closest('a').href);\n const tableElement = document.getElementById(elementId);\n const links = tableElement.querySelectorAll('a');\n let targetAction;\n let targetColumn;\n let action;\n let column;\n\n if (linkUrl.search.indexOf('thide') !== -1) {\n targetAction = 'hide';\n targetColumn = linkUrl.searchParams.get('thide');\n } else {\n targetAction = 'show';\n targetColumn = linkUrl.searchParams.get('tshow');\n }\n\n for (let i = 0; i < links.length; i++) {\n let hideLinkUrl = new URL(links[i].href);\n if (hideLinkUrl.search.indexOf('thide') !== -1) {\n action = 'hide';\n column = hideLinkUrl.searchParams.get('thide');\n } else {\n action = 'show';\n column = hideLinkUrl.searchParams.get('tshow');\n }\n\n if (action === 'show') {\n hideArray[column] = 1;\n }\n\n }\n\n hideArray[targetColumn] = (targetAction === 'hide') ? 1 : 0; // We want to flip the clicked column.\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'collapse',\n values: JSON.stringify(hideArray)\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the reset click event from the table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableReset = (event) => {\n event.preventDefault();\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'reset',\n values: JSON.stringify({})\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the search events from the student table.\n *\n */\nexport const tableSearch = (event) => {\n if (event.key === 'Meta' || event.ctrlKey) {\n return false;\n }\n\n if (event.target.value.length === 0 || event.target.value.length > 2) {\n debounceTable();\n }\n};\n\n/**\n * Process the search reset click event from the student table.\n *\n */\nexport const tableSearchReset = () => {\n let tableSearchInputElement = document.getElementById(searchElement);\n tableSearchInputElement.value = '';\n tableSearchInputElement.focus();\n getTable(quizId, hoursFilter, sortValue);\n};\n\n/**\n * Process the row set event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nexport const tableSearchRowSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let rows = event.target.dataset.metric;\n UserPreference.setUserPreference(rowPreference, rows)\n .then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: rows'));\n });\n }\n};\n\n/**\n * Process the nav event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableNav = (event) => {\n event.preventDefault();\n\n const linkUrl = new URL(event.target.closest('a').href);\n const page = linkUrl.searchParams.get('page');\n\n if (page) {\n getTable(quizId, hoursFilter, sortValue, page);\n }\n};\n\n/**\n * Get and process the selected assessment metric from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {Event} event The triggered event for the element.\n */\nexport const tableSortButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.sort !== sortValue) {\n sortValue = element.dataset.sort;\n\n let links = element.parentNode.getElementsByTagName('a');\n for (let i = 0; i < links.length; i++) {\n links[i].classList.remove('active');\n }\n\n element.classList.add('active');\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_quiz_table_inprogress_sort_preference', sortValue);\n\n debounceTable(); // Call function to update table.\n\n }\n};\n\n/**\n * Re-add event listeners when the student table is updated.\n */\nconst tableEventListeners = () => {\n const tableElement = document.getElementById(elementId);\n let tableNavElement;\n if (cardElement) {\n const tableCardElement = document.getElementById(cardElement);\n const links = tableElement.querySelectorAll('a');\n const resetLink = tableElement.getElementsByClassName('resettable');\n const overrideLinks = tableElement.getElementsByClassName('action-icon override');\n const disabledLinks = tableElement.getElementsByClassName('action-icon disabled');\n tableNavElement = tableCardElement.querySelectorAll('nav'); // There are two nav paging elements per table.\n\n for (let i = 0; i < links.length; i++) {\n let linkUrl = new URL(links[i].href);\n if (linkUrl.search.indexOf('thide') !== -1 || linkUrl.search.indexOf('tshow') !== -1) {\n links[i].addEventListener('click', tableHide);\n } else if (linkUrl.search.indexOf('tsort') !== -1) {\n links[i].addEventListener('click', tableSort);\n }\n\n }\n\n if (resetLink.length > 0) {\n resetLink[0].addEventListener('click', tableReset);\n }\n\n for (let i = 0; i < overrideLinks.length; i++) {\n overrideLinks[i].addEventListener('click', triggerOverrideModal);\n }\n\n for (let i = 0; i < disabledLinks.length; i++) {\n disabledLinks[i].addEventListener('click', (event) => {\n event.preventDefault();\n });\n }\n } else {\n tableNavElement = tableElement.querySelectorAll('nav');\n }\n\n tableNavElement.forEach((navElement) => {\n navElement.addEventListener('click', tableNav);\n });\n};\n\n/**\n * Trigger the override modal form. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerOverrideModal = (event) => {\n event.preventDefault();\n let userid = event.target.closest('a').id.substring(25);\n if (userid.includes('-')) {\n let elements = userid.split('-');\n quizId = elements.pop();\n userid = elements.pop();\n }\n\n OverrideModal.displayModalForm(quizId, userid, hoursFilter);\n};\n\n/**\n * Initialise method for table handler.\n *\n * @param {int} quiz The quiz id.\n * @param {int} context The context id.\n * @param {string} tableCardElement The table card element.\n * @param {string} tableElementId The table element id.\n * @param {string} tableFragmentValue The table fragment value.\n * @param {string} tableRowPreference The table row preference.\n * @param {string} tableSearchElement The table search element.\n * @param {string|null} tableId The table id.\n * @param {string|null} tableMethodName The table method name.\n */\nexport const init = (quiz,\n context,\n tableCardElement,\n tableElementId,\n tableFragmentValue,\n tableRowPreference,\n tableSearchElement,\n tableId = null,\n tableMethodName = null) => {\n quizId = quiz;\n contextId = context;\n cardElement = tableCardElement;\n elementId = tableElementId;\n fragmentValue = tableFragmentValue;\n rowPreference = tableRowPreference;\n searchElement = tableSearchElement;\n id = tableId;\n methodName = tableMethodName;\n};\n"],"file":"table_handler.min.js"} \ No newline at end of file +{"version":3,"file":"table_handler.min.js","sources":["../src/table_handler.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Table handler JS module.\n *\n * @module local_assessfreq/table_handler\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Fragment from 'core/fragment';\nimport Notification from 'core/notification';\nimport Templates from 'core/templates';\nimport * as Debouncer from 'local_assessfreq/debouncer';\nimport OverrideModal from 'local_assessfreq/override_modal';\nimport * as UserPreference from 'local_assessfreq/user_preferences';\n\n/**\n * Module level variables.\n */\nlet cardElement;\nlet contextId;\nlet elementId;\nlet fragmentValue;\nlet hoursFilter;\nlet quizId = 0;\nlet overridden = false;\nlet rowPreference;\nlet sortValue;\nlet searchElement;\n\n/**\n * Table id variable.\n *\n * @type {string}\n */\nlet id;\n\n/**\n * Table method name variable.\n *\n * @type {string}\n */\nlet methodName;\n\n/**\n * Display the table that contains all the students in the exam as well as their attempts.\n *\n * @param {int} quiz The Quiz Id.\n * @param {array|null} hours Array with hour ahead or behind preference.\n * @param {string|null} sortValueTable Sort preference.\n * @param {int|string|null} page Page number.\n */\nexport const getTable = (quiz, hours = null, sortValueTable = null, page) => {\n if (typeof page === \"undefined\" || overridden === true) {\n page = 0;\n }\n\n overridden = false;\n\n let search = document.getElementById(searchElement).value.trim();\n let tableElement = document.getElementById(elementId);\n let spinner = tableElement.getElementsByClassName('overlay-icon-container')[0];\n let tableBody = tableElement.getElementsByClassName('table-body')[0];\n let values = {'search': search, 'page': page};\n\n // Add values to Object depending on dashboard type.\n if (quiz > 0) {\n quizId = quiz;\n values.quiz = quizId;\n }\n if (hours) {\n hoursFilter = hours;\n values.hoursahead = hoursFilter[0];\n values.hoursbehind = hoursFilter[1];\n }\n if (sortValueTable) {\n sortValue = sortValueTable;\n let sortArray = sortValue.split('_');\n let sortOn = sortArray[0];\n let direction = sortArray[1];\n values.sorton = sortOn;\n values.direction = direction;\n }\n\n let params = {'data': JSON.stringify(values)};\n\n spinner.classList.remove('hide'); // Show spinner if not already shown.\n Fragment.loadFragment('local_assessfreq', fragmentValue, contextId, params)\n .done((response, js) => {\n tableBody.innerHTML = response;\n if (js) {\n Templates.runTemplateJS(js); // Magic call the initialises JS from template included in response template HTML.\n }\n spinner.classList.add('hide');\n tableEventListeners(); // Re-add table event listeners.\n\n }).fail(() => {\n Notification.exception(new Error('Failed to update table.'));\n });\n};\n\n/**\n * This stops the ajax method that updates the table from being updated\n * while the user is still checking options.\n *\n */\nconst debounceTable = Debouncer.debouncer(() => {\n getTable(quizId, hoursFilter, sortValue);\n}, 750);\n\n/**\n * Process the sort click events from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableSort = (event) => {\n event.preventDefault();\n\n let sortArray = {};\n const linkUrl = new URL(event.target.closest('a').href);\n const targetSortBy = linkUrl.searchParams.get('tsort');\n let targetSortOrder = linkUrl.searchParams.get('tdir');\n\n // We want to flip the clicked column.\n if (targetSortOrder === '') {\n targetSortOrder = \"4\";\n }\n\n sortArray[targetSortBy] = targetSortOrder;\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'sortby',\n values: JSON.stringify(sortArray)\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the sort click events from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableHide = (event) => {\n event.preventDefault();\n\n let hideArray = {};\n const linkUrl = new URL(event.target.closest('a').href);\n const tableElement = document.getElementById(elementId);\n const links = tableElement.querySelectorAll('a');\n let targetAction;\n let targetColumn;\n let action;\n let column;\n\n if (linkUrl.search.indexOf('thide') !== -1) {\n targetAction = 'hide';\n targetColumn = linkUrl.searchParams.get('thide');\n } else {\n targetAction = 'show';\n targetColumn = linkUrl.searchParams.get('tshow');\n }\n\n for (let i = 0; i < links.length; i++) {\n let hideLinkUrl = new URL(links[i].href);\n if (hideLinkUrl.search.indexOf('thide') !== -1) {\n action = 'hide';\n column = hideLinkUrl.searchParams.get('thide');\n } else {\n action = 'show';\n column = hideLinkUrl.searchParams.get('tshow');\n }\n\n if (action === 'show') {\n hideArray[column] = 1;\n }\n }\n\n hideArray[targetColumn] = (targetAction === 'hide') ? 1 : 0; // We want to flip the clicked column.\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'collapse',\n values: JSON.stringify(hideArray)\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the reset click event from the table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableReset = (event) => {\n event.preventDefault();\n\n // Set option via ajax.\n Ajax.call([{\n methodname: methodName,\n args: {\n tableid: id,\n preference: 'reset',\n values: JSON.stringify({})\n },\n }])[0].then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n });\n\n};\n\n/**\n * Process the search events from the student table.\n *\n */\nexport const tableSearch = (event) => {\n if (event.key === 'Meta' || event.ctrlKey) {\n return false;\n }\n\n if (event.target.value.length === 0 || event.target.value.length > 2) {\n debounceTable();\n }\n};\n\n/**\n * Process the search reset click event from the student table.\n *\n */\nexport const tableSearchReset = () => {\n let tableSearchInputElement = document.getElementById(searchElement);\n tableSearchInputElement.value = '';\n tableSearchInputElement.focus();\n getTable(quizId, hoursFilter, sortValue);\n};\n\n/**\n * Process the row set event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nexport const tableSearchRowSet = (event) => {\n event.preventDefault();\n if (event.target.tagName.toLowerCase() === 'a') {\n let rows = event.target.dataset.metric;\n UserPreference.setUserPreference(rowPreference, rows)\n .then(() => {\n getTable(quizId, hoursFilter, sortValue); // Reload the table.\n })\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference: rows'));\n });\n }\n};\n\n/**\n * Process the nav event from the student table.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst tableNav = (event) => {\n event.preventDefault();\n\n const linkUrl = new URL(event.target.closest('a').href);\n const page = linkUrl.searchParams.get('page');\n\n if (page) {\n getTable(quizId, hoursFilter, sortValue, page);\n }\n};\n\n/**\n * Get and process the selected assessment metric from the dropdown for the heatmap display,\n * and update the corresponding user preference.\n *\n * @param {Event} event The triggered event for the element.\n */\nexport const tableSortButtonAction = (event) => {\n event.preventDefault();\n var element = event.target;\n\n if (element.tagName.toLowerCase() === 'a' && element.dataset.sort !== sortValue) {\n sortValue = element.dataset.sort;\n\n let links = element.parentNode.getElementsByTagName('a');\n for (let i = 0; i < links.length; i++) {\n links[i].classList.remove('active');\n }\n\n element.classList.add('active');\n\n // Save selection as a user preference.\n UserPreference.setUserPreference('local_assessfreq_quiz_table_inprogress_sort_preference', sortValue);\n\n debounceTable(); // Call function to update table.\n }\n};\n\n/**\n * Re-add event listeners when the student table is updated.\n */\nconst tableEventListeners = () => {\n const tableElement = document.getElementById(elementId);\n let tableNavElement;\n if (cardElement) {\n const tableCardElement = document.getElementById(cardElement);\n const links = tableElement.querySelectorAll('a');\n const resetLink = tableElement.getElementsByClassName('resettable');\n const overrideLinks = tableElement.getElementsByClassName('action-icon override');\n const disabledLinks = tableElement.getElementsByClassName('action-icon disabled');\n tableNavElement = tableCardElement.querySelectorAll('nav'); // There are two nav paging elements per table.\n\n for (let i = 0; i < links.length; i++) {\n let linkUrl = new URL(links[i].href);\n if (linkUrl.search.indexOf('thide') !== -1 || linkUrl.search.indexOf('tshow') !== -1) {\n links[i].addEventListener('click', tableHide);\n } else if (linkUrl.search.indexOf('tsort') !== -1) {\n links[i].addEventListener('click', tableSort);\n }\n }\n\n if (resetLink.length > 0) {\n resetLink[0].addEventListener('click', tableReset);\n }\n\n for (let i = 0; i < overrideLinks.length; i++) {\n overrideLinks[i].addEventListener('click', triggerOverrideModal);\n }\n\n for (let i = 0; i < disabledLinks.length; i++) {\n disabledLinks[i].addEventListener('click', (event) => {\n event.preventDefault();\n });\n }\n } else {\n tableNavElement = tableElement.querySelectorAll('nav');\n }\n\n tableNavElement.forEach((navElement) => {\n navElement.addEventListener('click', tableNav);\n });\n};\n\n/**\n * Trigger the override modal form. Thin wrapper to add extra data to click event.\n *\n * @param {Event} event The triggered event for the element.\n */\nconst triggerOverrideModal = (event) => {\n event.preventDefault();\n let userid = event.target.closest('a').id.substring(25);\n if (userid.includes('-')) {\n let elements = userid.split('-');\n quizId = elements.pop();\n userid = elements.pop();\n }\n\n OverrideModal.displayModalForm(quizId, userid, hoursFilter);\n};\n\n/**\n * Initialise method for table handler.\n *\n * @param {int} quiz The quiz id.\n * @param {int} context The context id.\n * @param {string} tableCardElement The table card element.\n * @param {string} tableElementId The table element id.\n * @param {string} tableFragmentValue The table fragment value.\n * @param {string} tableRowPreference The table row preference.\n * @param {string} tableSearchElement The table search element.\n * @param {string|null} tableId The table id.\n * @param {string|null} tableMethodName The table method name.\n */\nexport const init = (quiz,\n context,\n tableCardElement,\n tableElementId,\n tableFragmentValue,\n tableRowPreference,\n tableSearchElement,\n tableId = null,\n tableMethodName = null) => {\n quizId = quiz;\n contextId = context;\n cardElement = tableCardElement;\n elementId = tableElementId;\n fragmentValue = tableFragmentValue;\n rowPreference = tableRowPreference;\n searchElement = tableSearchElement;\n id = tableId;\n methodName = tableMethodName;\n };\n"],"names":["cardElement","contextId","elementId","fragmentValue","hoursFilter","rowPreference","sortValue","searchElement","id","methodName","quizId","overridden","getTable","quiz","hours","sortValueTable","page","search","document","getElementById","value","trim","tableElement","spinner","getElementsByClassName","tableBody","values","hoursahead","hoursbehind","sortArray","split","sortOn","direction","sorton","params","JSON","stringify","classList","remove","loadFragment","done","response","js","innerHTML","runTemplateJS","add","tableEventListeners","fail","exception","Error","debounceTable","Debouncer","debouncer","tableSort","event","preventDefault","linkUrl","URL","target","closest","href","targetSortBy","searchParams","get","targetSortOrder","call","methodname","args","tableid","preference","then","tableHide","hideArray","links","querySelectorAll","targetAction","targetColumn","action","column","indexOf","i","length","hideLinkUrl","tableReset","key","ctrlKey","tableSearchInputElement","focus","tagName","toLowerCase","rows","dataset","metric","UserPreference","setUserPreference","tableNav","element","sort","parentNode","getElementsByTagName","tableNavElement","tableCardElement","resetLink","overrideLinks","disabledLinks","addEventListener","triggerOverrideModal","forEach","navElement","userid","substring","includes","elements","pop","displayModalForm","context","tableElementId","tableFragmentValue","tableRowPreference","tableSearchElement","tableId","tableMethodName"],"mappings":";;;;;;;;SAmCIA,YACAC,UACAC,UACAC,cACAC,siBAGAC,cACAC,UACAC,cAOAC,GAOAC,WAlBAC,OAAS,EACTC,YAAa,QA2BJC,SAAW,SAACC,UAAMC,6DAAQ,KAAMC,sEAAiB,KAAMC,iDAC5C,IAATA,OAAuC,IAAfL,aAC/BK,KAAO,GAGXL,YAAa,MAETM,OAASC,SAASC,eAAeZ,eAAea,MAAMC,OACtDC,aAAeJ,SAASC,eAAejB,WACvCqB,QAAUD,aAAaE,uBAAuB,0BAA0B,GACxEC,UAAYH,aAAaE,uBAAuB,cAAc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,QAASC,0BAG1C,IAAI1B,EAAI,EAAGA,EAAIwB,cAAcvB,OAAQD,IACtCwB,cAAcxB,GAAGyB,iBAAiB,SAAUnD,QACxCA,MAAMC,yBAId6C,gBAAkB9E,aAAaoD,iBAAiB,OAGpD0B,gBAAgBO,SAASC,aACrBA,WAAWH,iBAAiB,QAASV,cASvCW,qBAAwBpD,QAC1BA,MAAMC,qBACFsD,OAASvD,MAAMI,OAAOC,QAAQ,KAAKnD,GAAGsG,UAAU,OAChDD,OAAOE,SAAS,KAAM,KAClBC,SAAWH,OAAO/E,MAAM,KAC5BpB,OAASsG,SAASC,MAClBJ,OAASG,SAASC,8BAGRC,iBAAiBxG,OAAQmG,OAAQzG,4BAgB/B,SAACS,KACAsG,QACAd,iBACAe,eACAC,mBACAC,mBACAC,wBACAC,+DAAU,KACVC,uEAAkB,KACX/G,OAASG,KACTZ,UAAYkH,QACZnH,YAAcqG,iBACdnG,UAAYkH,eACZjH,cAAgBkH,mBAChBhH,cAAgBiH,mBAChB/G,cAAgBgH,mBAChB/G,GAAKgH,QACL/G,WAAagH"} \ No newline at end of file diff --git a/amd/build/user_preferences.min.js b/amd/build/user_preferences.min.js index 6eb7bdc..7294ec2 100644 --- a/amd/build/user_preferences.min.js +++ b/amd/build/user_preferences.min.js @@ -1,2 +1,11 @@ -define ("local_assessfreq/user_preferences",["exports","core/ajax","core/notification"],function(a,b,c){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.getUserPreference=a.setUserPreference=void 0;b=d(b);c=d(c);function d(a){return a&&a.__esModule?a:{default:a}}var e=function(a,d){return b.default.call([{methodname:"core_user_update_user_preferences",args:{preferences:[{type:a,value:d}]}}])[0].fail(function(){c.default.exception(new Error("Failed to update user preference"))})};a.setUserPreference=e;var f=function(a){return b.default.call([{methodname:"core_user_get_user_preferences",args:{name:a}}])[0]};a.getUserPreference=f}); -//# sourceMappingURL=user_preferences.min.js.map +define("local_assessfreq/user_preferences",["exports","core/ajax","core/notification"],(function(_exports,_ajax,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} +/** + * User preferences JS module. + * + * @module local_assessfreq/user_preferences + * @package local_assessfreq + * @copyright 2020 Guillermo Gomez + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.setUserPreference=_exports.getUserPreference=void 0,_ajax=_interopRequireDefault(_ajax),_notification=_interopRequireDefault(_notification);_exports.setUserPreference=(type,value)=>{const request={methodname:"core_user_update_user_preferences",args:{preferences:[{type:type,value:value}]}};return _ajax.default.call([request])[0].fail((()=>{_notification.default.exception(new Error("Failed to update user preference"))}))};_exports.getUserPreference=name=>{const request={methodname:"core_user_get_user_preferences",args:{name:name}};return _ajax.default.call([request])[0]}})); + +//# sourceMappingURL=user_preferences.min.js.map \ No newline at end of file diff --git a/amd/build/user_preferences.min.js.map b/amd/build/user_preferences.min.js.map index 18f98ef..1f5759f 100644 --- a/amd/build/user_preferences.min.js.map +++ b/amd/build/user_preferences.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/user_preferences.js"],"names":["setUserPreference","type","value","Ajax","call","methodname","args","preferences","fail","Notification","exception","Error","getUserPreference","name"],"mappings":"qNAwBA,OACA,O,mDAUO,GAAMA,CAAAA,CAAiB,CAAG,SAACC,CAAD,CAAOC,CAAP,CAAiB,CAQ9C,MAAOC,WAAKC,IAAL,CAAU,CAPD,CACZC,UAAU,CAAE,mCADA,CAEZC,IAAI,CAAE,CACFC,WAAW,CAAE,CAAC,CAACN,IAAI,CAAEA,CAAP,CAAaC,KAAK,CAAEA,CAApB,CAAD,CADX,CAFM,CAOC,CAAV,EAAqB,CAArB,EACNM,IADM,CACD,UAAM,CACRC,UAAaC,SAAb,CAAuB,GAAIC,CAAAA,KAAJ,CAAU,kCAAV,CAAvB,CACH,CAHM,CAIV,CAZM,C,sBAqBA,GAAMC,CAAAA,CAAiB,CAAG,SAACC,CAAD,CAAU,CAQvC,MAAOV,WAAKC,IAAL,CAAU,CAPD,CACZC,UAAU,CAAE,gCADA,CAEZC,IAAI,CAAE,CACF,KAAQO,CADN,CAFM,CAOC,CAAV,EAAqB,CAArB,CACV,CATM,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 * User preferences JS module.\n *\n * @module local_assessfreq/user_preferences\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\n\n/**\n * Generic handler to persist user preferences.\n *\n * @method setUserPreference\n * @param {string} type The name of the attribute you're updating\n * @param {string} value The value of the attribute you're updating\n * @return {promise} jQuery promise\n */\nexport const setUserPreference = (type, value) => {\n const request = {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [{type: type, value: value}]\n }\n };\n\n return Ajax.call([request])[0]\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference'));\n });\n};\n\n/**\n * Generic handler to get user preference.\n *\n * @method getUserPreference\n * @param {string} name The name of the attribute you're getting.\n * @return {promise} jQuery promise\n */\nexport const getUserPreference = (name) => {\n const request = {\n methodname: 'core_user_get_user_preferences',\n args: {\n 'name': name\n }\n };\n\n return Ajax.call([request])[0];\n};\n"],"file":"user_preferences.min.js"} \ No newline at end of file +{"version":3,"file":"user_preferences.min.js","sources":["../src/user_preferences.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * User preferences JS module.\n *\n * @module local_assessfreq/user_preferences\n * @package local_assessfreq\n * @copyright 2020 Guillermo Gomez \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Ajax from 'core/ajax';\nimport Notification from 'core/notification';\n\n/**\n * Generic handler to persist user preferences.\n *\n * @method setUserPreference\n * @param {string} type The name of the attribute you're updating\n * @param {string} value The value of the attribute you're updating\n * @return {promise} jQuery promise\n */\nexport const setUserPreference = (type, value) => {\n const request = {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [{type: type, value: value}]\n }\n };\n\n return Ajax.call([request])[0]\n .fail(() => {\n Notification.exception(new Error('Failed to update user preference'));\n });\n};\n\n/**\n * Generic handler to get user preference.\n *\n * @method getUserPreference\n * @param {string} name The name of the attribute you're getting.\n * @return {promise} jQuery promise\n */\nexport const getUserPreference = (name) => {\n const request = {\n methodname: 'core_user_get_user_preferences',\n args: {\n 'name': name\n }\n };\n\n return Ajax.call([request])[0];\n};\n"],"names":["type","value","request","methodname","args","preferences","Ajax","call","fail","exception","Error","name"],"mappings":";;;;;;;;6OAmCiC,CAACA,KAAMC,eAC9BC,QAAU,CACZC,WAAY,oCACZC,KAAM,CACFC,YAAa,CAAC,CAACL,KAAMA,KAAMC,MAAOA,iBAInCK,cAAKC,KAAK,CAACL,UAAU,GAC3BM,MAAK,2BACWC,UAAU,IAAIC,MAAM,oEAWPC,aACxBT,QAAU,CACZC,WAAY,iCACZC,KAAM,MACMO,cAITL,cAAKC,KAAK,CAACL,UAAU"} \ No newline at end of file diff --git a/amd/build/zoom_modal.min.js b/amd/build/zoom_modal.min.js index 209a8b6..7f5204d 100644 --- a/amd/build/zoom_modal.min.js +++ b/amd/build/zoom_modal.min.js @@ -1,2 +1,10 @@ -define ("local_assessfreq/zoom_modal",["core/str","core/modal_factory","core/fragment","core/ajax","core/templates","local_assessfreq/modal_large","core/notification"],function(a,b,c,d,e,f,g){var h={},i,j;h.zoomGraph=function(b,d,f){var h=b.target.parentElement.dataset.title;c.loadFragment("local_assessfreq",f,i,d).done(function(b){var c=JSON.parse(b);if(!0==c.hasdata){var d={withtable:!1,chartdata:JSON.stringify(c.chart),aspect:!1};j.setTitle(h);j.setBody(e.render("local_assessfreq/chart",d));j.show()}else{a.get_string("nodata","local_assessfreq").then(function(a){var b=document.createElement("h3");b.innerHTML=a;j.setTitle(h);j.setBody(b.outerHTML);j.show()}).catch(function(){g.exception(new Error("Failed to load string: nodata"))})}}).fail(function(){g.exception(new Error("Failed to load zoomed graph"))})};var k=function(){return new Promise(function(c,d){a.get_string("loading","core").then(function(a){b.create({type:f.TYPE,title:a,body:"

"}).done(function(a){j=a;c()})}).catch(function(){d(new Error("Failed to load string: loading"))})})};h.init=function(a){i=a;k()};return h}); -//# sourceMappingURL=zoom_modal.min.js.map +/** + * Javascript for report card display and processing. + * + * @package local_assessfreq + * @copyright 2020 Matt Porritt + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define("local_assessfreq/zoom_modal",["core/str","core/modal_factory","core/fragment","core/ajax","core/templates","local_assessfreq/modal_large","core/notification"],(function(Str,ModalFactory,Fragment,Ajax,Templates,ModalLarge,Notification){var contextid,modalObj,ZoomModal={};ZoomModal.zoomGraph=function(event,params,method){let title=event.target.parentElement.dataset.title;Fragment.loadFragment("local_assessfreq",method,contextid,params).done((response=>{let resObj=JSON.parse(response);if(1==resObj.hasdata){var context={withtable:!1,chartdata:JSON.stringify(resObj.chart),aspect:!1};return modalObj.setTitle(title),modalObj.setBody(Templates.render("local_assessfreq/chart",context)),void modalObj.show()}Str.get_string("nodata","local_assessfreq").then((str=>{const noDatastr=document.createElement("h3");noDatastr.innerHTML=str,modalObj.setTitle(title),modalObj.setBody(noDatastr.outerHTML),modalObj.show()}))})).fail((()=>{Notification.exception(new Error("Failed to load zoomed graph"))}))};return ZoomModal.init=function(context){contextid=context,new Promise(((resolve,reject)=>{Str.get_string("loading","core").then((title=>{ModalFactory.create({type:ModalLarge.TYPE,title:title,body:'

'}).done((modal=>{modalObj=modal,resolve()}))})).catch((()=>{reject(new Error("Failed to load string: loading"))}))}))},ZoomModal})); + +//# sourceMappingURL=zoom_modal.min.js.map \ No newline at end of file diff --git a/amd/build/zoom_modal.min.js.map b/amd/build/zoom_modal.min.js.map index 6f16f9b..f05bfad 100644 --- a/amd/build/zoom_modal.min.js.map +++ b/amd/build/zoom_modal.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/zoom_modal.js"],"names":["define","Str","ModalFactory","Fragment","Ajax","Templates","ModalLarge","Notification","ZoomModal","contextid","modalObj","zoomGraph","event","params","method","title","target","parentElement","dataset","loadFragment","done","response","resObj","JSON","parse","hasdata","context","stringify","chart","aspect","setTitle","setBody","render","show","get_string","then","str","noDatastr","document","createElement","innerHTML","outerHTML","catch","exception","Error","fail","createModal","Promise","resolve","reject","create","type","TYPE","body","modal","init"],"mappings":"AAuBAA,OAAM,+BAAC,CAAC,UAAD,CAAa,oBAAb,CAAmC,eAAnC,CAAoD,WAApD,CAAiE,gBAAjE,CAAmF,8BAAnF,CACH,mBADG,CAAD,CAEN,SAASC,CAAT,CAAcC,CAAd,CAA4BC,CAA5B,CAAsCC,CAAtC,CAA4CC,CAA5C,CAAuDC,CAAvD,CAAmEC,CAAnE,CAAiF,IAKzEC,CAAAA,CAAS,CAAG,EAL6D,CAMzEC,CANyE,CAOzEC,CAPyE,CAe7EF,CAAS,CAACG,SAAV,CAAsB,SAASC,CAAT,CAAgBC,CAAhB,CAAwBC,CAAxB,CAAgC,CAClD,GAAIC,CAAAA,CAAK,CAAGH,CAAK,CAACI,MAAN,CAAaC,aAAb,CAA2BC,OAA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B,MAAO,IAAIC,CAAAA,OAAJ,CAAY,SAACC,CAAD,CAAUC,CAAV,CAAqB,CACpChD,CAAG,CAACiC,UAAJ,CAAe,SAAf,CAA0B,MAA1B,EAAkCC,IAAlC,CAAuC,SAACpB,CAAD,CAAW,CAE9Cb,CAAY,CAACgD,MAAb,CAAoB,CAChBC,IAAI,CAAE7C,CAAU,CAAC8C,IADD,CAEhBrC,KAAK,CAAEA,CAFS,CAGhBsC,IAAI,0FAHY,CAApB,EAKCjC,IALD,CAKM,SAACkC,CAAD,CAAW,CACb5C,CAAQ,CAAG4C,CAAX,CACAN,CAAO,EACV,CARD,CASH,CAXD,EAWGN,KAXH,CAWS,UAAM,CACXO,CAAM,CAAC,GAAIL,CAAAA,KAAJ,CAAU,gCAAV,CAAD,CACT,CAbD,CAcH,CAfM,CAgBV,CAjBD,CAsBApC,CAAS,CAAC+C,IAAV,CAAiB,SAAS7B,CAAT,CAAkB,CAC/BjB,CAAS,CAAGiB,CAAZ,CACAoB,CAAW,EACd,CAHD,CAKA,MAAOtC,CAAAA,CACV,CAjFK,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 * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax', 'core/templates', 'local_assessfreq/modal_large',\n 'core/notification'],\nfunction(Str, ModalFactory, Fragment, Ajax, Templates, ModalLarge, Notification) {\n\n /**\n * Module level variables.\n */\n var ZoomModal = {};\n var contextid;\n var modalObj;\n const spinner = '

'\n + ''\n + '

';\n\n /**\n * Provides zoom functionality for card graphs.\n */\n ZoomModal.zoomGraph = function(event, params, method) {\n let title = event.target.parentElement.dataset.title;\n\n Fragment.loadFragment('local_assessfreq', method, contextid, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata == true) {\n var context = { 'withtable' : false, 'chartdata' : JSON.stringify(resObj.chart), aspect: false};\n modalObj.setTitle(title);\n modalObj.setBody(Templates.render('local_assessfreq/chart', context));\n modalObj.show();\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n modalObj.setTitle(title);\n modalObj.setBody(noDatastr.outerHTML);\n modalObj.show();\n return;\n }).catch(() => {\n Notification.exception(new Error('Failed to load string: nodata'));\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load zoomed graph'));\n return;\n });\n\n };\n\n /**\n * Create the modal window for graph zooming.\n *\n * @private\n */\n const createModal = function() {\n return new Promise((resolve, reject) => {\n Str.get_string('loading', 'core').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalLarge.TYPE,\n title: title,\n body: spinner\n })\n .done((modal) => {\n modalObj = modal;\n resolve();\n });\n }).catch(() => {\n reject(new Error('Failed to load string: loading'));\n });\n });\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n ZoomModal.init = function(context) {\n contextid = context;\n createModal();\n };\n\n return ZoomModal;\n});\n"],"file":"zoom_modal.min.js"} \ No newline at end of file +{"version":3,"file":"zoom_modal.min.js","sources":["../src/zoom_modal.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Javascript for report card display and processing.\n *\n * @package local_assessfreq\n * @copyright 2020 Matt Porritt \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\ndefine(\n ['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax', 'core/templates', 'local_assessfreq/modal_large',\n 'core/notification'],\n function (Str, ModalFactory, Fragment, Ajax, Templates, ModalLarge, Notification) {\n\n /**\n * Module level variables.\n */\n var ZoomModal = {};\n var contextid;\n var modalObj;\n const spinner = '

'\n + ''\n + '

';\n\n /**\n * Provides zoom functionality for card graphs.\n */\n ZoomModal.zoomGraph = function (event, params, method) {\n let title = event.target.parentElement.dataset.title;\n\n Fragment.loadFragment('local_assessfreq', method, contextid, params)\n .done((response) => {\n let resObj = JSON.parse(response);\n if (resObj.hasdata == true) {\n var context = { 'withtable' : false, 'chartdata' : JSON.stringify(resObj.chart), aspect: false};\n modalObj.setTitle(title);\n modalObj.setBody(Templates.render('local_assessfreq/chart', context));\n modalObj.show();\n return;\n } else {\n Str.get_string('nodata', 'local_assessfreq').then((str) => {\n const noDatastr = document.createElement('h3');\n noDatastr.innerHTML = str;\n modalObj.setTitle(title);\n modalObj.setBody(noDatastr.outerHTML);\n modalObj.show();\n return;\n });\n }\n }).fail(() => {\n Notification.exception(new Error('Failed to load zoomed graph'));\n return;\n });\n\n };\n\n /**\n * Create the modal window for graph zooming.\n *\n * @private\n */\n const createModal = function () {\n return new Promise((resolve, reject) => {\n Str.get_string('loading', 'core').then((title) => {\n // Create the Modal.\n ModalFactory.create({\n type: ModalLarge.TYPE,\n title: title,\n body: spinner\n })\n .done((modal) => {\n modalObj = modal;\n resolve();\n });\n }).catch(() => {\n reject(new Error('Failed to load string: loading'));\n });\n });\n };\n\n /**\n * Initialise method for quiz dashboard rendering.\n */\n ZoomModal.init = function (context) {\n contextid = context;\n createModal();\n };\n\n return ZoomModal;\n }\n);\n"],"names":["define","Str","ModalFactory","Fragment","Ajax","Templates","ModalLarge","Notification","contextid","modalObj","ZoomModal","zoomGraph","event","params","method","title","target","parentElement","dataset","loadFragment","done","response","resObj","JSON","parse","hasdata","context","stringify","chart","aspect","setTitle","setBody","render","show","get_string","then","str","noDatastr","document","createElement","innerHTML","outerHTML","fail","exception","Error","init","Promise","resolve","reject","create","type","TYPE","body","modal","catch"],"mappings":";;;;;;;AAuBAA,qCACI,CAAC,WAAY,qBAAsB,gBAAiB,YAAa,iBAAkB,+BACnF,sBACA,SAAUC,IAAKC,aAAcC,SAAUC,KAAMC,UAAWC,WAAYC,kBAM5DC,UACAC,SAFAC,UAAY,GAUhBA,UAAUC,UAAY,SAAUC,MAAOC,OAAQC,YACvCC,MAAQH,MAAMI,OAAOC,cAAcC,QAAQH,MAE/CZ,SAASgB,aAAa,mBAAoBL,OAAQN,UAAWK,QAC5DO,MAAMC,eACCC,OAASC,KAAKC,MAAMH,aACF,GAAlBC,OAAOG,QAAiB,KACpBC,QAAU,YAAgB,YAAqBH,KAAKI,UAAUL,OAAOM,OAAQC,QAAQ,UACzFpB,SAASqB,SAASf,OAClBN,SAASsB,QAAQ1B,UAAU2B,OAAO,yBAA0BN,eAC5DjB,SAASwB,OAGThC,IAAIiC,WAAW,SAAU,oBAAoBC,MAAMC,YACzCC,UAAYC,SAASC,cAAc,MACzCF,UAAUG,UAAYJ,IACtB3B,SAASqB,SAASf,OAClBN,SAASsB,QAAQM,UAAUI,WAC3BhC,SAASwB,aAIlBS,MAAK,KACJnC,aAAaoC,UAAU,IAAIC,MAAM,2CAiCzClC,UAAUmC,KAAO,SAAUnB,SACvBlB,UAAYkB,QAtBL,IAAIoB,SAAQ,CAACC,QAASC,UACzB/C,IAAIiC,WAAW,UAAW,QAAQC,MAAMpB,QAEpCb,aAAa+C,OAAO,CAChBC,KAAM5C,WAAW6C,KACjBpC,MAAOA,MACPqC,KAhDA,wFAkDHhC,MAAMiC,QACH5C,SAAW4C,MACXN,gBAELO,OAAM,KACLN,OAAO,IAAIJ,MAAM,0CAatBlC"} \ No newline at end of file diff --git a/amd/src/chart_data.js b/amd/src/chart_data.js index c66a818..0ee5dbc 100644 --- a/amd/src/chart_data.js +++ b/amd/src/chart_data.js @@ -90,8 +90,6 @@ export const getCardCharts = (quizId, hoursFilter, yearSelect) => { chartBody.innerHTML = noDatastr.outerHTML; spinner.classList.add('hide'); // Hide spinner if not already hidden. return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: nodata')); }); } }).fail(() => { diff --git a/amd/src/dashboard_quiz.js b/amd/src/dashboard_quiz.js index 6a036bf..9401596 100644 --- a/amd/src/dashboard_quiz.js +++ b/amd/src/dashboard_quiz.js @@ -129,8 +129,6 @@ const processDashboard = (quiz) => { Str.get_string('dashboard:quiztitle', 'local_assessfreq', {'quiz': quizArray.name, 'course': quizArray.courseshortname}) .then((str) => { document.title = str; - }).catch(() => { - Notification.exception(new Error('Failed to load string: dashboard:quiztitle')); }); // Populate quiz summary card with details. @@ -221,8 +219,6 @@ export const init = (context, quiz) => { ChartData.init(cards, context, 'get_quiz_chart', 'local_assessfreq/chart'); Str.get_string('loadingquiztitle', 'local_assessfreq').then((str) => { selectQuizStr = str; - }).catch(() => { - Notification.exception(new Error('Failed to load string: loadingquiz')); }).then(() => { if (quiz > 0) { quizId = quiz; diff --git a/amd/src/dayview.js b/amd/src/dayview.js index 4e3bdb0..5c6c76c 100644 --- a/amd/src/dayview.js +++ b/amd/src/dayview.js @@ -167,10 +167,7 @@ define( */ Dayview.init = function () { // Load the strings we'll need later. - Str.get_strings(stringArr).catch(() => { // Get required strings. - Notification.exception(new Error('Failed to load strings')); - return; - }).then(stringReturn => { // Save string to global to be used later. + Str.get_strings(stringArr).then(stringReturn => { // Save string to global to be used later. stringResult = stringReturn; }); @@ -198,8 +195,6 @@ define( modalObj = modal; }); - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); }); }; diff --git a/amd/src/form_modal.js b/amd/src/form_modal.js index 23117f2..56ffc39 100644 --- a/amd/src/form_modal.js +++ b/amd/src/form_modal.js @@ -123,8 +123,6 @@ define( }); }); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); }); }; @@ -174,8 +172,6 @@ define( observer.observe(modalContainer, observerConfig); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: searchquiz')); }); }); }; @@ -203,8 +199,6 @@ define( modalObj.getBody().prepend(element); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: searchquiz')); }); } } else { diff --git a/amd/src/override_modal.js b/amd/src/override_modal.js index 6409e51..3a07232 100644 --- a/amd/src/override_modal.js +++ b/amd/src/override_modal.js @@ -65,8 +65,6 @@ define( }); }); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); }); }; @@ -92,8 +90,6 @@ define( modalObj.setTitle(title); modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_override_form', contextid, params)); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: useroverride')); }); }; diff --git a/amd/src/summary_participants.js b/amd/src/summary_participants.js index 3182a80..0e5198e 100644 --- a/amd/src/summary_participants.js +++ b/amd/src/summary_participants.js @@ -60,8 +60,6 @@ define( noDatastr.innerHTML = str; chartElement.innerHTML = noDatastr.outerHTML; return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: nodata')); }); } }).fail(() => { diff --git a/amd/src/zoom_modal.js b/amd/src/zoom_modal.js index 06bbc1e..304b5a5 100644 --- a/amd/src/zoom_modal.js +++ b/amd/src/zoom_modal.js @@ -59,8 +59,6 @@ define( modalObj.setBody(noDatastr.outerHTML); modalObj.show(); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: nodata')); }); } }).fail(() => {