Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Breaking/tdr 9/handlebars 4 upgrade #379

Draft
wants to merge 5 commits into
base: develop
Choose a base branch
from

Conversation

oatymart
Copy link
Contributor

@oatymart oatymart commented Sep 21, 2023

https://oat-sa.atlassian.net/browse/TR-3264
https://oat-sa.atlassian.net/wiki/spaces/FOUN/pages/144081031/Upgrade+Handlebars

  • rebundle all PCIs for Handlebars 4
  • migration for default PCIs
  • rebundle JS
  • composer dependency update

@github-actions
Copy link

Version

Target Version 8.11.0
Last version 8.10.2

There are 0 BREAKING CHANGE, 1 feature, 1 fix

@codecov-commenter
Copy link

Codecov Report

Patch and project coverage have no change.

Comparison is base (c6361a8) 0.00% compared to head (b5af867) 0.00%.

Additional details and impacted files
@@            Coverage Diff            @@
##             develop    #379   +/-   ##
=========================================
  Coverage       0.00%   0.00%           
  Complexity       176     176           
=========================================
  Files             12      12           
  Lines            563     563           
=========================================
  Misses           563     563           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@jsconan jsconan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea of using a different namespace for Handlebars in PCI is nice. However, it will only work if we can make sure the lib is loaded before.

Look at https://oat-sa.atlassian.net/browse/ADF-1293 for having a use case.

