<commit_before>!function(e){var t={};function o(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,o),r.l=!0,r.exports}o.m=e,o.c=t,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0)}([function(e,t,o){!function(){"use strict";var e=["C","C#","D","Eb","E","F","F#","G","G#","A","Bb","B"],t=new(o(1))(1024),n=new THREE.Scene,r=new THREE.PerspectiveCamera(40,1.6,.1,1e3),i=new THREE.LineBasicMaterial({color:65280}),a=(new THREE.LineBasicMaterial({color:65535}),function(e,t){for(var o=[],n=0;n<e;n++)o.push(Array.apply(null,Array(t)).map(Number.prototype.valueOf,0));return o}(20,1024)),c=new THREE.WebGLRenderer({canvas:document.querySelector("canvas")});function d(){c.domElement.style.width="100%",c.domElement.style.height="auto";var e=c.domElement.clientWidth/16*10;c.setPixelRatio(window.devicePixelRatio?window.devicePixelRatio:1),c.setSize(1.6*e,e),c.domElement.style.width="100%",c.domElement.style.height="auto",r.aspect=1.6*e/e,r.updateProjectionMatrix()}d(),window.addEventListener("resize",d);var s=new THREE.DirectionalLight(16777215,.5);s.position.set(0,1,1),n.add(s),r.position.z=5;var u=new THREE.Vector3(0,1,0),l=new THREE.Vector3(1,0,0),p=new THREE.Vector3(1,-6,-15),f=new THREE.ArrowHelper(u,p,1,16776960),m=new THREE.ArrowHelper(u,p,1,255),y=new THREE.ArrowHelper(l,p,1,16711935),g=new THREE.Group;n.add(f),n.add(m),n.add(y);for(var w=0;w<a.length;w++)if(a[w]){var v=new THREE.BufferGeometry,E=new Float32Array(3*a[w].length);v.addAttribute("position",new THREE.BufferAttribute(E,3)),v.setDrawRange(0,a[w].length);var h=new THREE.Line(v,i);g.add(h),E=h.geometry.attributes.position.array}var b=new THREE.BufferGeometry,M=new THREE.Line(b,i),x=new Float32Array(3072);b.addAttribute("position",new THREE.BufferAttribute(x,3)),b.setDrawRange(0,1024),x=M.geometry.attributes.position.array,n.add(M),n.add(g);var R=null,S=document.querySelector("#chroma"),A=document.querySelector("#mfcc");!function o(){if(R=t.get(["amplitudeSpectrum","spectralCentroid","spectralRolloff","loudness","rms","chroma","mfcc"])){S&&R.chroma&&(S.innerHTML=R.chroma.reduce((function(t,o,n){return"".concat(t,'\n
').concat(e[n],"
")}),"")),A&&R.mfcc&&(A.innerHTML=R.mfcc.reduce((function(e,t,o){return"".concat(e,'\n
').concat(o,"
")}),"")),a.pop(),a.unshift(R.amplitudeSpectrum);for(var i=t.meyda._m.signal,d=0;d<a.length;d++){for(var s=g.children[d].geometry.attributes.position.array,u=0,l=0;l<3*a[d].length;l++)s[u++]=10.7+8*Math.log10(l/a[d].length),s[u++]=.1*a[d][l]-5,s[u++]=-15-d;g.children[d].geometry.attributes.position.needsUpdate=!0}if(R.spectralCentroid&&f.position.set(10.7+8*Math.log10(R.spectralCentroid/512),-6,-15),R.spectralRolloff){var p=R.spectralRolloff/22050;m.position.set(10.7+8*Math.log10(p),-6,-15)}if(R.rms&&y.position.set(-11,10*R.rms-5,-15),i){for(var w=M.geometry.attributes.position.array,v=0,E=0;E<1024;E++)w[v++]=22*E/1024-11,w[v++]=4+5*i[E],w[v++]=-25;M.geometry.attributes.position.needsUpdate=!0}}requestAnimationFrame(o),c.render(n,r)}()}()},function(e,t){var o,n;(n=function(e){window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=webkitAudioContext),navigator.hasOwnProperty("webkitGetUserMedia")&&!navigator.hasOwnProperty("getUserMedia")&&(navigator.getUserMedia=webkitGetUserMedia,AudioContext.prototype.hasOwnProperty("createScriptProcessor")||(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode)),this.context=new AudioContext;var t=document.getElementById("elvisSong"),n=this.context.createMediaElementSource(t);n.connect(this.context.destination),this.meyda=Meyda.createMeydaAnalyzer({audioContext:this.context,source:n,bufferSize:e,windowingFunction:"blackman"}),o=this,this.initializeMicrophoneSampling()}).prototype.initializeMicrophoneSampling=function(){var e=function(e){"suspended"===o.context.state&&document.body.addEventListener("touchend",(function e(){o.context.resume(),setTimeout((function(){"running"===o.context.state&&document.body.removeEventListener("touchend",e,!1)}),0)}),!1)};try{navigator.getUserMedia=navigator.webkitGetUserMedia||navigator.getUserMedia||navigator.mediaDevices.getUserMedia;var t=function(e){document.getElementById("audioControl").style.display="none",console.log("User allowed microphone access."),console.log("Initializing AudioNode from MediaStream");var t=o.context.createMediaStreamSource(e);console.log("Setting Meyda Source to Microphone"),o.meyda.setSource(t),console.groupEnd()};console.log("Asking for permission..."),navigator.getUserMedia({video:!1,audio:!0},t,e)&&(p.then(t),p.catch(e))}catch(t){e()}},n.prototype.get=function(e){return o.context.resume(),o.meyda.get(e)},e.exports=n}]);<commit_msg>docs(formatting): run prettier on audio.js<commit_after>!function(){var e={909:function(e){var t,o;(o=function(e){window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=webkitAudioContext),navigator.hasOwnProperty("webkitGetUserMedia")&&!navigator.hasOwnProperty("getUserMedia")&&(navigator.getUserMedia=webkitGetUserMedia,AudioContext.prototype.hasOwnProperty("createScriptProcessor")||(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode)),this.context=new AudioContext;var o=document.getElementById("elvisSong"),r=this.context.createMediaElementSource(o);r.connect(this.context.destination),this.meyda=Meyda.createMeydaAnalyzer({audioContext:this.context,source:r,bufferSize:e,windowingFunction:"blackman"}),t=this,this.initializeMicrophoneSampling()}).prototype.initializeMicrophoneSampling=function(){var e=function(e){"suspended"===t.context.state&&document.body.addEventListener("touchend",(function e(){t.context.resume(),setTimeout((function(){"running"===t.context.state&&document.body.removeEventListener("touchend",e,!1)}),0)}),!1)};try{navigator.getUserMedia=navigator.webkitGetUserMedia||navigator.getUserMedia||navigator.mediaDevices.getUserMedia;var o=function(e){document.getElementById("audioControl").style.display="none",console.log("User allowed microphone access."),console.log("Initializing AudioNode from MediaStream");var o=t.context.createMediaStreamSource(e);console.log("Setting Meyda Source to Microphone"),t.meyda.setSource(o),console.groupEnd()};console.log("Asking for permission..."),navigator.getUserMedia({video:!1,audio:!0},o,e)&&(p.then(o),p.catch(e))}catch(t){e()}},o.prototype.get=function(e){return t.context.resume(),t.meyda.get(e)},e.exports=o}},t={};function o(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,o),i.exports}!function(){"use strict";var e=["C","C#","D","Eb","E","F","F#","G","G#","A","Bb","B"],t=1024,r=new(o(909))(t),n=new THREE.Scene,i=new THREE.PerspectiveCamera(40,1.6,.1,1e3),a=new THREE.LineBasicMaterial({color:65280}),c=(new THREE.LineBasicMaterial({color:65535}),function(e,t){for(var o=[],r=0;r<20;r++)o.push(Array.apply(null,Array(1024)).map(Number.prototype.valueOf,0));return o}()),d=new THREE.WebGLRenderer({canvas:document.querySelector("canvas")});function s(){d.domElement.style.width="100%",d.domElement.style.height="auto";var e=d.domElement.clientWidth/16*10;d.setPixelRatio(window.devicePixelRatio?window.devicePixelRatio:1),d.setSize(1.6*e,e),d.domElement.style.width="100%",d.domElement.style.height="auto",i.aspect=1.6*e/e,i.updateProjectionMatrix()}s(),window.addEventListener("resize",s);var u=new THREE.DirectionalLight(16777215,.5);u.position.set(0,1,1),n.add(u),i.position.z=5;var l=new THREE.Vector3(0,1,0),p=new THREE.Vector3(1,0,0),m=new THREE.Vector3(1,-6,-15),g=new THREE.ArrowHelper(l,m,1,16776960),w=new THREE.ArrowHelper(l,m,1,255),y=new THREE.ArrowHelper(p,m,1,16711935),E=new THREE.Group;n.add(g),n.add(w),n.add(y);for(var f=0;f<c.length;f++)if(c[f]){var h=new THREE.BufferGeometry,v=new Float32Array(3*c[f].length);h.addAttribute("position",new THREE.BufferAttribute(v,3)),h.setDrawRange(0,c[f].length);var b=new THREE.Line(h,a);E.add(b),v=b.geometry.attributes.position.array}var M=new THREE.BufferGeometry,R=new THREE.Line(M,a),x=new Float32Array(3072);M.addAttribute("position",new THREE.BufferAttribute(x,3)),M.setDrawRange(0,t),x=R.geometry.attributes.position.array,n.add(R),n.add(E);var A=null,H=document.querySelector("#chroma"),T=document.querySelector("#mfcc");!function o(){if(A=r.get(["amplitudeSpectrum","spectralCentroid","spectralRolloff","loudness","rms","chroma","mfcc"])){H&&A.chroma&&(H.innerHTML=A.chroma.reduce((function(t,o,r){return"".concat(t,'\n
').concat(e[r],"
")}),"")),T&&A.mfcc&&(T.innerHTML=A.mfcc.reduce((function(e,t,o){return"".concat(e,'\n
').concat(o,"
")}),"")),c.pop(),c.unshift(A.amplitudeSpectrum);for(var a=r.meyda._m.signal,s=0;s<c.length;s++){for(var u=E.children[s].geometry.attributes.position.array,l=0,p=0;p<3*c[s].length;p++)u[l++]=10.7+8*Math.log10(p/c[s].length),u[l++]=.1*c[s][p]-5,u[l++]=-15-s;E.children[s].geometry.attributes.position.needsUpdate=!0}if(A.spectralCentroid&&g.position.set(10.7+8*Math.log10(A.spectralCentroid/512),-6,-15),A.spectralRolloff){var m=A.spectralRolloff/22050;w.position.set(10.7+8*Math.log10(m),-6,-15)}if(A.rms&&y.position.set(-11,10*A.rms-5,-15),a){for(var f=R.geometry.attributes.position.array,h=0,v=0;v<t;v++)f[h++]=22*v/t-11,f[h++]=4+5*a[v],f[h++]=-25;R.geometry.attributes.position.needsUpdate=!0}}requestAnimationFrame(o),d.render(n,i)}()}()}();<|endoftext|>


<commit_before>// ==UserScript==
// @name         Sesame Better Time UI
// @namespace    https://github.com/danibaena/userscripts/blob/master/userscripts/sesame_better_time_ui.js
// @version      1.0
// @description  Show elapsed time per week and other handy metrics
// @author       danibaena
// @include      https://panel.sesametime.com/admin/users/checks/*
// @grant        none
// @downloadURL  https://raw.githubusercontent.com/danibaena/userscripts/master/userscripts/sesame_better_time_ui.js
// @updateUrl    https://raw.githubusercontent.com/danibaena/userscripts/master/userscripts/sesame_better_time_ui.js
// ==/UserScript==

(function() {
    'use strict';

    const formatMinutesForOutputString = unformattedMinutesInt => {
        const hourTimeString = Math.floor(unformattedMinutesInt / 60).toString();
        const minutesTimeString = (unformattedMinutesInt % 60).toString().padStart(2, 0);
        return `${hourTimeString}:${minutesTimeString}`
    }

    const parseMinutesFromInputString = formattedTimeString => {
        const splittedTimeString = formattedTimeString.split(':');
        const hourTime = parseInt(splittedTimeString[0]) * 60;
        const minutesTime = parseInt(splittedTimeString[1]);
        return (hourTime + minutesTime)
    }

    const totalWeekWorkMinutes = weekDaysMinutes => Object.values(weekDaysMinutes).reduce((accumulated, current) => {
        if(typeof current == 'number') {
            return accumulated + current
        }
        return accumulated
    });

    /* Change the minutes to fit your week work hours (i.e. reduced workweek) */
    const regularWeekDaysMinutes = {'lunes': 525,
                                    'martes': 525,
                                    'miércoles': 525,
                                    'jueves': 525,
                                    'viernes': 360};

    const expectedTotalWorkMinutes = weeklyCheckings => {
        const allowedDays = Object.keys(weeklyCheckings)
        const expectedWorkMinutes = Object.keys(regularWeekDaysMinutes).filter(key => allowedDays.includes(key)).reduce((obj, key) => {
            obj[key] = regularWeekDaysMinutes[key];
            return obj;
        }, {});
        return totalWeekWorkMinutes(expectedWorkMinutes)
    }

    const buildSummary = (missingWorkMinutes, isMonthlySummary, isCurrentDay) => {
        let content = '¡Todo bien!'
        if(missingWorkMinutes > 0) {
            content = `Falta/n ${formatMinutesForOutputString(missingWorkMinutes)} minuto/s`
            if(isCurrentDay) {
                const timeToStop = moment().add(missingWorkMinutes, 'm').format('HH:mm')
                content = `${content}. Deberías parar a las ${timeToStop}`
            }
        }
        if(missingWorkMinutes < 0) {
            content = `Sobra/n ${formatMinutesForOutputString(missingWorkMinutes * (-1))} minuto/s`
        }
        if(isMonthlySummary) {
            content = `${content} este mes`
        }
        const sesameLogo = '';
        return `<li class="margin-top-10 text-right"><strong>${content}</strong> ${missingWorkMinutes ? '' : sesameLogo}</li>`
    }

    const isCurrentWorkingWeek = checkingDayDate => moment().isSame(checkingDayDate, 'week')
    const isCurrentWorkingDay = checkingDayDate => moment().isSame(checkingDayDate, 'day')

    const regularTotalWeekWorkHours = totalWeekWorkMinutes(regularWeekDaysMinutes)
    let weekNumber = 1
    let dailyCheckingsByWeek = {}

    const lastDayOfMonth = moment().endOf('month');
    const checkingTimes = $('.checks-text:not(.red-text)');

    const checkingDays = checkingTimes.parent('.bar').prev().each(function(index) {
        const weekDayText = $(this).text().split(', ')
        const weekDay = weekDayText[0]
        const checkingDayDate = moment(weekDayText[1], 'DD de MMM');
        const checkingTimeElement = $(checkingTimes[index])
        const checkingTimeString = checkingTimeElement.text().split('Horas registradas ')[1]
        const checkingTime = parseMinutesFromInputString(checkingTimeString)

        if(!(weekNumber in dailyCheckingsByWeek)) {
            dailyCheckingsByWeek[weekNumber] = {}
        }
        dailyCheckingsByWeek[weekNumber][weekDay] = checkingTime
        if(weekDay === 'viernes' || moment(checkingDayDate).isSame(lastDayOfMonth, 'day')) {
            const workedWeekMinutes = totalWeekWorkMinutes(dailyCheckingsByWeek[weekNumber])
            const expectedWorkMinutes = expectedTotalWorkMinutes(dailyCheckingsByWeek[weekNumber])
            dailyCheckingsByWeek[weekNumber]['workedWeekMinutes'] = workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['expectedWorkMinutes'] = expectedWorkMinutes
            dailyCheckingsByWeek[weekNumber]['missingWorkMinutes'] = expectedWorkMinutes - workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['last_work_weekday_selector'] = $(this)
            weekNumber++
        }
        if(isCurrentWorkingWeek(checkingDayDate) && isCurrentWorkingDay(checkingDayDate)) {
            const workedWeekMinutes = totalWeekWorkMinutes(dailyCheckingsByWeek[weekNumber])
            const expectedWorkMinutes = expectedTotalWorkMinutes(dailyCheckingsByWeek[weekNumber])
            dailyCheckingsByWeek[weekNumber]['workedWeekMinutes'] = workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['expectedWorkMinutes'] = expectedWorkMinutes
            dailyCheckingsByWeek[weekNumber]['currentMissingWorkMinutes'] = expectedWorkMinutes - workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['current_work_weekday_selector'] = $(this)
        }
    })

    let missingWorkingMinutes = 0;
    for (let [weekNumber, dailyCheckings] of Object.entries(dailyCheckingsByWeek)) {
        if(dailyCheckings.missingWorkMinutes || dailyCheckings.missingWorkMinutes === 0) {
            missingWorkingMinutes += dailyCheckings.missingWorkMinutes;
        }
        if(dailyCheckings.last_work_weekday_selector) {
            const nextBar = dailyCheckings.last_work_weekday_selector.next('.bar')
            nextBar.after(buildSummary(dailyCheckings.missingWorkMinutes))
        }
        if(dailyCheckings.current_work_weekday_selector) {
            const nextBar = dailyCheckings.current_work_weekday_selector.next('.bar')
            nextBar.after(buildSummary(dailyCheckings.currentMissingWorkMinutes + missingWorkingMinutes, false, true))
            missingWorkingMinutes = 0
        }
    }
    const isMonthly = true
    const accumulatedTimeStats = $('.ssm-content-title > small').text().split(' / ')
    const isMonthlyAccumulatedTimeStats = accumulatedTimeStats[0] === accumulatedTimeStats[1]

    if(isMonthlyAccumulatedTimeStats){
        missingWorkingMinutes = 0
    }
    $('.ssm-checks-list-days > ul').last().after(buildSummary(missingWorkingMinutes, isMonthly))
})();
<commit_msg>Update sesame_better_time_ui.js<commit_after>// ==UserScript==
// @name         Sesame Better Time UI
// @namespace    https://github.com/danibaena/userscripts/blob/master/userscripts/sesame_better_time_ui.js
// @version      1.0
// @description  Show elapsed time per week and other handy metrics
// @author       danibaena
// @include      https://panel.sesametime.com/admin/users/checks*
// @grant        none
// @downloadURL  https://raw.githubusercontent.com/danibaena/userscripts/master/userscripts/sesame_better_time_ui.js
// @updateUrl    https://raw.githubusercontent.com/danibaena/userscripts/master/userscripts/sesame_better_time_ui.js
// ==/UserScript==

(function() {
    'use strict';

    const formatMinutesForOutputString = unformattedMinutesInt => {
        const hourTimeString = Math.floor(unformattedMinutesInt / 60).toString();
        const minutesTimeString = (unformattedMinutesInt % 60).toString().padStart(2, 0);
        return `${hourTimeString}:${minutesTimeString}`
    }

    const parseMinutesFromInputString = formattedTimeString => {
        const splittedTimeString = formattedTimeString.split(':');
        const hourTime = parseInt(splittedTimeString[0]) * 60;
        const minutesTime = parseInt(splittedTimeString[1]);
        return (hourTime + minutesTime)
    }

    const totalWeekWorkMinutes = weekDaysMinutes => Object.values(weekDaysMinutes).reduce((accumulated, current) => {
        if(typeof current == 'number') {
            return accumulated + current
        }
        return accumulated
    });

    /* Change the minutes to fit your week work hours (i.e. reduced workweek) */
    const regularWeekDaysMinutes = {'lunes': 525,
                                    'martes': 525,
                                    'miércoles': 525,
                                    'jueves': 525,
                                    'viernes': 360};

    const expectedTotalWorkMinutes = weeklyCheckings => {
        const allowedDays = Object.keys(weeklyCheckings)
        const expectedWorkMinutes = Object.keys(regularWeekDaysMinutes).filter(key => allowedDays.includes(key)).reduce((obj, key) => {
            obj[key] = regularWeekDaysMinutes[key];
            return obj;
        }, {});
        return totalWeekWorkMinutes(expectedWorkMinutes)
    }

    const buildSummary = (missingWorkMinutes, isMonthlySummary, isCurrentDay) => {
        let content = '¡Todo bien!'
        if(missingWorkMinutes > 0) {
            content = `Falta/n ${formatMinutesForOutputString(missingWorkMinutes)} minuto/s`
            if(isCurrentDay) {
                const timeToStop = moment().add(missingWorkMinutes, 'm').format('HH:mm')
                content = `${content}. Deberías parar a las ${timeToStop}`
            }
        }
        if(missingWorkMinutes < 0) {
            content = `Sobra/n ${formatMinutesForOutputString(missingWorkMinutes * (-1))} minuto/s`
        }
        if(isMonthlySummary) {
            content = `${content} este mes`
        }
        const sesameLogo = '';
        return `<li class="margin-top-10 text-right"><strong>${content}</strong> ${missingWorkMinutes ? '' : sesameLogo}</li>`
    }

    const isCurrentWorkingWeek = checkingDayDate => moment().isSame(checkingDayDate, 'week')
    const isCurrentWorkingDay = checkingDayDate => moment().isSame(checkingDayDate, 'day')

    const regularTotalWeekWorkHours = totalWeekWorkMinutes(regularWeekDaysMinutes)
    let weekNumber = 1
    let dailyCheckingsByWeek = {}

    const lastDayOfMonth = moment().endOf('month');
    const checkingTimes = $('.checks-text:not(.red-text)');

    const checkingDays = checkingTimes.parent('.bar').prev().each(function(index) {
        const weekDayText = $(this).text().split(', ')
        const weekDay = weekDayText[0]
        const checkingDayDate = moment(weekDayText[1], 'DD de MMM');
        const checkingTimeElement = $(checkingTimes[index])
        const checkingTimeString = checkingTimeElement.text().split('Horas registradas ')[1]
        const checkingTime = parseMinutesFromInputString(checkingTimeString)

        if(!(weekNumber in dailyCheckingsByWeek)) {
            dailyCheckingsByWeek[weekNumber] = {}
        }
        dailyCheckingsByWeek[weekNumber][weekDay] = checkingTime
        if((weekDay === 'viernes' || moment(checkingDayDate).isSame(lastDayOfMonth, 'day')) && !isCurrentWorkingDay(checkingDayDate)) {
            const workedWeekMinutes = totalWeekWorkMinutes(dailyCheckingsByWeek[weekNumber])
            const expectedWorkMinutes = expectedTotalWorkMinutes(dailyCheckingsByWeek[weekNumber])
            dailyCheckingsByWeek[weekNumber]['workedWeekMinutes'] = workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['expectedWorkMinutes'] = expectedWorkMinutes
            dailyCheckingsByWeek[weekNumber]['missingWorkMinutes'] = expectedWorkMinutes - workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['last_work_weekday_selector'] = $(this)
            weekNumber++
        }

        if(isCurrentWorkingWeek(checkingDayDate) && isCurrentWorkingDay(checkingDayDate)) {
            const workedWeekMinutes = totalWeekWorkMinutes(dailyCheckingsByWeek[weekNumber])
            const expectedWorkMinutes = expectedTotalWorkMinutes(dailyCheckingsByWeek[weekNumber])
            dailyCheckingsByWeek[weekNumber]['workedWeekMinutes'] = workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['expectedWorkMinutes'] = expectedWorkMinutes
            dailyCheckingsByWeek[weekNumber]['currentMissingWorkMinutes'] = expectedWorkMinutes - workedWeekMinutes
            dailyCheckingsByWeek[weekNumber]['current_work_weekday_selector'] = $(this)
        }
    })

    let missingWorkingMinutes = 0;
    for (let [weekNumber, dailyCheckings] of Object.entries(dailyCheckingsByWeek)) {
        if(dailyCheckings.missingWorkMinutes || dailyCheckings.missingWorkMinutes === 0) {
            missingWorkingMinutes += dailyCheckings.missingWorkMinutes;
        }
        if(dailyCheckings.last_work_weekday_selector) {
            const nextBar = dailyCheckings.last_work_weekday_selector.next('.bar')
            nextBar.after(buildSummary(dailyCheckings.missingWorkMinutes))
        }
        if(dailyCheckings.current_work_weekday_selector) {
            const nextBar = dailyCheckings.current_work_weekday_selector.next('.bar')
            nextBar.after(buildSummary(dailyCheckings.currentMissingWorkMinutes + missingWorkingMinutes, false, true))
            missingWorkingMinutes = 0
        }
    }
    const isMonthly = true
    const accumulatedTimeStats = $('.ssm-content-title > small').text().split(' / ')
    const isMonthlyAccumulatedTimeStats = accumulatedTimeStats[0] === accumulatedTimeStats[1]

    if(isMonthlyAccumulatedTimeStats){
        missingWorkingMinutes = 0
    }
    $('.ssm-checks-list-days > ul').last().after(buildSummary(missingWorkingMinutes, isMonthly))
})();
<|endoftext|>


<commit_before><commit_msg>adds module comment.<commit_after><|endoftext|>


<commit_before>define( [
	'jquery',
	'underscore'
], function ( $ /*, _*/ ) {
	'use strict';

	return {

		/**
		 * Add a style to the document's header.
		 * @param cssContent (String)
		 */
		addStyleToHeader: function ( cssContent ) {
			$( "<style>" ).html( cssContent ).appendTo( "head" );
		}

	};

} );
<commit_msg>Added save log, needs some testing<commit_after>define( [
	'jquery',
	'underscore'
], function ( $ /*, _*/ ) {
	'use strict';

	// Taken from http://www.briangrinstead.com/blog/console-log-helper-function
	// Full version of `log` that:
	//  * Prevents errors on console methods when no console present.
	//  * Exposes a global 'log' function that preserves line numbering and formatting.
	(function () {
		var method;
		var noop = function () { };
		var methods = [
			'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
			'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
			'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
			'timeStamp', 'trace', 'warn'
		];
		var length = methods.length;
		var console = (window.console = window.console || {});

		while (length--) {
			method = methods[length];

			// Only stub undefined methods.
			if (!console[method]) {
				console[method] = noop;
			}
		}

		if (Function.prototype.bind) {
			window.log = Function.prototype.bind.call(console.log, console);
		}
		else {
			window.log = function() {
				Function.prototype.apply.call(console.log, console, arguments);
			};
		}
	})();

	return {

		/**
		 * Add a style to the document's header.
		 * @param cssContent (String)
		 */
		addStyleToHeader: function ( cssContent ) {
			$( "<style>" ).html( cssContent ).appendTo( "head" );
		}

	};

} );
<|endoftext|>


<commit_before>/* --------------------------------------------------------------------------- */
// ВЫВОД НА ЭКРАН
    window.SCREEN = {
        Out: function (text, _panel) {
            if (_panel === undefined) {_panel = 'main-output'} // end if
            //----------
            var EL=document.getElementById(_panel);
            //----------
            if (EL!=null) {
                //EL.innerHTML += TYPOGRAPH.text2html(text);
                EL.innerHTML += text;
            };
        }, // end function "Out"
        //----------
        Clear: function (_panel) {
            if (_panel === undefined) {_panel = 'main-output'} // end if
            //----------
            var EL=document.getElementById(_panel);
            //----------
            if (EL!=null) {
                EL.innerHTML='';
            } // end if
        }, // end function "Clear"
    };
/* --------------------------------------------------------------------------- */
// ВЫВОД НА ЭКРАН
    window.INTERFACE = {
        //--------------------------------------------------
        // Обработка нажатия клавиш игроком
        userInput: function (field, event) {
            if (event.which == null) { // IE
                if (event.keyCode == 13) {
                    INTERFACE.ExecuteCMD(field);
                } // end if
            } // end if
            //----------
            if (event.which != 0 && event.charCode != 0) { // все кроме IE
                if (event.which == 13) {
                    INTERFACE.ExecuteCMD(field);
                } // end if
            } // end if
            //----------
            return true; // спец. символ
        }, // end function "userInput"
        //--------------------------------------------------
        preparsing: function (field) {
            //----------
            var command = field.value || '';
            //----------
            if (command.trim() == '') {
                PARSER.pre_parse();
            } else {
                PARSER.parse(command, true);
            } // end if
            //----------
            INTERFACE.checkENTER();
            //----------
            DEBUG.updateWordsFullList();
            DEBUG.updateWordsShortList();
        }, // end function "preparsing"
        //--------------------------------------------------
        // Добавление (остатка) слова к команде игрока
        addWordToCommand: function (_text) {
            var field = document.getElementById('user_command');
            //----------
            if (field == null) {return;}
            //----------
            var value   = field.value;
            var lsymbol = value.substr(-1);
            if (lsymbol == ' ' || lsymbol == '\t') {
                field.value = value + _text + ' ';
            } else {
                var pos = value.lastIndexOf(' ');
                if (pos == -1) {
                    field.value = _text + ' ';
                } else {
                    field.value = value.substr(0, pos)+ ' ' + _text + ' ';
                } // end if
            } // end if
            //----------
            INTERFACE.preparsing(field);
            //----------
            field.focus();
        }, // end function "addWordToCommand"
        //--------------------------------------------------
        checkENTER: function () {
            var field = document.getElementById('user_command');
            if (field == null) {return;}
            //----------
            field.style.color = (AUTOCOMPLETE.getActionFlag() == true) ? "#00F" : "#000";
        }, // end function "addWordToCommand"
        //--------------------------------------------------
        ExecuteCMD: function (field) {
            // Выводим на экран команду игрока
            printCommand(field.value);
            //----------
            // Разбираем команду игрока
            var CMD = PARSER.parse(field.value);
            //----------
            field.value='';
            //----------
            if (CMD.action == null) {
                print('Ничего не понятно.');
            } else {
                // Вызываем событие "Перед выполнением действия с объектом"
                if (EVENTS.checkReactions(EVENTS.ACTION, {'what':CMD.object, 'when':EVENTS.BEFORE}, {'parameter': CMD}) == true) {
                    //----------
                    incProperty('turns.all');
                    incProperty('turns.loc');
                    //----------
                    CMD.action(CMD);
                    //----------
                    // Вызываем событие "После выполнением действия с объектом"
                    EVENTS.checkReactions(EVENTS.ACTION, {'what':CMD.object, 'when':EVENTS.AFTER}, {'parameter': CMD});
                } // end if
            } // end if
            //----------
            AZ.startNewTurn();
        },
        //--------------------------------------------------
    };
/* --------------------------------------------------------------------------- */
// ФУНКЦИИ РАБОТЫ С ЭКРАНОМ
    window.print = function (_text) {
        //----------
        SCREEN.Out(_text);
        //----------
    };
    //--------------------------------------------------
    window.printCommand = function (_text) {
        //----------
        SCREEN.Out(DECOR.Command.print(_text));
        //----------
    };
    //--------------------------------------------------
    window.printDescription = function (_object, _param) {
        var object = AZ.getObject(_object);
        //----------
        // +++ Что делать, если объект для описания не найден
        if (object != null) {
            SCREEN.Out(object.getDescription(_param));
        } // end if
        //----------
    }; // end function "printDescription"
    //--------------------------------------------------
    window.printInventory = function () {
        //----------
        SCREEN.Out(DECOR.Inventory.get());
        //----------
    };
/* --------------------------------------------------------------------------- */
<commit_msg>Преобразование текста, вывод описания<commit_after>/* --------------------------------------------------------------------------- */
// ВЫВОД НА ЭКРАН
    window.SCREEN = {
        Out: function (text, _panel) {
            if (_panel === undefined) {_panel = 'main-output'} // end if
            //----------
            var EL=document.getElementById(_panel);
            //----------
            if (EL!=null) {
                EL.innerHTML += text2html(text);
                //EL.innerHTML += text;
            };
        }, // end function "Out"
        //----------
        Clear: function (_panel) {
            if (_panel === undefined) {_panel = 'main-output'} // end if
            //----------
            var EL=document.getElementById(_panel);
            //----------
            if (EL!=null) {
                EL.innerHTML='';
            } // end if
        }, // end function "Clear"
    };
/* --------------------------------------------------------------------------- */
// ВЫВОД НА ЭКРАН
    window.INTERFACE = {
        //--------------------------------------------------
        // Обработка нажатия клавиш игроком
        userInput: function (field, event) {
            if (event.which == null) { // IE
                if (event.keyCode == 13) {
                    INTERFACE.ExecuteCMD(field);
                } // end if
            } // end if
            //----------
            if (event.which != 0 && event.charCode != 0) { // все кроме IE
                if (event.which == 13) {
                    INTERFACE.ExecuteCMD(field);
                } // end if
            } // end if
            //----------
            return true; // спец. символ
        }, // end function "userInput"
        //--------------------------------------------------
        preparsing: function (field) {
            //----------
            var command = field.value || '';
            //----------
            if (command.trim() == '') {
                PARSER.pre_parse();
            } else {
                PARSER.parse(command, true);
            } // end if
            //----------
            INTERFACE.checkENTER();
            //----------
            DEBUG.updateWordsFullList();
            DEBUG.updateWordsShortList();
        }, // end function "preparsing"
        //--------------------------------------------------
        // Добавление (остатка) слова к команде игрока
        addWordToCommand: function (_text) {
            var field = document.getElementById('user_command');
            //----------
            if (field == null) {return;}
            //----------
            var value   = field.value;
            var lsymbol = value.substr(-1);
            if (lsymbol == ' ' || lsymbol == '\t') {
                field.value = value + _text + ' ';
            } else {
                var pos = value.lastIndexOf(' ');
                if (pos == -1) {
                    field.value = _text + ' ';
                } else {
                    field.value = value.substr(0, pos)+ ' ' + _text + ' ';
                } // end if
            } // end if
            //----------
            INTERFACE.preparsing(field);
            //----------
            field.focus();
        }, // end function "addWordToCommand"
        //--------------------------------------------------
        checkENTER: function () {
            var field = document.getElementById('user_command');
            if (field == null) {return;}
            //----------
            field.style.color = (AUTOCOMPLETE.getActionFlag() == true) ? "#00F" : "#000";
        }, // end function "addWordToCommand"
        //--------------------------------------------------
        ExecuteCMD: function (field) {
            // Выводим на экран команду игрока
            printCommand(field.value);
            //----------
            // Разбираем команду игрока
            var CMD = PARSER.parse(field.value);
            //----------
            field.value='';
            //----------
            if (CMD.action == null) {
                print('Ничего не понятно.');
            } else {
                // Вызываем событие "Перед выполнением действия с объектом"
                if (EVENTS.checkReactions(EVENTS.ACTION, {'what':CMD.object, 'when':EVENTS.BEFORE}, {'parameter': CMD}) == true) {
                    //----------
                    incProperty('turns.all');
                    incProperty('turns.loc');
                    //----------
                    CMD.action(CMD);
                    //----------
                    // Вызываем событие "После выполнением действия с объектом"
                    EVENTS.checkReactions(EVENTS.ACTION, {'what':CMD.object, 'when':EVENTS.AFTER}, {'parameter': CMD});
                } // end if
            } // end if
            //----------
            AZ.startNewTurn();
        },
        //--------------------------------------------------
    };
/* --------------------------------------------------------------------------- */
// ФУНКЦИИ РАБОТЫ С ЭКРАНОМ
    window.print = function (_text) {
        //----------
        SCREEN.Out(_text);
        //----------
    };
    //--------------------------------------------------
    window.printCommand = function (_text) {
        //----------
        SCREEN.Out(DECOR.Command.print(_text));
        //----------
    };
    //--------------------------------------------------
    window.printInventory = function () {
        //----------
        SCREEN.Out(DECOR.Inventory.get());
        //----------
    };
/* --------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>/*
Copyright 2016 Brazil Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function () {
  'use strict';

  angular.module('app')
    .component('commentGrid', {
      templateUrl: 'templates/commentGrid.html',
      controller: CommentGridCtrl
    });

  function CommentGridCtrl(
    $scope,
    $filter,
    CommonService,
    CommentService,
    PlayerService
  ) {
    var $ctrl = this;
    var autoScrolling = false;

    $ctrl.autoScroll = true;
    $ctrl.gridOptions = {
      rowSelection: 'single',
      enableColResize: true,
      enableSorting: true,
      suppressCellSelection: true,
      columnDefs: [{
        colId: 'playTime',
        field: 'playTime',
        headerName: '時間',
        width: 70,
        cellStyle: {
          textAlign: 'right'
        },
        cellRenderer: function (params) {
          var time = CommonService.formatTime(params.value);

          return ['
', time, '
'].join('');
        }
      }, {
        colId: 'time',
        field: 'time',
        headerName: '時刻',
        width: 70,
        cellStyle: {
          textAlign: 'right'
        },
        cellRenderer: function (params) {
          var time = $filter('date')(params.value, 'HH:mm:ss');

          return ['
', time, '
'].join('');
        }
      }, {
        colId: 'text',
        field: 'text',
        tooltipField: 'text',
        headerName: 'コメント',
        width: 428
      }, {
        colId: 'name',
        field: 'name',
        tooltipField: 'name',
        headerName: '名前',
        width: 180
      }, {
        colId: 'id',
        field: 'id',
        tooltipField: 'id',
        headerName: 'ID',
        width: 180
      }, {
        colId: 'email',
        field: 'email',
        tooltipField: 'email',
        headerName: 'メール',
        width: 240
      }, {
        colId: 'title',
        field: 'title',
        tooltipField: 'title',
        headerName: 'スレッド',
        width: 240
      }],
      onSortChanged: function () {
        var sortModel = this.api.getSortModel();

        if (
          sortModel.length > 1 ||
          sortModel[0].colId !== 'playTime' ||
          sortModel[0].sort !== 'asc'
        ) {
          $ctrl.autoScroll = false;
        }
      },
      onViewportChanged: function () {
        if (autoScrolling) {
          autoScrolling = false;
        } else {
          $ctrl.autoScroll = false;
        }
      },
      onRowDoubleClicked: function () {
        var selectedtRows = this.api.getSelectedRows();

        if (selectedtRows.length > 0) {
          PlayerService.time(selectedtRows[0].playTime);
        }
      }
    };

    $ctrl.updateFilter = function () {
      var checkedThreads = [];

      $ctrl.threads.forEach(function (a) {
        if (a.checked) {
          checkedThreads.push(a.title);
        }
      });
      CommentService.filter(function (comment) {
        if (checkedThreads.indexOf(comment.title) < 0) {
          return false;
        }
        return true;
      });
      $ctrl.gridOptions.api.setRowData(CommentService.filteredComments());
      checkedThreads = null;
    };

    $ctrl.autoScrollChanged = function () {
      if ($ctrl.autoScroll) {
        $ctrl.gridOptions.api.setSortModel([{
          colId: 'playTime',
          sort: 'asc'
        }]);
      }
    };

    $scope.$watch(function () {
      return CommentService.comments();
    }, function (value) {
      var titles = [];
      var threads = [];

      value.forEach(function (a) {
        if (titles.indexOf(a.title) < 0) {
          titles.push(a.title);
          threads.push({
            title: a.title
          });
        }
      });
      $ctrl.threads = threads;
      $ctrl.gridOptions.api.setRowData(CommentService.filteredComments());
      titles = null;
      threads = null;
    });

    $scope.$watch(function () {
      return PlayerService.time();
    }, function (newValue, oldValue) {
      if ($ctrl.autoScroll) {
        $ctrl.gridOptions.api.ensureNodeVisible(function (a) {
          return a.data.playTime >= oldValue;
        });
        autoScrolling = true;
      }
    });
  }
}());
<commit_msg>miyoutv: コメントのフィルター解除に対応<commit_after>/*
Copyright 2016 Brazil Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function () {
  'use strict';

  angular.module('app')
    .component('commentGrid', {
      templateUrl: 'templates/commentGrid.html',
      controller: CommentGridCtrl
    });

  function CommentGridCtrl(
    $scope,
    $filter,
    CommonService,
    CommentService,
    PlayerService
  ) {
    var $ctrl = this;
    var autoScrolling = false;

    $ctrl.autoScroll = true;
    $ctrl.gridOptions = {
      rowSelection: 'single',
      enableColResize: true,
      enableSorting: true,
      suppressCellSelection: true,
      columnDefs: [{
        colId: 'playTime',
        field: 'playTime',
        headerName: '時間',
        width: 70,
        cellStyle: {
          textAlign: 'right'
        },
        cellRenderer: function (params) {
          var time = CommonService.formatTime(params.value);

          return ['
', time, '
'].join('');
        }
      }, {
        colId: 'time',
        field: 'time',
        headerName: '時刻',
        width: 70,
        cellStyle: {
          textAlign: 'right'
        },
        cellRenderer: function (params) {
          var time = $filter('date')(params.value, 'HH:mm:ss');

          return ['
', time, '
'].join('');
        }
      }, {
        colId: 'text',
        field: 'text',
        tooltipField: 'text',
        headerName: 'コメント',
        width: 428
      }, {
        colId: 'name',
        field: 'name',
        tooltipField: 'name',
        headerName: '名前',
        width: 180
      }, {
        colId: 'id',
        field: 'id',
        tooltipField: 'id',
        headerName: 'ID',
        width: 180
      }, {
        colId: 'email',
        field: 'email',
        tooltipField: 'email',
        headerName: 'メール',
        width: 240
      }, {
        colId: 'title',
        field: 'title',
        tooltipField: 'title',
        headerName: 'スレッド',
        width: 240
      }],
      onSortChanged: function () {
        var sortModel = this.api.getSortModel();

        if (
          sortModel.length > 1 ||
          sortModel[0].colId !== 'playTime' ||
          sortModel[0].sort !== 'asc'
        ) {
          $ctrl.autoScroll = false;
        }
      },
      onViewportChanged: function () {
        if (autoScrolling) {
          autoScrolling = false;
        } else {
          $ctrl.autoScroll = false;
        }
      },
      onRowDoubleClicked: function () {
        var selectedtRows = this.api.getSelectedRows();

        if (selectedtRows.length > 0) {
          PlayerService.time(selectedtRows[0].playTime);
        }
      }
    };

    $ctrl.updateFilter = function () {
      var checkedThreads = [];

      $ctrl.threads.forEach(function (a) {
        if (a.checked) {
          checkedThreads.push(a.title);
        }
      });
      if (checkedThreads.length > 0) {
        CommentService.filter(function (comment) {
          if (checkedThreads.indexOf(comment.title) < 0) {
            return false;
          }
          return true;
        });
      } else {
        CommentService.filter(null);
      }
      $ctrl.gridOptions.api.setRowData(CommentService.filteredComments());
      checkedThreads = null;
    };

    $ctrl.autoScrollChanged = function () {
      if ($ctrl.autoScroll) {
        $ctrl.gridOptions.api.setSortModel([{
          colId: 'playTime',
          sort: 'asc'
        }]);
      }
    };

    $scope.$watch(function () {
      return CommentService.comments();
    }, function (value) {
      var titles = [];
      var threads = [];

      value.forEach(function (a) {
        if (titles.indexOf(a.title) < 0) {
          titles.push(a.title);
          threads.push({
            title: a.title
          });
        }
      });
      $ctrl.threads = threads;
      $ctrl.gridOptions.api.setRowData(CommentService.filteredComments());
      titles = null;
      threads = null;
    });

    $scope.$watch(function () {
      return PlayerService.time();
    }, function (newValue, oldValue) {
      if ($ctrl.autoScroll) {
        $ctrl.gridOptions.api.ensureNodeVisible(function (a) {
          return a.data.playTime >= oldValue;
        });
        autoScrolling = true;
      }
    });
  }
}());
<|endoftext|>


<commit_before>import React from 'react'
//import { StickyContainer, Sticky } from 'react-sticky';
import W from '../../../shared/woodcraft.js'
import {
    Row,
    Col,
} from 'reactstrap';

const moment = require("moment");

W.reverse();

export default class ParticipantsList extends React.Component {

    render() {

        const list = this.props.booking.participants.filter(p => p.name !== '' && p.age !== '' && p.diet !== '');
        const groups = W.map(w => {
            const people = list.filter((p) => p.age === '' ? false : w.filter(moment(this.props.event.startDate).diff(moment(p.age), 'years'))).map((p, k) =>

<a href={`#participant-${p.id}`}>{p.name}
);
            if (people.length === 0) return null;
            return (

                <h8>{w.name}: {people.length}</h8>
                {people}

);
        });

        return (<Col md={2}>

                <h7>Participants: {list.length}</h7>
                {groups}

        </Col>);

    }

}	<commit_msg>Sort quick list<commit_after>import React from 'react'
//import { StickyContainer, Sticky } from 'react-sticky';
import W from '../../../shared/woodcraft.js'
import {
    Row,
    Col,
} from 'reactstrap';

const moment = require("moment");

W.reverse();

export default class ParticipantsList extends React.Component {

    render() {

        const list = this.props.booking.participants.filter(p => p.name !== '' && p.age !== '' && p.diet !== '');
        const groups = W.map(w => {
            const people = list.filter((p) => p.age === '' ? false : w.filter(moment(this.props.event.startDate).diff(moment(p.age), 'years')))
                .sort(nameSort)
                .map((p, k) =>

<a href={`#participant-${p.id}`}>{p.name}
);
            if (people.length === 0) return null;
            return (

{w.name}: {people.length}

                {people}

);
        });

        return (<Col md={2}>

Participants: {list.length}

                {groups}

        </Col>);

    }
}

const nameSort = (a, b) => {
    var splitA = a.name.split(" ");
    var splitB = b.name.split(" ");
    var lastA = splitA[splitA.length - 1];
    var lastB = splitB[splitB.length - 1];

    if (lastA < lastB) return -1;
    if (lastA > lastB) return 1;
    return 0;
};<|endoftext|>


<commit_before>var Alloy = require('alloy'),
	_ = Alloy._,
	Backbone = Alloy.Backbone;

var WM = module.exports = {
	navWindows: [],

	/**
	 * Open given Window in a new Ti.UI.iOS.NavigationWindow on iOS and return it. Do nothing on other platforms
	 *
	 * @param {Ti.UI.Window} win Window to open in NavigationWindow
	 *
	 * @return {Ti.UI.iOS.NavigationWindow} Created NavigationWindow
	 */
	createNewNavWindow: function(win) {
		if (OS_IOS) {
			var navWindow = Ti.UI.iOS.createNavigationWindow({
				backgroundColor: '#fff',

				window: win
			});
			navWindow.id = 'navWindow_' + _.uniqueId();

			WM.navWindows.push(navWindow);

			// Store reference in the root Window to the NavigationWindow
			win.navWin = navWindow;

			return navWindow;
		} else
			return win;
	},

	/**
	 * Open given Window in a the last created Ti.UI.iOS.NavigationWindow on iOS. Just open the Window on other platforms
	 *
	 * @param {Ti.UI.Window} win Window to open in NavigationWindow
	 */
	openWinInActiveNavWindow: function(win) {
		if (OS_IOS) {
			if (!WM.navWindows.length) {
				if(Alloy.Globals.tabGroup)
					Alloy.Globals.tabGroup.activeTab.open(win);
				else
					WM.createNewNavWindow(win).open();
			}
			else
				_.last(WM.navWindows).openWindow(win);
		} else
			win.open();
	},

	/**
	 * Open the given Window.
	 *
	 * @param {Ti.UI.Window} win Window to open
	 */
	openWin: function(win) {
		if (win.createStack) {
			addWinToStack(win.createStack, win);
		} else if (win.addToStack) {
			addWinToStack(win.addToStack, win);
		}

		if (OS_IOS) {
			// Sometimes we accidentally set modal and navGroup to true.
			// In that case 'modal' should be preferred, because modal windows are always opened in a new NavWindow
			if (win.navGroup && win.modalWin)
				win.navGroup = false;

			// Show SideMenu button and replace current centerWindow with this new Window
			if (win.showSideMenu) {
				// Show sideMenu button
				var sideMenuButton = Alloy.createWidget(Alloy.CFG.SideMenu.buttonWidget || 'rebel.MenuBarButton', {
					buttonType: 'hamburger',
					delay: 200
				});
				win.leftNavButton = sideMenuButton.getView();
				sideMenuButton.on('click', WM.toggleLeftNavDrawer);

				// Create SideMenu if not yet created.
				// Else replace current centerWindow with this Window
				setupNavDrawer({
					centerWin: WM.createNewNavWindow(win)
				});
			}
			// If window should be Modal Window
			// Also add it to a new navigationGroup
			else if (win.modalWin) {
				var navWin = WM.createNewNavWindow(win);
				navWin.open({
					modal: true
				});
			}
			// If window should be part of NavigationGroup
			else if (win.navGroup) {
				WM.openWinInActiveNavWindow(win);
			}
			// Else, just open the Window
			else
				win.open();
		} else if (OS_ANDROID) {
			Ti.API.info(win.showSideMenu);
			if (win.showSideMenu) {
				// Create SideMenu if not yet created.
				setupNavDrawer({
					centerWin: win
				});
			}
				// win.addEventListener('open', onOpenTopWindow);
			// } else
				// win.addEventListener('open', onOpenSubWindow);

			// win.open();
		} else
			win.open();
	},

	/**
	 * Close the given Window

	 * @param {Ti.UI.Window} win Window to close
	 */
	closeWin: function(win) {
		if (OS_IOS) {
			// If Window is a NavigationWindow, clean up root Window as well
			if (win.window) {
				win.window.fireEvent('close');

				if (win.window.leftNavButton)
					win.window.leftNavButton.removeEventListener('click', WM.toggleLeftNavDrawer);

				win.window = null;

				// WM.navWindows.pop();
				var index = WM.navWindows.indexOf(win);

				WM.navWindows.splice(index, 1);

				win.close();
			}
			// If Window is a root Window of a NavigationWindow, close the NavigationWindow instead
			else if (win.navWin) {
				var navWin = win.navWin;
				delete win.navWin;

				WM.closeWin(navWin);
			// If Window is part of tabGroup, close via TabGroup
			} else if(Alloy.Globals.tabGroup)
				Alloy.Globals.tabGroup.close(win);
			// Else just close the Window
			else
				win.close();
		} else
			win.close();
	},

	/**
	 * Open or Close the left-side Navigation Drawer (if exists)
	 */
	toggleLeftNavDrawer: function() {
		if (_navDrawer)
			_navDrawer.toggleLeftWindow();
	},

	/**
	 * Close the Stack of Windows with given name
	 *
	 * @param {String} name Name of Stack to close
	 */
	killStack: function(name) {
		if (_windowStacks[name])
			_.each(_windowStacks[name], function(win) {
				WM.closeWin(win);
			});
	},
	destruct: function() {
		_.each(WM.navWindows,function(win) {
			WM.closeWin(win);
		});
	}

};

_.extend(WM, Backbone.Events);

/**
 * @property {Object} _windowStacks Dictionary of stacks of Windows. Each element contains an array of one or more windows
 */
_windowStacks = {};

/**
 * Add given Window to stack with given name
 * @private
 *
 * @param {String} name Stack to add given Window to
 * @param {Ti.UI.Window} win Window to add
 */
function addWinToStack(name, win) {
	if (!_windowStacks[name])
		_windowStacks[name] = [];

	_windowStacks[name].push(win);
}

if (OS_ANDROID) {

	/**
	 * On Android: Handle open event of Sub window. It adds the Android backbutton and closes it on click
	 * @private
	 *
	 * @param {Object} evt Event details
	 */
	function onOpenSubWindow(evt) {
		var win = this;

		if (this.activity) {
			//Setup the ActionBar for 1> level windows
			var actionBar = this.activity.actionBar;
			if (actionBar && !this.navBarHidden) {
				actionBar.displayHomeAsUp = true;
				actionBar.icon = '/images/generic/logoTransparentSmall.png';
				actionBar.onHomeIconItemSelected = function() {
					win.close();
				};
			}

			this.activity.onPrepareOptionsMenu = createOptionsMenu;

			this.activity.invalidateOptionsMenu();
		}
	}

	/**
	 * On Android: Handle open event of Top window. It opens the NavigationDrawer
	 * @private
	 *
	 * @param {Object} evt Event details
	 */
	function onOpenTopWindow(evt) {
		if (this.activity) {
			//Setup ActionBar for level 1 windows
			var actionBar = this.activity.actionBar;
			if (actionBar && !this.navBarHidden) {
				actionBar.displayHomeAsUp = false;
				actionBar.icon = '/images/generic/hamburger.png';

				actionBar.onHomeIconItemSelected = function() {
					if (_navDrawerAndroid) {
						_navDrawerAndroid.toggleDrawer();
					}
				};
			}

			// Close app when clicking back button
			this.addEventListener('androidback', onBackButtonClick);

			this.activity.onPrepareOptionsMenu = createOptionsMenu;

			this.activity.invalidateOptionsMenu();
		}
	}

	function onBackButtonClick(evt) {
		this.removeEventListener('androidback', onBackButtonClick);

		// Go back to home
		// Ti.Android.currentActivity.finish();
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_MAIN
		});
		intent.addCategory(Ti.Android.CATEGORY_HOME);
		Ti.Android.currentActivity.startActivity(intent);
	}

	function createOptionsMenu(evt) {
		var menu = evt.menu,
			menuItem;

		// Settings
		// if (F.load('Acl').isLoggedin() && !menu.findItem(998)) {
		// 	menuItem = menu.add({
		// 		itemId: 998,
		// 		title: L('menuSettings'),
		// 		showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
		// 		order: 998
		// 	});
		// 	menuItem.addEventListener('click', onOpenSettings);
		// }

		// Feedback
		// if (!menu.findItem(998)) {
		// 	menuItem = menu.add({
		// 		itemId: 998,
		// 		title: L('menuSettings'),
		// 		showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
		// 		order: 998
		// 	});
		// 	menuItem.addEventListener('click', onOpenSettings);
		// }

		// Help
		if (!menu.findItem(999)) {
			menuItem = menu.add({
				itemId: 999,
				title: L('Help'),
				showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
				order: 999
			});
			menuItem.addEventListener('click', onOpenHelp);
		}

		// this.invalidateOptionsMenu();
	}

	function onOpenSettings() {
		Alloy.createController('Settings');
	}

	function onOpenHelp() {
		var Acl = require('Acl'),
			emailDialog = Ti.UI.createEmailDialog();

		emailDialog.subject = "I could use some help!";
		emailDialog.toRecipients = [Alloy.CFG.supportEmail];

		var message = "\n\r\n\r\n\r --- \n\r";

		if (Acl.isLoggedin()) {
			var user = Acl.getLoggedinUser();

			message = message + 'User: ' + user.get('name') + ' (' + user.id + ')' + "\n\r";
		}

		message = message + 'Version: ' + Ti.App.getVersion() + "\n\r" +
			'Phone model: ' + Ti.Platform.model + "\n\r" +
			'OS: ' + Ti.Platform.osname + ' ' + Ti.Platform.version + "\n\r" +
			'';

		emailDialog.messageBody = message;
		emailDialog.open();
	}
}
/**
 * @property {Ti.UI.Window} _navDrawer The Navigation Drawer window
 * @private
 */
_navDrawer = null;

/**
 * Setup Navigation Drawer module
 * @private
 *
 * @param {Object} config Configuration for module
 */
function setupNavDrawer(config) {
	// Setup NavDrawer module on iOS
	if (OS_IOS) {
		if (!_navDrawer) {
			_navDrawer = require('RebelFrame/SideMenu/' + Alloy.CFG.SideMenu.type);
			_navDrawer.setup(config);

			_navDrawer.on('open', onNavBarOpen);
			_navDrawer.on('close', onNavBarClose);
		} else {
			// Replace current centerWindow with new centerWindow
			_navDrawer.setCenterWindow(config.centerWin);
		}
	} else if (OS_ANDROID) {
		if (!_navDrawer) {
			console.log('drawer');

			// Create NavigationDrawer for Android
			_navDrawer = require('RebelFrame/SideMenu/Android');
			_navDrawer.setup(config);

			_navDrawer.on('navigate', function(evt) {
				// Open new win
				// Close old win
			});
		} else {
			_navDrawer.attach(config.centerWin);
		}
	}
}

function onNavBarOpen(evt) {
	WM.trigger('navbaropen', evt);
}

function onNavBarClose(evt) {
	WM.trigger('navbarclose', evt);
}
<commit_msg>Only Windows with hamburger could be opened<commit_after>var Alloy = require('alloy'),
	_ = Alloy._,
	Backbone = Alloy.Backbone;

var WM = module.exports = {
	navWindows: [],

	/**
	 * Open given Window in a new Ti.UI.iOS.NavigationWindow on iOS and return it. Do nothing on other platforms
	 *
	 * @param {Ti.UI.Window} win Window to open in NavigationWindow
	 *
	 * @return {Ti.UI.iOS.NavigationWindow} Created NavigationWindow
	 */
	createNewNavWindow: function(win) {
		if (OS_IOS) {
			var navWindow = Ti.UI.iOS.createNavigationWindow({
				backgroundColor: '#fff',

				window: win
			});
			navWindow.id = 'navWindow_' + _.uniqueId();

			WM.navWindows.push(navWindow);

			// Store reference in the root Window to the NavigationWindow
			win.navWin = navWindow;

			return navWindow;
		} else
			return win;
	},

	/**
	 * Open given Window in a the last created Ti.UI.iOS.NavigationWindow on iOS. Just open the Window on other platforms
	 *
	 * @param {Ti.UI.Window} win Window to open in NavigationWindow
	 */
	openWinInActiveNavWindow: function(win) {
		if (OS_IOS) {
			if (!WM.navWindows.length) {
				if(Alloy.Globals.tabGroup)
					Alloy.Globals.tabGroup.activeTab.open(win);
				else
					WM.createNewNavWindow(win).open();
			}
			else
				_.last(WM.navWindows).openWindow(win);
		} else
			win.open();
	},

	/**
	 * Open the given Window.
	 *
	 * @param {Ti.UI.Window} win Window to open
	 */
	openWin: function(win) {
		if (win.createStack) {
			addWinToStack(win.createStack, win);
		} else if (win.addToStack) {
			addWinToStack(win.addToStack, win);
		}

		if (OS_IOS) {
			// Sometimes we accidentally set modal and navGroup to true.
			// In that case 'modal' should be preferred, because modal windows are always opened in a new NavWindow
			if (win.navGroup && win.modalWin)
				win.navGroup = false;

			// Show SideMenu button and replace current centerWindow with this new Window
			if (win.showSideMenu) {
				// Show sideMenu button
				var sideMenuButton = Alloy.createWidget(Alloy.CFG.SideMenu.buttonWidget || 'rebel.MenuBarButton', {
					buttonType: 'hamburger',
					delay: 200
				});
				win.leftNavButton = sideMenuButton.getView();
				sideMenuButton.on('click', WM.toggleLeftNavDrawer);

				// Create SideMenu if not yet created.
				// Else replace current centerWindow with this Window
				setupNavDrawer({
					centerWin: WM.createNewNavWindow(win)
				});
			}
			// If window should be Modal Window
			// Also add it to a new navigationGroup
			else if (win.modalWin) {
				var navWin = WM.createNewNavWindow(win);
				navWin.open({
					modal: true
				});
			}
			// If window should be part of NavigationGroup
			else if (win.navGroup) {
				WM.openWinInActiveNavWindow(win);
			}
			// Else, just open the Window
			else
				win.open();
		} else if (OS_ANDROID) {

			if (win.showSideMenu) {
				// Create SideMenu if not yet created.
				setupNavDrawer({
					centerWin: win
				});

				// win.addEventListener('open', onOpenTopWindow);
			} else {
				// win.addEventListener('open', onOpenSubWindow);

				win.open();
			}
		} else
			win.open();
	},

	/**
	 * Close the given Window

	 * @param {Ti.UI.Window} win Window to close
	 */
	closeWin: function(win) {
		if (OS_IOS) {
			// If Window is a NavigationWindow, clean up root Window as well
			if (win.window) {
				win.window.fireEvent('close');

				if (win.window.leftNavButton)
					win.window.leftNavButton.removeEventListener('click', WM.toggleLeftNavDrawer);

				win.window = null;

				// WM.navWindows.pop();
				var index = WM.navWindows.indexOf(win);

				WM.navWindows.splice(index, 1);

				win.close();
			}
			// If Window is a root Window of a NavigationWindow, close the NavigationWindow instead
			else if (win.navWin) {
				var navWin = win.navWin;
				delete win.navWin;

				WM.closeWin(navWin);
			// If Window is part of tabGroup, close via TabGroup
			} else if(Alloy.Globals.tabGroup)
				Alloy.Globals.tabGroup.close(win);
			// Else just close the Window
			else
				win.close();
		} else
			win.close();
	},

	/**
	 * Open or Close the left-side Navigation Drawer (if exists)
	 */
	toggleLeftNavDrawer: function() {
		if (_navDrawer)
			_navDrawer.toggleLeftWindow();
	},

	/**
	 * Close the Stack of Windows with given name
	 *
	 * @param {String} name Name of Stack to close
	 */
	killStack: function(name) {
		if (_windowStacks[name])
			_.each(_windowStacks[name], function(win) {
				WM.closeWin(win);
			});
	},
	destruct: function() {
		_.each(WM.navWindows,function(win) {
			WM.closeWin(win);
		});
	}

};

_.extend(WM, Backbone.Events);

/**
 * @property {Object} _windowStacks Dictionary of stacks of Windows. Each element contains an array of one or more windows
 */
_windowStacks = {};

/**
 * Add given Window to stack with given name
 * @private
 *
 * @param {String} name Stack to add given Window to
 * @param {Ti.UI.Window} win Window to add
 */
function addWinToStack(name, win) {
	if (!_windowStacks[name])
		_windowStacks[name] = [];

	_windowStacks[name].push(win);
}

if (OS_ANDROID) {

	/**
	 * On Android: Handle open event of Sub window. It adds the Android backbutton and closes it on click
	 * @private
	 *
	 * @param {Object} evt Event details
	 */
	function onOpenSubWindow(evt) {
		var win = this;

		if (this.activity) {
			//Setup the ActionBar for 1> level windows
			var actionBar = this.activity.actionBar;
			if (actionBar && !this.navBarHidden) {
				actionBar.displayHomeAsUp = true;
				actionBar.icon = '/images/generic/logoTransparentSmall.png';
				actionBar.onHomeIconItemSelected = function() {
					win.close();
				};
			}

			this.activity.onPrepareOptionsMenu = createOptionsMenu;

			this.activity.invalidateOptionsMenu();
		}
	}

	/**
	 * On Android: Handle open event of Top window. It opens the NavigationDrawer
	 * @private
	 *
	 * @param {Object} evt Event details
	 */
	function onOpenTopWindow(evt) {
		if (this.activity) {
			//Setup ActionBar for level 1 windows
			var actionBar = this.activity.actionBar;
			if (actionBar && !this.navBarHidden) {
				actionBar.displayHomeAsUp = false;
				actionBar.icon = '/images/generic/hamburger.png';

				actionBar.onHomeIconItemSelected = function() {
					if (_navDrawerAndroid) {
						_navDrawerAndroid.toggleDrawer();
					}
				};
			}

			// Close app when clicking back button
			this.addEventListener('androidback', onBackButtonClick);

			this.activity.onPrepareOptionsMenu = createOptionsMenu;

			this.activity.invalidateOptionsMenu();
		}
	}

	function onBackButtonClick(evt) {
		this.removeEventListener('androidback', onBackButtonClick);

		// Go back to home
		// Ti.Android.currentActivity.finish();
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_MAIN
		});
		intent.addCategory(Ti.Android.CATEGORY_HOME);
		Ti.Android.currentActivity.startActivity(intent);
	}

	function createOptionsMenu(evt) {
		var menu = evt.menu,
			menuItem;

		// Settings
		// if (F.load('Acl').isLoggedin() && !menu.findItem(998)) {
		// 	menuItem = menu.add({
		// 		itemId: 998,
		// 		title: L('menuSettings'),
		// 		showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
		// 		order: 998
		// 	});
		// 	menuItem.addEventListener('click', onOpenSettings);
		// }

		// Feedback
		// if (!menu.findItem(998)) {
		// 	menuItem = menu.add({
		// 		itemId: 998,
		// 		title: L('menuSettings'),
		// 		showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
		// 		order: 998
		// 	});
		// 	menuItem.addEventListener('click', onOpenSettings);
		// }

		// Help
		if (!menu.findItem(999)) {
			menuItem = menu.add({
				itemId: 999,
				title: L('Help'),
				showAsAction: Ti.Android.SHOW_AS_ACTION_NEVER,
				order: 999
			});
			menuItem.addEventListener('click', onOpenHelp);
		}

		// this.invalidateOptionsMenu();
	}

	function onOpenSettings() {
		Alloy.createController('Settings');
	}

	function onOpenHelp() {
		var Acl = require('Acl'),
			emailDialog = Ti.UI.createEmailDialog();

		emailDialog.subject = "I could use some help!";
		emailDialog.toRecipients = [Alloy.CFG.supportEmail];

		var message = "\n\r\n\r\n\r --- \n\r";

		if (Acl.isLoggedin()) {
			var user = Acl.getLoggedinUser();

			message = message + 'User: ' + user.get('name') + ' (' + user.id + ')' + "\n\r";
		}

		message = message + 'Version: ' + Ti.App.getVersion() + "\n\r" +
			'Phone model: ' + Ti.Platform.model + "\n\r" +
			'OS: ' + Ti.Platform.osname + ' ' + Ti.Platform.version + "\n\r" +
			'';

		emailDialog.messageBody = message;
		emailDialog.open();
	}
}
/**
 * @property {Ti.UI.Window} _navDrawer The Navigation Drawer window
 * @private
 */
_navDrawer = null;

/**
 * Setup Navigation Drawer module
 * @private
 *
 * @param {Object} config Configuration for module
 */
function setupNavDrawer(config) {
	// Setup NavDrawer module on iOS
	if (OS_IOS) {
		if (!_navDrawer) {
			_navDrawer = require('RebelFrame/SideMenu/' + Alloy.CFG.SideMenu.type);
			_navDrawer.setup(config);

			_navDrawer.on('open', onNavBarOpen);
			_navDrawer.on('close', onNavBarClose);
		} else {
			// Replace current centerWindow with new centerWindow
			_navDrawer.setCenterWindow(config.centerWin);
		}
	} else if (OS_ANDROID) {
		if (!_navDrawer) {
			console.log('drawer');

			// Create NavigationDrawer for Android
			_navDrawer = require('RebelFrame/SideMenu/Android');
			_navDrawer.setup(config);

			_navDrawer.on('navigate', function(evt) {
				// Open new win
				// Close old win
			});
		} else {
			_navDrawer.attach(config.centerWin);
		}
	}
}

function onNavBarOpen(evt) {
	WM.trigger('navbaropen', evt);
}

function onNavBarClose(evt) {
	WM.trigger('navbarclose', evt);
}
<|endoftext|>


<commit_before>/*!
 * Mappersmith 2.0.0-rc3
 * https://github.com/tulios/mappersmith
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mappersmith=t():e.mappersmith=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,t),s.l=!0,s.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=10)}([function(module,exports,__webpack_require__){"use strict";function toQueryString(e){return isPlainObject(e)?validKeys(e).map(function(t){return buildRecursive(t,e[t])}).join("&").replace(R20,"+"):e}function performanceNow(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()}function parseResponseHeaders(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n<r.length;n++){var s=r[n],o=s.indexOf(": ");if(o>0){var i=s.substring(0,o).toLowerCase(),a=s.substring(o+2).trim();t[i]=a}}return t}function lowerCaseObjectKeys(e){return Object.keys(e).reduce(function(t,r){return t[r.toLowerCase()]=e[r],t},{})}function isPlainObject(e){return"[object Object]"===toString.call(e)&&Object.getPrototypeOf(e)===Object.getPrototypeOf({})}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)};exports.toQueryString=toQueryString,exports.performanceNow=performanceNow,exports.parseResponseHeaders=parseResponseHeaders,exports.lowerCaseObjectKeys=lowerCaseObjectKeys,exports.isPlainObject=isPlainObject,"undefined"!=typeof window&&null!==window&&(window.performance||(window.performance={}),performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process=void 0,getNanoSeconds=void 0,loadTime=void 0;try{_process=eval("process")}catch(e){}var hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime};hasProcessHrtime()&&(getNanoSeconds=function(){var e=_process.hrtime();return 1e9*e[0]+e[1]},loadTime=getNanoSeconds());var R20=/%20/g,validKeys=function(e){return Object.keys(e).filter(function(t){return void 0!==e[t]&&null!==e[t]})},buildRecursive=function e(t,r,n){n=n||"";var s=Array.isArray(r),o="object"===("undefined"==typeof r?"undefined":_typeof(r));return s||o?s?r.map(function(r){return e(t,r,n+"[]")}).join("&"):validKeys(r).map(function(s){return e(t,r[s],n+"["+s+"]")}).join("&"):encodeURIComponent(t+n)+"="+encodeURIComponent(r)},hasOwnProperty=Object.prototype.hasOwnProperty,assign=exports.assign=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},toString=Object.prototype.toString},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){return new i.default(e,a.gateway).build()}Object.defineProperty(t,"__esModule",{value:!0}),t.configs=void 0,t.default=s;var o=r(6),i=n(o),a=t.configs={Promise:"function"==typeof Promise?Promise:null,gateway:null,gatewayConfigs:{emulateHTTP:!1,XHR:{withCredentials:!1,configure:null}}}},function(e,t,r){"use strict";function n(e){this.host=e.host,this.path=e.path,this.method=e.method||"get",this.headers=e.headers,this.params=e.params,this.bodyAttr=e.bodyAttr||"body",this.headersAttr=e.headersAttr||"headers"}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";function n(e,t,r,n){this.originalRequest=e,this.responseStatus=t,this.responseData=r,this.responseHeaders=n||{},this.timeElapsed=null}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0);n.prototype={request:function(){return this.originalRequest},status:function(){return 1223===this.responseStatus?204:this.responseStatus},success:function(){var e=this.status();return e>=200&&e<400},headers:function(){return(0,s.lowerCaseObjectKeys)(this.responseHeaders)},rawData:function(){return this.responseData},data:function e(){var e=this.responseData;if(this.isContentTypeJSON())try{e=JSON.parse(this.responseData)}catch(e){}return e},isContentTypeJSON:function(){return/application\/json/.test(this.headers()["content-type"])},enhance:function(e){return new n(this.request(),e.status||this.status(),e.rawData||this.rawData(),(0,s.assign)({},this.headers(),e.headers))}},t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){i.default.apply(this,arguments)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(7),i=n(o),a=r(3),u=n(a),c=r(0);s.prototype=i.default.extends({get:function(){var e=new XMLHttpRequest;this.configureCallbacks(e),e.open("get",this.request.url(),!0),this.setHeaders(e,{}),e.send()},post:function(){this.performRequest("post")},put:function(){this.performRequest("put")},patch:function(){this.performRequest("patch")},delete:function(){this.performRequest("delete")},configureCallbacks:function(e){var t=this;e.addEventListener("load",function(){t.dispatchResponse(t.createResponse(e))}),e.addEventListener("error",function(){t.dispatchClientError("Network error")});var r=this.options().XHR;r.withCredentials&&(e.withCredentials=!0),r.configure&&r.configure(e)},performRequest:function(e){var t=this.shouldEmulateHTTP()?"post":e,r=new XMLHttpRequest;this.configureCallbacks(r),r.open(t,this.request.url(),!0);var n={},s=this.prepareBody(e,n);this.setHeaders(r,n);var o=[];s&&o.push(s),r.send.apply(r,o)},createResponse:function(e){var t=e.status,r=e.responseText,n=(0,c.parseResponseHeaders)(e.getAllResponseHeaders());return new u.default(this.request,t,r,n)},setHeaders:function(e,t){var r=(0,c.assign)(t,this.request.headers());Object.keys(r).forEach(function(t){e.setRequestHeader(t,r[t])})}}),t.default=s},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!e)throw new Error("[Mappersmith] invalid manifest ("+e+")");if(!t)throw new Error("[Mappersmith] gateway class not configured (configs.gateway)");this.manifest=new a.default(e),this.GatewayClass=t}Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),a=n(i),u=r(2),c=(n(u),r(9)),f=n(c),p=r(0);o.prototype={build:function(){var e=this,t={_manifest:this.manifest};return this.manifest.eachResource(function(r,n){t[r]=e.buildResource(n)}),t},buildResource:function(e){var t=this;return e.reduce(function(e,r){return(0,p.assign)(e,s({},r.name,function(e){var n=new f.default(r.descriptor,e);return t.invokeMiddlewares(n)}))},{})},invokeMiddlewares:function(e){var t=this,r=this.manifest.createMiddlewares(),n=r.reduce(function(e,t){return t.request(e)},e),s=function(){return new t.GatewayClass(n).call()},o=r.reduce(function(e,t){return function(){return t.response(e)}},s);return o()}},t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.request=e,this.successCallback=function(){},this.failCallback=function(){}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(0),i=r(1),a=r(3),u=n(a);s.extends=function(e){return(0,o.assign)({},s.prototype,e)},s.prototype={options:function(){return i.configs.gatewayConfigs},shouldEmulateHTTP:function(){return this.options().emulateHTTP&&/^(delete|put|patch)/i.test(this.request.method())},call:function(){var e=this,t=arguments,r=(0,o.performanceNow)();return new i.configs.Promise(function(n,s){e.successCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,n(e)},e.failCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,s(e)};try{e[e.request.method()].apply(e,t)}catch(t){e.dispatchClientError(t.message)}})},dispatchResponse:function(e){e.success()?this.successCallback(e):this.failCallback(e)},dispatchClientError:function(e){this.failCallback(new u.default(this.request,400,e))},prepareBody:function(e,t){var r=this.request.body();this.shouldEmulateHTTP()&&(r=r||{},(0,o.isPlainObject)(r)&&(r._method=e),t["x-http-method-override"]=e);var n=(0,o.toQueryString)(r);return n&&(0,o.isPlainObject)(r)&&(t["content-type"]="application/x-www-form-urlencoded;charset=utf-8"),n}},t.default=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.host=e.host,this.resources=e.resources||{},this.middlewares=e.middlewares||[]}Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),i=n(o),a=r(0);s.prototype={eachResource:function(e){var t=this;Object.keys(this.resources).forEach(function(r){var n=t.eachMethod(r,function(e){return{name:e,descriptor:t.createMethodDescriptor(r,e)}});e(r,n)})},eachMethod:function(e,t){return Object.keys(this.resources[e]).map(function(e){return t(e)})},createMethodDescriptor:function(e,t){var r=this.resources[e][t];if(!r||!r.path)throw new Error('[Mappersmith] path is undefined for resource "'+e+'" method "'+t+'"');return new i.default((0,a.assign)({host:this.host},r))},createMiddlewares:function(){var e=function(e){return(0,a.assign)({request:function(e){return e},response:function(e){return e()}},e())};return this.middlewares.map(function(t){return e(t)})}},t.default=s},function(e,t,r){"use strict";function n(e,t){this.methodDescriptor=e,this.requestParams=t||{}}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0),o=new RegExp("{([^}]+)}");n.prototype={params:function e(){var t=this,e=(0,s.assign)({},this.methodDescriptor.params,this.requestParams),r=function(e){return e!==t.methodDescriptor.headersAttr&&e!==t.methodDescriptor.bodyAttr};return Object.keys(e).reduce(function(t,n){return r(n)&&(t[n]=e[n]),t},{})},method:function(){return this.methodDescriptor.method.toLowerCase()},host:function(){return(this.methodDescriptor.host||"").replace(/\/$/,"")},path:function e(){var e=this.methodDescriptor.path,t=this.methodDescriptor;t.headersAttr,t.bodyAttr;"/"!==this.methodDescriptor.path[0]&&(e="/"+this.methodDescriptor.path);var r=this.params();Object.keys(r).forEach(function(t){var n=r[t],s="{"+t+"}";new RegExp(s).test(e)&&(e=e.replace("{"+t+"}",n),delete r[t])});var n=e.match(o);if(n)throw new Error("[Mappersmith] required parameter missing ("+n[1]+'), "'+e+'" cannot be resolved');var i=(0,s.toQueryString)(r);return 0!==i.length&&(e+="?"+i),e},url:function(){return""+this.host()+this.path()},headers:function(){return(0,s.lowerCaseObjectKeys)((0,s.assign)({},this.methodDescriptor.headers,this.requestParams[this.methodDescriptor.headersAttr]))},body:function(){return this.requestParams[this.methodDescriptor.bodyAttr]},enhance:function(e){var t=this.methodDescriptor.headersAttr,r=this.methodDescriptor.bodyAttr,o=(0,s.assign)({},this.requestParams,e.params);return o[t]=(0,s.assign)({},this.requestParams[t],e.headers),o[r]=e.body,new n(this.methodDescriptor,o)}},t.default=n},function(module,exports,__webpack_require__){"use strict";var lib=__webpack_require__(1),_process,defaultGateway;try{_process=eval("process")}catch(e){}"undefined"!=typeof XMLHttpRequest?defaultGateway=__webpack_require__(4).default:"undefined"!=typeof _process&&(defaultGateway=__webpack_require__(5).default),lib.configs.gateway=defaultGateway,module.exports=lib}])});
//# sourceMappingURL=mappersmith.map<commit_msg>update precompiled version<commit_after>/*!
 * Mappersmith 2.0.0-rc4
 * https://github.com/tulios/mappersmith
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mappersmith=t():e.mappersmith=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,t),s.l=!0,s.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=10)}([function(module,exports,__webpack_require__){"use strict";function toQueryString(e){return isPlainObject(e)?validKeys(e).map(function(t){return buildRecursive(t,e[t])}).join("&").replace(R20,"+"):e}function performanceNow(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()}function parseResponseHeaders(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n<r.length;n++){var s=r[n],o=s.indexOf(": ");if(o>0){var i=s.substring(0,o).toLowerCase(),a=s.substring(o+2).trim();t[i]=a}}return t}function lowerCaseObjectKeys(e){return Object.keys(e).reduce(function(t,r){return t[r.toLowerCase()]=e[r],t},{})}function isPlainObject(e){return"[object Object]"===toString.call(e)&&Object.getPrototypeOf(e)===Object.getPrototypeOf({})}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)};exports.toQueryString=toQueryString,exports.performanceNow=performanceNow,exports.parseResponseHeaders=parseResponseHeaders,exports.lowerCaseObjectKeys=lowerCaseObjectKeys,exports.isPlainObject=isPlainObject,"undefined"!=typeof window&&null!==window&&(window.performance||(window.performance={}),performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process=void 0,getNanoSeconds=void 0,loadTime=void 0;try{_process=eval("process")}catch(e){}var hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime};hasProcessHrtime()&&(getNanoSeconds=function(){var e=_process.hrtime();return 1e9*e[0]+e[1]},loadTime=getNanoSeconds());var R20=/%20/g,validKeys=function(e){return Object.keys(e).filter(function(t){return void 0!==e[t]&&null!==e[t]})},buildRecursive=function e(t,r,n){n=n||"";var s=Array.isArray(r),o="object"===("undefined"==typeof r?"undefined":_typeof(r));return s||o?s?r.map(function(r){return e(t,r,n+"[]")}).join("&"):validKeys(r).map(function(s){return e(t,r[s],n+"["+s+"]")}).join("&"):encodeURIComponent(t+n)+"="+encodeURIComponent(r)},hasOwnProperty=Object.prototype.hasOwnProperty,assign=exports.assign=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},toString=Object.prototype.toString},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){return new i.default(e,a.gateway).build()}Object.defineProperty(t,"__esModule",{value:!0}),t.configs=void 0,t.default=s;var o=r(6),i=n(o),a=t.configs={Promise:"function"==typeof Promise?Promise:null,gateway:null,gatewayConfigs:{emulateHTTP:!1,XHR:{withCredentials:!1,configure:null}}}},function(e,t,r){"use strict";function n(e){this.host=e.host,this.path=e.path,this.method=e.method||"get",this.headers=e.headers,this.params=e.params,this.bodyAttr=e.bodyAttr||"body",this.headersAttr=e.headersAttr||"headers"}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";function n(e,t,r,n){this.originalRequest=e,this.responseStatus=t,this.responseData=r,this.responseHeaders=n||{},this.timeElapsed=null}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0);n.prototype={request:function(){return this.originalRequest},status:function(){return 1223===this.responseStatus?204:this.responseStatus},success:function(){var e=this.status();return e>=200&&e<400},headers:function(){return(0,s.lowerCaseObjectKeys)(this.responseHeaders)},rawData:function(){return this.responseData},data:function e(){var e=this.responseData;if(this.isContentTypeJSON())try{e=JSON.parse(this.responseData)}catch(e){}return e},isContentTypeJSON:function(){return/application\/json/.test(this.headers()["content-type"])},enhance:function(e){return new n(this.request(),e.status||this.status(),e.rawData||this.rawData(),(0,s.assign)({},this.headers(),e.headers))}},t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){i.default.apply(this,arguments)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(7),i=n(o),a=r(3),u=n(a),c=r(0);s.prototype=i.default.extends({get:function(){var e=new XMLHttpRequest;this.configureCallbacks(e),e.open("get",this.request.url(),!0),this.setHeaders(e,{}),e.send()},post:function(){this.performRequest("post")},put:function(){this.performRequest("put")},patch:function(){this.performRequest("patch")},delete:function(){this.performRequest("delete")},configureCallbacks:function(e){var t=this;e.addEventListener("load",function(){t.dispatchResponse(t.createResponse(e))}),e.addEventListener("error",function(){t.dispatchClientError("Network error")});var r=this.options().XHR;r.withCredentials&&(e.withCredentials=!0),r.configure&&r.configure(e)},performRequest:function(e){var t=this.shouldEmulateHTTP()?"post":e,r=new XMLHttpRequest;this.configureCallbacks(r),r.open(t,this.request.url(),!0);var n={},s=this.prepareBody(e,n);this.setHeaders(r,n);var o=[];s&&o.push(s),r.send.apply(r,o)},createResponse:function(e){var t=e.status,r=e.responseText,n=(0,c.parseResponseHeaders)(e.getAllResponseHeaders());return new u.default(this.request,t,r,n)},setHeaders:function(e,t){var r=(0,c.assign)(t,this.request.headers());Object.keys(r).forEach(function(t){e.setRequestHeader(t,r[t])})}}),t.default=s},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!e)throw new Error("[Mappersmith] invalid manifest ("+e+")");if(!t)throw new Error("[Mappersmith] gateway class not configured (configs.gateway)");this.manifest=new a.default(e),this.GatewayClass=t}Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),a=n(i),u=r(2),c=(n(u),r(9)),f=n(c),p=r(0);o.prototype={build:function(){var e=this,t={_manifest:this.manifest};return this.manifest.eachResource(function(r,n){t[r]=e.buildResource(n)}),t},buildResource:function(e){var t=this;return e.reduce(function(e,r){return(0,p.assign)(e,s({},r.name,function(e){var n=new f.default(r.descriptor,e);return t.invokeMiddlewares(n)}))},{})},invokeMiddlewares:function(e){var t=this,r=this.manifest.createMiddlewares(),n=r.reduce(function(e,t){return t.request(e)},e),s=function(){return new t.GatewayClass(n).call()},o=r.reduce(function(e,t){return function(){return t.response(e)}},s);return o()}},t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.request=e,this.successCallback=function(){},this.failCallback=function(){}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(0),i=r(1),a=r(3),u=n(a);s.extends=function(e){return(0,o.assign)({},s.prototype,e)},s.prototype={options:function(){return i.configs.gatewayConfigs},shouldEmulateHTTP:function(){return this.options().emulateHTTP&&/^(delete|put|patch)/i.test(this.request.method())},call:function(){var e=this,t=arguments,r=(0,o.performanceNow)();return new i.configs.Promise(function(n,s){e.successCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,n(e)},e.failCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,s(e)};try{e[e.request.method()].apply(e,t)}catch(t){e.dispatchClientError(t.message)}})},dispatchResponse:function(e){e.success()?this.successCallback(e):this.failCallback(e)},dispatchClientError:function(e){this.failCallback(new u.default(this.request,400,e))},prepareBody:function(e,t){var r=this.request.body();this.shouldEmulateHTTP()&&(r=r||{},(0,o.isPlainObject)(r)&&(r._method=e),t["x-http-method-override"]=e);var n=(0,o.toQueryString)(r);return n&&(0,o.isPlainObject)(r)&&(t["content-type"]="application/x-www-form-urlencoded;charset=utf-8"),n}},t.default=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.host=e.host,this.resources=e.resources||{},this.middlewares=e.middlewares||[]}Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),i=n(o),a=r(0);s.prototype={eachResource:function(e){var t=this;Object.keys(this.resources).forEach(function(r){var n=t.eachMethod(r,function(e){return{name:e,descriptor:t.createMethodDescriptor(r,e)}});e(r,n)})},eachMethod:function(e,t){return Object.keys(this.resources[e]).map(function(e){return t(e)})},createMethodDescriptor:function(e,t){var r=this.resources[e][t];if(!r||!r.path)throw new Error('[Mappersmith] path is undefined for resource "'+e+'" method "'+t+'"');return new i.default((0,a.assign)({host:this.host},r))},createMiddlewares:function(){var e=function(e){return(0,a.assign)({request:function(e){return e},response:function(e){return e()}},e())};return this.middlewares.map(function(t){return e(t)})}},t.default=s},function(e,t,r){"use strict";function n(e,t){this.methodDescriptor=e,this.requestParams=t||{}}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0),o=new RegExp("{([^}]+)}");n.prototype={params:function e(){var t=this,e=(0,s.assign)({},this.methodDescriptor.params,this.requestParams),r=function(e){return e!==t.methodDescriptor.headersAttr&&e!==t.methodDescriptor.bodyAttr};return Object.keys(e).reduce(function(t,n){return r(n)&&(t[n]=e[n]),t},{})},method:function(){return this.methodDescriptor.method.toLowerCase()},host:function(){return(this.methodDescriptor.host||"").replace(/\/$/,"")},path:function e(){var e=this.methodDescriptor.path,t=this.methodDescriptor;t.headersAttr,t.bodyAttr;"/"!==this.methodDescriptor.path[0]&&(e="/"+this.methodDescriptor.path);var r=this.params();Object.keys(r).forEach(function(t){var n=r[t],s="{"+t+"}";new RegExp(s).test(e)&&(e=e.replace("{"+t+"}",n),delete r[t])});var n=e.match(o);if(n)throw new Error("[Mappersmith] required parameter missing ("+n[1]+'), "'+e+'" cannot be resolved');var i=(0,s.toQueryString)(r);return 0!==i.length&&(e+="?"+i),e},url:function(){return""+this.host()+this.path()},headers:function(){return(0,s.lowerCaseObjectKeys)((0,s.assign)({},this.methodDescriptor.headers,this.requestParams[this.methodDescriptor.headersAttr]))},body:function(){return this.requestParams[this.methodDescriptor.bodyAttr]},enhance:function(e){var t=this.methodDescriptor.headersAttr,r=this.methodDescriptor.bodyAttr,o=(0,s.assign)({},this.requestParams,e.params);return o[t]=(0,s.assign)({},this.requestParams[t],e.headers),o[r]=e.body,new n(this.methodDescriptor,o)}},t.default=n},function(module,exports,__webpack_require__){"use strict";var lib=__webpack_require__(1),_process,defaultGateway;try{_process=eval("process")}catch(e){}"undefined"!=typeof XMLHttpRequest?defaultGateway=__webpack_require__(4).default:"undefined"!=typeof _process&&(defaultGateway=__webpack_require__(5).default),lib.configs.gateway=defaultGateway,module.exports=lib}])});
//# sourceMappingURL=mappersmith.map<|endoftext|>