</button>`).appendTo($modal),options.startClosed||modal._open($modal)})},_destroy:function($element){return $element.each(function(){var $modal=$(this),options=$modal.data(dataNs);$modal.removeData(dataNs),$("#"+options.modalOverlay).remove(),$modal.hide()})},_bindEvents:function($element){var options=$element.data(dataNs);options&&("responsive"===options.width&&$(window).on("resize.modal",function(e){e.preventDefault(),modal._resize($element)}),!options.disableClosing&&($("."+options.modalCloseClass,$element).on("click.modal",function(e){e.preventDefault(),closeModal($element)}),$("#"+options.modalOverlay).on("click.modal",function(e){e.preventDefault(),closeModal($element)}),!options.disableEscape&&$(document).on("keydown.modal",function(e){27===e.keyCode&&(e.preventDefault(),closeModal($element))})))},_unBindEvents:function($element){var options=$element.data(dataNs);options&&"responsive"===options.width&&$(window).off("resize.modal"),$element.off("click.modal"),options&&!options.disableClosing&&($("."+options.modalCloseClass,$element).off("click.modal"),$("#"+options.modalOverlay).off("click.modal"),$(document).off("keydown.modal"))},_open:function($element){var modalHeight=$element.outerHeight(),windowHeight=$(window).height(),options=$element.data(dataNs),topOffset,onOpen,$overlay,to;"undefined"!=typeof options&&(onOpen=function(){$element.addClass("opened"),modal._bindEvents($element)},topOffset=options.top?options.top:options.vCenter||modalHeight>windowHeight?40:(windowHeight-modalHeight)/2,!options.top&&!$element.parent().hasClass("no-scroll-offset")&&$element.parents().map(function(){"BODY"!==this.tagName&&"HTML"!==this.tagName&&(topOffset+=parseInt($(this).scrollTop(),10))}),to={opacity:"1",top:topOffset+"px"},modal._resize($element),$overlay=$("#"+options.modalOverlay),$element.show(),options.animate&&$element.is(":visible")?($element.css({top:"-"+modalHeight+"px",display:"block"}),$overlay.fadeIn(options.animate-animateDiff),$element.animate(to,options.animate,onOpen)):($overlay.show(),$element.css(to),onOpen()))},_close:function($element){closeModal($element)},_resize:function($element){var options=$element.data(dataNs),windowWidth=parseInt($(window).width(),10),css={},modalWidth="responsive"===options.width?.7*windowWidth:parseInt(options.width,10);css.width=Math.max(modalWidth,options.minWidth),options.minHeight&&(css.minHeight=parseInt(options.minHeight)+"px"),$element.css(css)}};return function listenDataAttr($container){new DataAttrHandler("modal",{container:$container,listenerEvent:"click",namespace:dataNs}).init(function($elt,$target){$target.modal()})}}),define("tpl!audioRecordingInteraction/runtime/js/dialog/tpl/body",["taoQtiItem/portableLib/handlebars_4"],function(hb){return hb.template({compiler:[8,">= 4.3.0"],main:function(container,depth0,helpers,partials,data){var lookupProperty=container.lookupProperty||function(parent,propertyName){return Object.prototype.hasOwnProperty.call(parent,propertyName)?parent[propertyName]:void 0},stack1,helper;return"<div\n class=\"modal "+container.escapeExpression((helper=null==(helper=lookupProperty(helpers,"class")||(null==depth0?depth0:lookupProperty(depth0,"class")))?container.hooks.helperMissing:helper,"function"==typeof helper?helper.call(null==depth0?container.nullContext||{}:depth0,{name:"class",hash:{},data:data,loc:{start:{line:2,column:17},end:{line:2,column:26}}}):helper))+"\"\n role=\"dialog\"\n aria-modal=\"true\"\n data-control=\"navigable-modal-body\"\n aria-describedby=\"core/ui-dialog-message-"+container.escapeExpression((helper=null==(helper=lookupProperty(helpers,"dialogId")||(null==depth0?depth0:lookupProperty(depth0,"dialogId")))?container.hooks.helperMissing:helper,"function"==typeof helper?helper.call(null==depth0?container.nullContext||{}:depth0,{name:"dialogId",hash:{},data:data,loc:{start:{line:6,column:45},end:{line:6,column:57}}}):helper))+"\"\n>\n <div class=\"modal-body clearfix\">\n <p id=\"core/ui-dialog-message-"+container.escapeExpression((helper=null==(helper=lookupProperty(helpers,"dialogId")||(null==depth0?depth0:lookupProperty(depth0,"dialogId")))?container.hooks.helperMissing:helper,"function"==typeof helper?helper.call(null==depth0?container.nullContext||{}:depth0,{name:"dialogId",hash:{},data:data,loc:{start:{line:9,column:38},end:{line:9,column:50}}}):helper))+"\" class=\"message\">"+(null==(stack1=(helper=null==(helper=lookupProperty(helpers,"message")||(null==depth0?depth0:lookupProperty(depth0,"message")))?container.hooks.helperMissing:helper,"function"==typeof helper?helper.call(null==depth0?container.nullContext||{}:depth0,{name:"message",hash:{},data:data,loc:{start:{line:9,column:68},end:{line:9,column:81}}}):helper))?"":stack1)+"</p>\n </div>\n</div>"},useData:!0})}),define("audioRecordingInteraction/runtime/js/dialog",["lodash","jquery","audioRecordingInteraction/runtime/js/modal","tpl!audioRecordingInteraction/runtime/js/dialog/tpl/body"],function(_,$,modal,bodyTpl){"use strict";const _scope=".modal",_defaults={message:"",width:500,animate:!1,autoRender:!1,autoDestroy:!1,renderTo:"body"},dialog={init(options){const events={},initOptions=_.omit(options||{},(value,key)=>!!(2<key.length&&"on"===key.substr(0,2))&&(events[key.substr(2)]=value,!0));return _.defaults(this,initOptions,_defaults),this.dialogId=_.uniqueId("dlg-"),this.$html=$(bodyTpl(this)),this.rendered=!1,this.destroyed=!1,_.forEach(events,(callback,eventName)=>{0>eventName.indexOf(".")&&(eventName+=_scope),this.on(eventName.toLowerCase(),callback)}),this.autoRender&&this.render(),this},destroy(){return this.destroyed||(this._destroy(),this.rendered=!1,this.destroyed=!0,this.trigger("destroy.modal"),this.$html.off(_scope).remove(),this.$html=null),this},render(to){return this.destroyed||($(to||this.renderTo).append(this.$html),this._install(),this.rendered=!0),this},show(){return this.destroyed||(this.rendered?this._open():this.render()),this},hide(){return!this.destroyed&&this.rendered&&(this._close(),this.autoDestroy&&this.destroy()),this},on(eventName){return this.$html&&this.$html.on.apply(this.$html,arguments),this},off(eventName){return this.$html&&this.$html.off.apply(this.$html,arguments),this},trigger(eventName,extraParameters){return this.$html&&(void 0===extraParameters&&(extraParameters=[]),!_.isArray(extraParameters)&&(extraParameters=[extraParameters]),extraParameters=Array.prototype.slice.call(extraParameters),extraParameters.push(this),this.$html.trigger(eventName,extraParameters)),this},getDom(){return this.$html},_install(){if(!this.destroyed){this.$html.modal({width:this.width,animate:this.animate,disableClosing:this.disableClosing,disableEscape:this.disableEscape}).on("closed.modal",()=>{this.autoDestroy&&this.destroy()});const $items=this.getDom().add($(_scope).find("input")),closeButton=$(_scope).find("#modal-close-btn")[0];closeButton&&$items.push(closeButton),this.trigger("create.dialog")}},_open(){this.$html.modal("open")},_close(){this.$html.modal("close")},_destroy(){this.$html.modal("destroy"),this.navigator&&this.navigator.destroy(),this.globalShortcut&&this.globalShortcut.clear()}};return function dialogFactory(options){const instance=Object.assign({},dialog);return instance.init(options),instance}}),define("audioRecordingInteraction/runtime/js/player",["taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/jquery_2_1_1","taoQtiItem/portableLib/OAT/util/event","audioRecordingInteraction/runtime/js/dialog","i18n"],function(_,$,event,dialogFactory,__){"use strict";function b64toBlob(b64Data,contentType,sliceSize){var byteCharacters=atob(b64Data),byteArrays=[],offset,slice,byteNumbers,byteArray,blob,i;for(contentType=contentType||"",sliceSize=sliceSize||512,offset=0;offset<byteCharacters.length;offset+=sliceSize){for(slice=byteCharacters.slice(offset,offset+sliceSize),byteNumbers=Array(slice.length),i=0;i<slice.length;i++)byteNumbers[i]=slice.charCodeAt(i);byteArray=new Uint8Array(byteNumbers),byteArrays.push(byteArray)}return blob=new Blob(byteArrays,{type:contentType}),blob}var playerStates={CREATED:"created",IDLE:"idle",PLAYING:"playing"};return function playerFactory(){function setState(playerInstance,newState){state=newState,playerInstance.trigger("statechange"),playerInstance.trigger(newState)}function errorDialog(message){var dialog=dialogFactory({message:message,autoRender:!0,autoDestroy:!0,class:"icon-info audio"});return dialog}var state=playerStates.CREATED,audioEl,player;return player={is:function is(queriedState){return state===queriedState},load:function load(url){var self=this;audioEl=new Audio(url),audioEl.ondurationchange=function ondurationchange(){_.isFinite(audioEl.duration)&&self.trigger("durationchange",[audioEl.duration])},audioEl.oncanplay=function oncanplay(){setState(player,playerStates.IDLE),self.trigger("oncanplay")},audioEl.onended=function onended(){setState(player,playerStates.IDLE),audioEl.currentTime=0,self.trigger("timeupdate",[0]),self.trigger("playbackend")},audioEl.onplaying=function onplaying(){setState(player,playerStates.PLAYING)},audioEl.ontimeupdate=function ontimeupdate(){self.trigger("timeupdate",[audioEl.currentTime])},audioEl.onloadedmetadata=function(){var ontimeupdateBackup=audioEl.ontimeupdate;audioEl.duration===1/0&&(audioEl.ontimeupdate=function(){audioEl.ontimeupdate=ontimeupdateBackup,audioEl.currentTime=0,audioEl.load()},audioEl.currentTime=1e101,audioEl.onloadedmetadata=null)},setState(player,playerStates.IDLE)},loadFromBase64:function loadFromBase64(base64,mime){var blob=b64toBlob(base64,mime),blobUrl=window.URL&&window.URL.createObjectURL&&window.URL.createObjectURL(blob);blobUrl&&this.load(blobUrl)},play:function play(){audioEl.play().catch(e=>errorDialog(__("Audio has been previously recorded. Your browser does not support the playback of this recording. Please try on a different browser.")))},stop:function stop(){audioEl.pause(),audioEl.currentTime=0,setState(player,playerStates.IDLE),this.trigger("playbackend")},unload:function unload(){audioEl&&(audioEl.ontimeupdate=null),audioEl=null,setState(player,playerStates.CREATED)}},event.addEventMgr(player),player}}),define("audioRecordingInteraction/runtime/js/providers/mediaRecorder",["taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/OAT/util/event"],function(_,event){"use strict";var defaultPartialUpdateInterval=1e3;return function mediaRecorderProviderFactory(config){var partialUpdateInterval=config.partialUpdateInterval||1000,partialUpdateTimeout=null,partialUpdateAllowed=!0,partialSize=0,recordSize=0,cleanupPartialUpdateTimeout=function cleanupPartialUpdateTimeout(){partialUpdateTimeout&&clearTimeout(partialUpdateTimeout),partialUpdateTimeout=null},MediaRecorder=window.MediaRecorder,recorderOptions={audioBitsPerSecond:config.audioBitrate||2e4},chunks=[],chunkSizeMs=100,codecsByPreferenceOrder=["audio/ogg;codecs=opus","audio/webm;codecs=opus","audio/webm","audio/ogg","audio/mp4"],mediaRecorderProvider,mediaRecorder,mimeType;return"function"==typeof MediaRecorder.isTypeSupported&&codecsByPreferenceOrder.forEach(function(format){_.isUndefined(recorderOptions.mimeType)&&MediaRecorder.isTypeSupported(format)&&(recorderOptions.mimeType=format)}),mediaRecorderProvider={init:function init(stream){var self=this;mediaRecorder=new MediaRecorder(stream,recorderOptions),mimeType=mediaRecorder.mimeType,mediaRecorder.ondataavailable=function ondataavailable(e){var blob;chunks.push(e.data),recordSize+=e.data.size,config.updateResponsePartially&&partialUpdateAllowed&&recordSize>partialSize&&(partialUpdateAllowed=!1,partialSize=recordSize,blob=new Blob(chunks,{type:mimeType}),self.trigger("partialblobavailable",[blob]),partialUpdateTimeout=setTimeout(function allowPartialUpdate(){partialUpdateAllowed=!0,partialUpdateTimeout=null},partialUpdateInterval))},mediaRecorder.onstop=function onstop(){var blob;cleanupPartialUpdateTimeout(),self.cancelled||(blob=new Blob(chunks,{type:mimeType}),self.trigger("blobavailable",[blob])),chunks=[]},mediaRecorder.onerror=function(error){window.console.error(error)}},start:function start(){partialUpdateAllowed=!0,partialSize=0,recordSize=0,mediaRecorder.start(chunkSizeMs)},stop:function stop(){this.cancelled=!1,mediaRecorder.stop()},cancel:function cancel(){this.cancelled=!0,mediaRecorder.stop()},destroy:function destroy(){cleanupPartialUpdateTimeout(),mediaRecorder&&"recording"===mediaRecorder.state&&mediaRecorder.stop(),mediaRecorder=null}},event.addEventMgr(mediaRecorderProvider),mediaRecorderProvider}}),define("audioRecordingInteraction/runtime/js/providers/webAudio",["taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/OAT/promise","taoQtiItem/portableLib/OAT/util/event"],function(_,Promise,event){"use strict";return function webAudioProviderFactory(config,assetManager){function initWorker(){recorderWorker=new Worker(assetManager.resolve("audioRecordingInteraction/runtime/js/workers/WebAudioRecorderWav.js")),sendToWorker("init",{config:{numChannels:numChannels,sampleRate:getAudioContext().sampleRate,updateResponsePartially:updateResponsePartially,partialUpdateInterval:partialUpdateInterval},options:{timeLimit:0,progressInterval:1e3,wav:{mimeType:"audio/wav"}}})}function sendToWorker(command,payload){recorderWorker.postMessage(_.merge({command:command},payload))}function getAudioContext(){return window.audioContext}var recorderWorkerPath="audioRecordingInteraction/runtime/js/workers/WebAudioRecorderWav.js",audioNodes={},numChannels=config.isStereo?2:1,buffer=[],updateResponsePartially=config.updateResponsePartially,partialUpdateInterval=config.partialUpdateInterval,webAudioProvider,recorderWorker;return webAudioProvider={init:function init(stream){var self=this;audioNodes.source=getAudioContext().createMediaStreamSource(stream),audioNodes.inputGain=getAudioContext().createGain(),audioNodes.source.connect(audioNodes.inputGain),initWorker(),recorderWorker.onmessage=function(e){var data=e.data,blob;switch(data.command){case"partialcomplete":blob=data.blob,self.trigger("partialblobavailable",[blob]);break;case"complete":{blob=data.blob,self.trigger("blobavailable",[blob]);break}}}},start:function start(){audioNodes.processor=getAudioContext().createScriptProcessor(0,numChannels,numChannels),audioNodes.processor.onaudioprocess=function(e){var ch;for(ch=0;ch<numChannels;++ch)buffer[ch]=e.inputBuffer.getChannelData(ch);sendToWorker("record",{buffer:buffer})},audioNodes.inputGain.connect(audioNodes.processor),audioNodes.processor.connect(getAudioContext().destination),sendToWorker("start",{bufferSize:audioNodes.processor.bufferSize})},_interruptRecording:function _interruptRecording(){audioNodes.processor.onaudioprocess=null,audioNodes.inputGain.disconnect(),delete audioNodes.processor},stop:function stop(){this._interruptRecording(),sendToWorker("finish")},cancel:function cancel(){this._interruptRecording(),sendToWorker("cancel")},destroy:function destroy(){recorderWorker&&(recorderWorker.terminate(),recorderWorker=null),audioNodes={}}},event.addEventMgr(webAudioProvider),webAudioProvider}}),define("audioRecordingInteraction/runtime/js/recorder",["taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/OAT/promise","taoQtiItem/portableLib/OAT/util/event","audioRecordingInteraction/runtime/js/providers/mediaRecorder","audioRecordingInteraction/runtime/js/providers/webAudio"],function(_,Promise,event,mediaRecorderProvider,webAudioProvider){"use strict";function getRndInteger(min,max){return Math.floor(Math.random()*(max-min))+min}function setGetUserMedia(){var promisifiedOldGUM=function promisifiedOldGUM(constraints){var getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;return getUserMedia?new Promise(function(successCallback,errorCallback){getUserMedia.call(navigator,constraints,successCallback,errorCallback)}):Promise.reject(new Error("getUserMedia is not implemented in this browser"))};"undefined"==typeof navigator.mediaDevices&&(navigator.mediaDevices={}),"undefined"==typeof navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=promisifiedOldGUM)}var recorderStates={CREATED:"created",IDLE:"idle",RECORDING:"recording",STOPED:"stoped",CANCELED:"canceled"};return function recorderFactory(config,assetManager){function isIOSDevice(){return /(iPhone|iPad)/i.test(navigator.userAgent)}function fillFakeEmitter(frequencyArray){var frequencyLength=frequencyArray.length,level=0,levelIndex=0;frequencyLength&&(level=getRndInteger(frequencyLength*(frequencyLength/2),frequencyLength*frequencyLength));do frequencyArray[levelIndex++]=level;while(levelIndex<frequencyLength/2)}function initAnalyser(stream){var source,bufferLength;source=audioContext.createMediaStreamSource(stream),analyser=audioContext.createAnalyser(),analyser.minDecibels=-100,analyser.maxDecibels=-30,analyser.fftSize=32,source.connect(analyser),bufferLength=analyser.frequencyBinCount,frequencyArray=new Uint8Array(bufferLength)}function getInputLevel(){var sum;return analyser.getByteFrequencyData(frequencyArray),frequencyArray.length&&isIOSDevice()&&fillFakeEmitter(frequencyArray),sum=frequencyArray.reduce(function(a,b){return a+b}),Math.floor(sum/frequencyArray.length)}function setState(recorderInstance,newState){state=newState,recorderInstance.trigger("statechange"),recorderInstance.trigger(newState)}var state=recorderStates.CREATED,recorder,mediaStream,provider,startTimeMs,durationMs,timerId,audioContext,analyser,frequencyArray;return setGetUserMedia(),recorder={is:function is(queriedState){return state===queriedState},isNeedInit:function isNeedInit(){return this.is(recorderStates.CREATED)||this.is(recorderStates.STOPED)||this.is(recorderStates.CANCELED)},init:function init(){var self=this;return provider=config.isCompressed?mediaRecorderProvider(config):webAudioProvider(config,assetManager),this.initAudioContext(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(stream){mediaStream=stream,provider.init(stream),provider.on("blobavailable",function(blob){self.trigger("recordingavailable",[blob,durationMs]),self.releaseResourses()}),provider.on("partialblobavailable",function(blob){self.trigger("partialrecordingavailable",[blob])}),initAnalyser(stream),setState(recorder,recorderStates.IDLE)})},initAudioContext:function initAudioContext(){var context=window.audioContext;return audioContext=context?context:new(window.AudioContext||window.webkitAudioContext),window.audioContext=audioContext,audioContext},start:function start(){startTimeMs=new window.Date().getTime(),provider.start(),setState(recorder,recorderStates.RECORDING),this._monitorRecording()},stop:function stop(){durationMs=new window.Date().getTime()-startTimeMs,this._interruptRecording(),provider.stop(),setState(recorder,recorderStates.STOPED),this.trigger("stop")},cancel:function cancel(){this._interruptRecording(),provider.cancel(),setState(recorder,recorderStates.CANCELED),this.releaseResourses(),this.trigger("cancel")},releaseResourses:function releaseResourses(){mediaStream&&_.forEach(mediaStream.getTracks(),function(track){track.stop()}),audioContext.close().then(function(){audioContext=null}),window.audioContext=null,provider.destroy(),provider=null},_interruptRecording:function _interruptRecording(){cancelAnimationFrame(timerId),setState(recorder,recorderStates.IDLE),this.trigger("levelUpdate",[0])},_monitorRecording:function _monitorRecording(){var nowMs=new window.Date().getTime(),elapsedSeconds=(nowMs-startTimeMs)/1e3;timerId=requestAnimationFrame(this._monitorRecording.bind(this)),this.trigger("timeupdate",[elapsedSeconds]),this.trigger("levelUpdate",[getInputLevel()]),0<config.maxRecordingTime&&elapsedSeconds>=config.maxRecordingTime&&(this.trigger("timeout"),this.stop())},destroy:function destroy(){var promises=[cancelAnimationFrame(timerId)];return provider&&promises.push(provider.destroy()),Promise.all(promises)}},event.addEventMgr(recorder),recorder}}),define("taoQtiItem/portableLib/OAT/mediaPlayer",["taoQtiItem/portableLib/jquery_2_1_1","taoQtiItem/portableLib/lodash","core/promise","ui/mediaplayer"],function($,_,Promise,mediaplayer){"use strict";var defaults={type:"video/mp4",video:{width:480,height:270},audio:{width:400,height:30}},canBePlayed=function canBePlayed(timesPlayed,maxPlays){return 0===maxPlays||maxPlays>timesPlayed},resize=_.debounce(function resize(mediaElement,$container,maxWidth){var newWidth,newHeight;mediaElement&&(newHeight=$container.height(),newWidth=$container.width(),newWidth=maxWidth&&newWidth>maxWidth?maxWidth:newWidth,mediaElement.resize(newWidth,newHeight))},200);return function mediaPlayerFactory(options){var $container=options.$container,timesPlayed=0,url=options.url||"",type=options.type||defaults.type,width=options.width||defaults.video.width,height=options.height||defaults.video.height,autostart=!!options.autostart,pause=!!options.pause,loop=!!options.loop,maxPlays=options.maxPlays||0,replayTimeout=options.replayTimeout||0,mediaElement;return{getMediaElement:function getMediaElement(){return mediaElement},render:function render(){var self=this;return new Promise(function(resolve){mediaElement||(mediaElement=mediaplayer({url:url,type:type,canPause:pause,maxPlays:maxPlays,replayTimeout:replayTimeout,width:width,height:height,volume:100,autoStart:autostart&&canBePlayed(timesPlayed,maxPlays),loop:loop,renderTo:$container,_debugMode:!1}).on("render",function(){resize(mediaElement,$container,width),$(window).off("resize.pciMediaPlayer").on("resize.pciMediaPlayer",function(){resize(mediaElement,$container,width)}),resolve()}).on("ready",function(){$container.trigger("playerready")}).on("ended",function(){timesPlayed++,canBePlayed(timesPlayed,maxPlays)||this.disable()}),self.element=mediaElement)})},destroy:function destroy(){mediaElement&&(mediaElement.destroy(),mediaElement=null),$(window).off("resize.pciMediaPlayer")}}}}),define("audioRecordingInteraction/runtime/js/uiElements",["taoQtiItem/portableLib/jquery_2_1_1","taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/OAT/util/event","taoQtiItem/portableLib/OAT/mediaPlayer"],function($,_,event,mediaPlayerFactory){"use strict";function controlFactory(config){function setState(newState){$control.removeClass(state),state=newState,$control.addClass(state)}var $control=$("<button>",{class:"audiorec-control","data-identifier":config.id,html:config.label}),state,control;return $control.appendTo(config.container),setState(config.defaultState||controlStates.DISABLED),control={is:function is(queriedState){return state===queriedState},enable:function enable(){setState(controlStates.ENABLED)},disable:function disable(){setState(controlStates.DISABLED)},activate:function activate(){setState(controlStates.ACTIVE)},getState:function getState(){return state},setState:setState,updateState:function updateState(){this.trigger("updatestate")},updateLabel:function updateLabel(label){$control.html(label)},destroy:function destroy(){$control.off(".audioPCI"),$control.remove(),$control=null}},event.addEventMgr(control),$control.on("click.audioPCI",function(){control.trigger("click")}),control}function progressBarFactory($container,config){var $progressBar=$("<progress>",{value:"0"}),progressBar,currentClass;return progressBar={setMax:function setMax(max){$progressBar.attr("max",max)},setValue:function setValue(value){$progressBar.attr("value",value),$progressBar.text(value)},setStyle:function setStyle(className){$progressBar.removeClass(currentClass),currentClass=className,$progressBar.addClass(currentClass)},reset:function reset(){this.setValue(0),this.setStyle(""),config.maxRecordingTime&&this.setMax(config.maxRecordingTime)}},$container.empty(),$container.append($progressBar),progressBar}function inputMeterFactory(config){function drawLed(index,color){var x=0,y=3*(ledNumbers-(index+1));canvasCtx.fillStyle=color,canvasCtx.fillRect(0,y,10,3)}var grey="#cccccc",green="#00aa00",orange="#ff9300",red="#ff0000",ledHeight=3,ledWidth=10,ledPadding=0,ledColors=[green,green,green,green,green,green,orange,orange,orange,orange,red,red,red],ledNumbers=ledColors.length,width=ledWidth,height=ledHeight*ledNumbers+ledPadding*(ledNumbers-1),inputMeter,canvas,canvasCtx,scaledLevel;return canvas=document.createElement("canvas"),canvas.height=height,canvas.width=width,config.$container.empty(),config.$container.append($(canvas)),canvasCtx=canvas.getContext("2d"),inputMeter={draw:function draw(level){var currentColor,i;for(scaledLevel=Math.floor(level/config.maxLevel*height),i=0;i<ledNumbers;i+=1)currentColor=grey,(0===i&&0<scaledLevel||scaledLevel>config.maxLevel/ledNumbers*i)&&(currentColor=ledColors[i]),drawLed(i,currentColor)},destroy:function destroy(){canvasCtx=null,canvas=null,config.$container.empty()}},inputMeter.draw(0),inputMeter}function mediaStimulusFactory(config){var $container=config.$container,assetManager=config.assetManager,media=config.media||{},state=mediaStimulusStates.CREATED,mediaStimulus,mediaPlayer,mediaPlayerOptions,mediaElement;return mediaStimulus={setState:function setState(newState){state=newState,this.trigger("statechange"),this.trigger(state)},is:function is(queriedState){return state===queriedState},render:function render(){var self=this;$container.empty(),mediaPlayer&&mediaPlayer.destroy(),media.uri&&(mediaPlayerOptions=_.assign({},media,{$container:$container,url:assetManager.resolve(media.uri)}),mediaPlayer=mediaPlayerFactory(mediaPlayerOptions),mediaPlayer.render(),mediaElement=mediaPlayer.getMediaElement(),mediaElement&&mediaElement.on("ready pause stop",function(){self.setState(mediaStimulusStates.IDLE)}).on("play",function(){self.setState(mediaStimulusStates.PLAYING)}).on("ended",function(){self.setState(mediaStimulusStates.ENDED)}).on("disabled",function(){self.setState(mediaStimulusStates.DISABLED)}))},destroy:function destroy(){mediaPlayer.destroy(),$container.empty()}},event.addEventMgr(mediaStimulus),mediaStimulus}function countdownPieChartFactory(config){var $container=config.$container,delay=config.delayInSeconds-1,$countdownPieChart=$("<div class=\"countdown-pie-container countdown-pie-animated\"><div class=\"countdown-pie-circle\"><div class=\"countdown-pie countdown-pie-spinner countdown-pie-animated\"></div><div class=\"countdown-pie countdown-pie-filler countdown-pie-animated\"></div><div class=\"countdown-pie-mask countdown-pie-animated\"></div></div></div>"),displayed=!0,countdownPieChart;return countdownPieChart={isDisplayed:function isDisplayed(){return displayed},start:function start(){$countdownPieChart.css("animation-play-state","running"),$countdownPieChart.find(".countdown-pie-animated").css("animation-play-state","running")},destroy:function destroy(){displayed=!1,$container.empty()}},$countdownPieChart.css("animation-duration",delay+"s"),$countdownPieChart.find(".countdown-pie-animated").css("animation-duration",delay+"s"),$container.empty(),$container.append($countdownPieChart),countdownPieChart}var controlStates={DISABLED:"disabled",ENABLED:"enabled",ACTIVE:"active"},mediaStimulusStates={CREATED:"created",IDLE:"idle",PLAYING:"playing",ENDED:"ended",DISABLED:"disabled"};return{controlFactory:controlFactory,progressBarFactory:progressBarFactory,inputMeterFactory:inputMeterFactory,mediaStimulusFactory:mediaStimulusFactory,countdownPieChartFactory:countdownPieChartFactory}}),define("text!audioRecordingInteraction/runtime/img/mic.svg",[],function(){return"<svg xmlns:svg=\"http://www.w3.org/2000/svg\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 16 16\">\n <path d=\"M7.5 11c1.381 0 2.5-1.119 2.5-2.5v-6c0-1.381-1.119-2.5-2.5-2.5s-2.5 1.119-2.5 2.5v6c0 1.381 1.119 2.5 2.5 2.5zM11 7v1.5c0 1.933-1.567 3.5-3.5 3.5s-3.5-1.567-3.5-3.5v-1.5h-1v1.5c0 2.316 1.75 4.223 4 4.472v2.028h-2v1h5v-1h-2v-2.028c2.25-0.249 4-2.156 4-4.472v-1.5h-1z\"/>\n</svg>\n"}),define("audioRecordingInteraction/runtime/audioRecordingInteraction",["qtiCustomInteractionContext","taoQtiItem/portableLib/jquery_2_1_1","taoQtiItem/portableLib/lodash","taoQtiItem/portableLib/OAT/promise","taoQtiItem/portableLib/OAT/util/event","taoQtiItem/portableLib/OAT/util/html","audioRecordingInteraction/runtime/js/player","audioRecordingInteraction/runtime/js/recorder","audioRecordingInteraction/runtime/js/uiElements","text!audioRecordingInteraction/runtime/img/mic.svg"],function(qtiCustomInteractionContext,$,_,Promise,event,html,playerFactory,recorderFactory,uiElements,micIcon){"use strict";function toBoolean(value,defaultValue){return"undefined"==typeof value||""===value?defaultValue:!0===value||"true"===value}function toInteger(value,defaultValue){return"undefined"==typeof value||""===value?defaultValue:parseInt(value,10)}function getFileName(filePrefix,blob){return filePrefix+"_"+window.Date.now()+"."+blob.type.split(";")[0].split("/")[1]}var ICON_CONTROLS="audioRecordingInteraction/runtime/img/controls.svg",audioRecordingInteraction;audioRecordingInteraction={_filePrefix:"audioRecording",_recording:null,_recordsAttempts:0,_isAutoPlayingBack:!1,_delayCallback:null,inQtiCreator:function inQtiCreator(){return _.isUndefined(this._inQtiCreator)&&this.$container&&(this._inQtiCreator=this.$container.hasClass("tao-qti-creator-context")),this._inQtiCreator},_cleanDelayCallback:function _cleanDelayCallback(){this._delayCallback&&(clearTimeout(this._delayCallback),this._delayCallback=null)},getDelayInSeconds:function getDelayInSeconds(){return 60*this.config.delayMinutes+this.config.delaySeconds},render:function render(config){this.$mediaStimulusContainer=this.$container.find(".audio-rec > .media-stimulus"),this.$controlsContainer=this.$container.find(".audio-rec > .controls"),this.$progressContainer=this.$container.find(".audio-rec > .progress"),this.$meterContainer=this.$container.find(".audio-rec > .input-meter"),this._recording=null,this._recordsAttempts=0,this.config={},this.controls={},this.iconsFileUrl=this.assetManager.resolve("audioRecordingInteraction/runtime/img/controls.svg"),this.initConfig(config),this.initRecorder(),this.initPlayer(),this.initProgressBar(),this.initMeter(),this.initMediaStimulus(),this.initControls(),this.updateResetCount(),this.initRecording()},initConfig:function init(config){this.config={isReviewMode:toBoolean(config.isReviewMode,!1),allowPlayback:toBoolean(config.allowPlayback,!0),autoStart:toBoolean(config.autoStart,!1),autoPlayback:toBoolean(config.autoPlayback,!1),delaySeconds:toInteger(config.delaySeconds,0),delayMinutes:toInteger(config.delayMinutes,0),maxRecords:toInteger(config.maxRecords,3),maxRecordingTime:toInteger(config.maxRecordingTime,120),isCompressed:toBoolean(config.isCompressed,!0),audioBitrate:toInteger(config.audioBitrate,2e4),isStereo:toBoolean(config.isStereo,!1),useMediaStimulus:toBoolean(config.useMediaStimulus,!1),media:config.media||{},displayDownloadLink:toBoolean(config.displayDownloadLink,!1),updateResponsePartially:toBoolean(config.updateResponsePartially,!0),partialUpdateInterval:toInteger(config.partialUpdateInterval,1e3)}},initRecorder:function initRecorder(){var self=this;this.recorder=recorderFactory(this.config,this.assetManager),this.recorder.on("cancel",function(){self.progressBar.reset(),self.$meterContainer.removeClass("record")}),this.recorder.on("recordingavailable",function(blob,durationMs){var recordingUrl=window.URL&&window.URL.createObjectURL&&window.URL.createObjectURL(blob),filename=getFileName(self._filePrefix,blob),filesize=blob.size;self.getBase64Recoding(blob,filename).then(function(recording){self._recordsAttempts++,self.updateResponse(recording);self.progressBar&&self.player&&(self.progressBar.reset(),self.$meterContainer.removeClass("record"),self.player.unload(),self.config.autoPlayback&&self.player.on("oncanplay",function(){self.player.off("oncanplay"),self._isAutoPlayingBack=!0,self.playRecording()}),self.player.loadFromBase64(recording.data,recording.mime),self.displayDownloadLink(recordingUrl,filename,filesize,durationMs))}).catch(function(){self.resetRecording()})}),this.recorder.on("partialrecordingavailable",function(blob){var filename=getFileName(self._filePrefix,blob);self.getBase64Recoding(blob,filename).then(function(recording){self.updateResponse(recording)}).catch(function(){self.resetRecording()})}),this.recorder.on("statechange",function(){self.updateControls()}),this.recorder.on("timeupdate",function(currentTime){self.progressBar.setValue(currentTime)}),this.recorder.on("levelUpdate",function(level){self.inputMeter.draw(level)})},initPlayer:function initPlayer(){var self=this;this.player=playerFactory(),this.player.on("statechange",function(){self.updateControls()}),this.player.on("playbackend",function(){self.progressBar.setStyle(""),self._isAutoPlayingBack=!1}),this.player.on("timeupdate",function(currentTime){self.progressBar.setValue(currentTime)}),this.player.on("durationchange",function(durationSeconds){self.progressBar.setMax(durationSeconds)})},initProgressBar:function initProgressBar(){this.progressBar=uiElements.progressBarFactory(this.$progressContainer,this.config)},initMeter:function initMeter(){var $micIcon=this.$meterContainer.find(".mic");$micIcon.empty(),$micIcon.append(micIcon),this.inputMeter=uiElements.inputMeterFactory({$container:this.$meterContainer.find(".leds"),maxLevel:100})},initRecording:function initRecording(){var delayInSeconds=this.getDelayInSeconds(),self=this;if(this.ctrCache={},!0===this.config.autoStart&&!0!==this.config.isReviewMode){if(0===delayInSeconds&&!this.hasMediaStimulus()&&!this.inQtiCreator())return void this.startRecording();_.forEach(this.controls,function(ctr,id){self.ctrCache[id]=ctr.getState(),ctr.disable()}),0<delayInSeconds&&!this.inQtiCreator()&&this.initCountdown(),this.hasMediaStimulus()||!this.inQtiCreator()&&this.initDelay()}},initDelay:function initDelay(){var self=this;this._cleanDelayCallback(),this.askPermissionAccessMic(function(){self.countdown.start(),self._delayCallback=setTimeout(function(){self.countdown.destroy(),_.forEach(self.controls,function(ctr,id){ctr.setState(self.ctrCache[id])}),self._cleanDelayCallback(),!self.hasMediaStimulus()||self.hasMediaStimulus()&&self.mediaStimulusHasPlayed()?self.startRecording():self.updateControls()},1e3*self.getDelayInSeconds())})},initMediaStimulus:function initMediaStimulus(){var self=this;this.hasMediaStimulus()?(this.$mediaStimulusContainer.addClass("active"),this.mediaStimulus=uiElements.mediaStimulusFactory({$container:this.$mediaStimulusContainer,assetManager:this.assetManager,media:this.config.media}),this.mediaStimulus.on("statechange",function(){self.updateControls()}),this.mediaStimulus.on("playing",function(){self.recorder.is("recording")&&self.recorder.cancel(),self.player.is("playing")&&self.player.stop()}),this.mediaStimulus.on("ended",function(){self.config.autoStart&&!self.config.isReviewMode&&(self.config.delayMinutes||self.config.delaySeconds?self.countdown&&self.countdown.isDisplayed()&&self.initDelay():self.startRecording())}),this.mediaStimulus.render()):(this.$mediaStimulusContainer.empty(),this.$mediaStimulusContainer.removeClass("active"))},initCountdown:function initCountdown(){!0===this.config.autoStart&&(this.countdown=uiElements.countdownPieChartFactory({$container:this.$meterContainer.find(".countdown-pie-chart"),delayInSeconds:this.getDelayInSeconds()}))},hasMediaStimulus:function hasMediaStimulus(){return this.config.useMediaStimulus&&this.config.media&&this.config.media.uri},mediaStimulusHasPlayed:function mediaStimulusHasPlayed(){return this.mediaStimulus&&(this.mediaStimulus.is("ended")||this.mediaStimulus.is("disabled"))},askPermissionAccessMic:function askPermissionAccessMic(callback){this.recorder&&this.recorder.is("created")&&this.recorder.init().then(function(){callback()}).catch(function(err){console.error(err)}),this.recorder&&this.recorder.is("idle")&&callback()},startRecording:function startRecording(){function startForReal(){self.resetRecording(),self.recorder.start(),self.config.maxRecordingTime&&(self.$meterContainer.addClass("record"),self.progressBar.setStyle("record"),self.progressBar.setMax(self.config.maxRecordingTime)),self.updateControls()}var self=this;this.recorder.isNeedInit()?this.recorder.init().then(function(){startForReal()}).catch(function(err){console.error(err)}):startForReal()},stopRecording:function stopRecording(){this.recorder.stop(),this.updateControls()},stopPlayback:function stopPlayback(){this.player.stop(),this.updateControls()},setRecording:function setRecording(data){this._recording=data},getRecording:function getRecording(){return this._recording},playRecording:function playRecording(){this.player.play(),this.progressBar.setStyle("playback"),this.updateControls()},pausePlayback:function pausePlayback(){this.player.pause(),this.updateControls()},resetRecording:function resetRecording(){this.player.unload(),this.updateResponse(null),this.updateControls(),this.progressBar.reset(),this.$meterContainer.removeClass("record"),this.recorder.is("recording")&&this.recorder.cancel()},getBase64Recoding:function getBase64Recoding(blob,filename){return new Promise(function(resolve){var reader=new FileReader;reader.readAsDataURL(blob),reader.onloadend=function onLoadEnd(e){var base64Raw=e.target.result,commaPosition=base64Raw.indexOf(","),base64Data=base64Raw.substring(commaPosition+1),recording={mime:blob.type,name:filename,data:base64Data};resolve(recording)}})},updateResponse:function updateResponse(recording){this.setRecording(recording),"function"==typeof this.trigger&&this.trigger("responseChange")},updateResetCount:function updateResetCount(){var remaining=this.config.maxRecords-this._recordsAttempts-1,resetLabel=this.getControlIcon("reset");1<this.config.maxRecords&&(resetLabel+=" ("+remaining+")"),this.controls.reset&&this.controls.reset.updateLabel(resetLabel)},displayDownloadLink:function displayDownloadLink(url,filename,filesize,durationMs){var downloadLink;!0===this.config.displayDownloadLink&&(downloadLink=document.createElement("a"),document.body.appendChild(downloadLink),document.body.appendChild(document.createElement("br")),downloadLink.text="download "+this._recordsAttempts+" - "+Math.round(filesize/1e3)+"KB - "+Math.round(durationMs/1e3)+"s",downloadLink.download=filename,downloadLink.href=url)},initControls:function initControls(){var self=this,record,stop,play,reset;this.$controlsContainer.empty(),this.controls={},!0!==this.config.isReviewMode&&(record=uiElements.controlFactory({id:"record",label:this.getControlIcon("record"),container:this.$controlsContainer}),record.on("click",function(){this.is("enabled")&&self.startRecording()}.bind(record)),record.on("updatestate",function(){self.player.is("created")&&!self.recorder.is("recording")&&(self.hasMediaStimulus()&&self.mediaStimulusHasPlayed()||!self.hasMediaStimulus())&&!self.getRecording()?this.enable():this.disable()}.bind(record)),this.controls.record=record),stop=uiElements.controlFactory({id:"stop",label:this.getControlIcon("stop"),container:this.$controlsContainer}),stop.on("click",function(){this.is("enabled")&&(self.recorder.is("recording")?self.stopRecording():self.player.is("playing")&&self.stopPlayback())}.bind(stop)),stop.on("updatestate",function(){self.player.is("playing")&&!self._isAutoPlayingBack||self.recorder.is("recording")?this.enable():this.disable()}.bind(stop)),this.controls.stop=stop,(!0===this.config.allowPlayback||!0===this.config.isReviewMode)&&(play=uiElements.controlFactory({id:"play",label:this.getControlIcon("play"),container:this.$controlsContainer}),play.on("click",function(){this.is("enabled")&&self.playRecording()}.bind(play)),play.on("updatestate",function(){self.player.is("idle")||self.getRecording()&&!self._isAutoPlayingBack?this.enable():this.disable()}.bind(play)),this.controls.play=play),1!==this.config.maxRecords&&!0!==this.config.isReviewMode&&(reset=uiElements.controlFactory({id:"reset",label:this.getControlIcon("reset"),container:this.$controlsContainer}),reset.on("click",function(){this.is("enabled")&&(self.resetRecording(),self.updateResetCount())}.bind(reset)),reset.on("updatestate",function(){1<self.config.maxRecords&&self.config.maxRecords===self._recordsAttempts?this.disable():self.player.is("idle")?this.enable():this.disable()}.bind(reset)),this.controls.reset=reset),self.updateControls()},updateControls:function updateControls(){this._delayCallback||this.countdown&&this.countdown.isDisplayed()||_.invoke(this.controls,"updateState")},destroyControls:function destroyControls(){_.invoke(this.controls,"destroy"),this.controls=null},getControlIcon:function getControlIcon(iconId){return"<svg title=\""+iconId+"\"><use xlink:href=\""+this.iconsFileUrl+"#"+iconId+"\"/></svg>"},id:-1,getTypeIdentifier:function getTypeIdentifier(){return"audioRecordingInteraction"},initialize:function initialize(id,dom,config,assetManager){var self=this;event.addEventMgr(this),this.id=id,this.assetManager=assetManager,this.$container=$(dom),this.render(config),qtiCustomInteractionContext.notifyReady(this),this.on("configChange",function(newConfig){self.render(newConfig)}),html.render(this.$container.find(".prompt"))},setResponse:function setResponse(response){var recording=response.base&&response.base.file;recording&&(this.updateResponse(recording),this.player.loadFromBase64(recording.data,recording.mime))},getResponse:function getResponse(){var response=null;return this.getRecording()&&(response={file:this.getRecording()}),{base:response}},resetResponse:function resetResponse(){this.updateResponse(null)},destroy:function destroy(){var self=this,promises=[];return self.recorder&&self.recorder.is("recording")&&promises.push(self.stopRecording()),self.player&&self.player.is("playing")&&promises.push(self.stopPlayback()),promises.push(self.destroyControls()),self.inputMeter&&promises.push(self.inputMeter.destroy()),self.mediaStimulus&&promises.push(self.mediaStimulus.destroy()),self.player&&promises.push(self.player.unload()),self.recorder&&promises.push(self.recorder.destroy()),promises.push(self.resetResponse()),self._cleanDelayCallback(),Promise.all(promises).then(function(){self.inputMeter=null,self.progressBar=null,self.mediaStimulus=null,self.player=null,self.recorder=null})},setSerializedState:function setSerializedState(state){this.setResponse(state&&state.response||state)},getSerializedState:function getSerializedState(){return this.getResponse()}},qtiCustomInteractionContext.register(audioRecordingInteraction)}),define(["audioRecordingInteraction/runtime/audioRecordingInteraction"],function(PCI){return PCI});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Handlebars is not defined before the compiled template requires it. It will fail at runtime. See for example:

define("tpl!audioRecordingInteraction/runtime/js/dialog/tpl/body",["taoQtiItem/portableLib/handlebars_4"],function(hb){
...
});

@oatymart oatymart marked this pull request as draft June 7, 2024 08:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants