<commit_before>/**
 * Created by andreas on 04.05.14.
 */

import navcompute from '../nav/navcompute.js';
import {extendCoordinate} from "ol/extent";

/**
 *
 * @param {number} coordinate
 * @param axis
 * @returns {string}
 */
const formatLonLatsDecimal=function(coordinate,axis){
    coordinate = (coordinate+540)%360 - 180; // normalize for sphere being round

    let abscoordinate = Math.abs(coordinate);
    let coordinatedegrees = Math.floor(abscoordinate);

    let coordinateminutes = (abscoordinate - coordinatedegrees)/(1/60);
    let numdecimal=2;
    //correctly handle the toFixed(x) - will do math rounding
    if (coordinateminutes.toFixed(numdecimal) == 60){
        coordinatedegrees+=1;
        coordinateminutes=0;
    }
    if( coordinatedegrees < 10 ) {
        coordinatedegrees = "0" + coordinatedegrees;
    }
    if (coordinatedegrees < 100 && axis == 'lon'){
        coordinatedegrees = "0" + coordinatedegrees;
    }
    let str = coordinatedegrees + "\u00B0";

    if( coordinateminutes < 10 ) {
        str +="0";
    }
    str += coordinateminutes.toFixed(numdecimal) + "'";
    if (axis == "lon") {
        str += coordinate < 0 ? "W" :"E";
    } else {
        str += coordinate < 0 ? "S" :"N";
    }
    return str;
};

/**
 *
 * @param {Point} lonlat
 * @returns {string}
 */
const formatLonLats=function(lonlat){
    if (! lonlat || isNaN(lonlat.lat) || isNaN(lonlat.lon)){
        return "-----";
    }
    let ns=this.formatLonLatsDecimal(lonlat.lat, 'lat');
    let ew=this.formatLonLatsDecimal(lonlat.lon, 'lon');
    return ns + ', ' + ew;
};
formatLonLats.parameters=[];

/**
 * format a number with a fixed number of fractions
 * @param number
 * @param fix
 * @param fract
 * @param addSpace if set - add a space for positive numbers
 * @returns {string}
 */

const formatDecimal=function(number,fix,fract,addSpace){
    let sign="";
    number=parseFloat(number);
    if (isNaN(number)){
        rt="";
        while (fix > 0) {
            rt+="-";
            fix--;
        }
        return rt;
    }
    if (addSpace !== undefined && addSpace) sign=" ";
    if (number < 0) {
        number=-number;
        sign="-";
    }
    let rt=number.toFixed(fract);
    let v=10;
    fix-=1;
    while (fix > 0){
        if (number < v){
            rt=" "+rt;
        }
        v=v*10;
        fix-=1;
    }
    return sign+rt;
};
formatDecimal.parameters=[
    {name:'fix',type:'NUMBER'},
    {name: 'fract',type:'NUMBER'},
    {name: 'addSpace',type:'BOOLEAN'}
];
const formatDecimalOpt=function(number,fix,fract,addSpace){
    number=parseFloat(number);
    if (isNaN(number)) return formatDecimal(number,fix,fract,addSpace);
    if (Math.floor(number) == number){
        return formatDecimal(number,fix,0,addSpace);
    }
    return formatDecimal(number,fix,fract,addSpace);
};

formatDecimalOpt.parameters=[
    {name:'fix',type:'NUMBER'},
    {name: 'fract',type:'NUMBER'},
    {name: 'addSpace',type:'BOOLEAN'}
];

/**
 * format a distance
 * show 99.9 for values < 100, show 999 for values >= 100, max 5
 * @param distance in m
 * @param unit: one of nm,m,km
 */
const formatDistance=function(distance,opt_unit){
    let number=parseFloat(distance);
    if (isNaN(number)) return "    -"; //4 spaces
    let factor=navcompute.NM;
    if (opt_unit == 'm') factor=1;
    if (opt_unit == 'km') factor=1000;
    number=number/factor;
    if (number < 1){
        return formatDecimal(number,3,2);
    }
    if (number < 100){
        return formatDecimal(number,4,1);
    }
    return formatDecimal(number,5,0);
};
formatDistance.parameters=[
    {name:'unit',type:'SELECT',list:['nm','m','km'],default:'nm'}
];

/**
 *
 * @param speed in m/s
 * @param opt_unit one of kn,ms,kmh
 * @returns {*}
 */

const formatSpeed=function(speed,opt_unit){
    let number=parseFloat(speed);
    if (isNaN(number)) return "  -"; //2 spaces
    let factor=3600/navcompute.NM;
    if (opt_unit == 'ms') factor=1;
    if (opt_unit == 'kmh') factor=3.6;
    number=number*factor;
    if (number < 100){
        return formatDecimal(number,2,1);
    }
    return formatDecimal(number,3,0);
};

formatSpeed.parameters=[
    {name:'unit',type:'SELECT',list:['kn','ms','kmh'],default:'kn'}
];

const formatDirection=function(dir,opt_rad){
    if (opt_rad){
        dir=180*dir/Math.PI;
    }
    return formatDecimal(dir,3,0);
};
formatDirection.parameters=[
    {name:'inputRadian',type:'BOOLEAN',default:false}
];

/**
 *
 * @param {Date} curDate
 * @returns {string}
 */
const formatTime=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "--:--:--";
    let datestr=this.formatDecimal(curDate.getHours(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getMinutes(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getSeconds(),2,0).replace(" ","0");
    return datestr;
};
formatTime.parameters=[]
/**
 *
 * @param {Date} curDate
 * @returns {string} hh:mm
 */
const formatClock=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "--:--";
    let datestr=this.formatDecimal(curDate.getHours(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getMinutes(),2,0).replace(" ","0");
    return datestr;
};
formatClock.parameters=[]
/**
 * format date and time
 * @param {Date} curDate
 * @returns {string}
 */
const formatDateTime=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "----/--/-- --:--:--";
    let datestr=this.formatDecimal(curDate.getFullYear(),4,0)+"/"+
        this.formatDecimal(curDate.getMonth()+1,2,0)+"/"+
        this.formatDecimal(curDate.getDate(),2,0)+" "+
        this.formatDecimal(curDate.getHours(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getMinutes(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getSeconds(),2,0).replace(" ","0");
    return datestr;
};
formatDateTime.parameters=[];

const formatDate=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "----/--/--";
    let datestr=this.formatDecimal(curDate.getFullYear(),4,0)+"/"+
        this.formatDecimal(curDate.getMonth()+1,2,0)+"/"+
        this.formatDecimal(curDate.getDate(),2,0);
    return datestr;
};
formatDate.parameters=[];

const formatString=function(data){
    return data;
};
formatString.parameters=[];
const formatPressure=function(data,opt_unit){
    try {
        if (!opt_unit || opt_unit.toLowerCase() === 'pa') return formatDecimal(data);
        if (opt_unit.toLowerCase() === 'hpa') {
            return (parseFloat(data)/100).toFixed(2)
        }
        if (opt_unit.toLowerCase() === 'bar') {
            return formatDecimal(parseFloat(data)/100000,2,4);
        }
    }catch(e){
        return "-----";
    }
}
formatPressure.parameters=[
    {name:'unit',type:'SELECT',list:['pa','hpa','bar'],default:'pa'}
]

const formatTemperature=function(data,opt_unit){
    try{
        if (! opt_unit || opt_unit.toLowerCase().match(/^k/)){
            return formatDecimal(data,3,1);
        }
        if (opt_unit.toLowerCase().match(/^c/)){
            return formatDecimal(parseFloat(data)-273.15,3,1)
        }
    }catch(e){
        return "-----"
    }
}
formatTemperature.parameters=[
    {name:'unit',type:'SELECT',list:['celsius','kelvin'],default:'kelvin'}
]

export default {
    formatDateTime,
    formatClock,
    formatTime,
    formatDecimalOpt,
    formatDecimal,
    formatLonLats,
    formatLonLatsDecimal,
    formatDistance,
    formatDirection,
    formatSpeed,
    formatString,
    formatDate,
    formatPressure,
    formatTemperature
};<commit_msg>format date with leading zeros for month and day, add option to formatDecimal<commit_after>/**
 * Created by andreas on 04.05.14.
 */

import navcompute from '../nav/navcompute.js';
import {extendCoordinate} from "ol/extent";

/**
 *
 * @param {number} coordinate
 * @param axis
 * @returns {string}
 */
const formatLonLatsDecimal=function(coordinate,axis){
    coordinate = (coordinate+540)%360 - 180; // normalize for sphere being round

    let abscoordinate = Math.abs(coordinate);
    let coordinatedegrees = Math.floor(abscoordinate);

    let coordinateminutes = (abscoordinate - coordinatedegrees)/(1/60);
    let numdecimal=2;
    //correctly handle the toFixed(x) - will do math rounding
    if (coordinateminutes.toFixed(numdecimal) == 60){
        coordinatedegrees+=1;
        coordinateminutes=0;
    }
    if( coordinatedegrees < 10 ) {
        coordinatedegrees = "0" + coordinatedegrees;
    }
    if (coordinatedegrees < 100 && axis == 'lon'){
        coordinatedegrees = "0" + coordinatedegrees;
    }
    let str = coordinatedegrees + "\u00B0";

    if( coordinateminutes < 10 ) {
        str +="0";
    }
    str += coordinateminutes.toFixed(numdecimal) + "'";
    if (axis == "lon") {
        str += coordinate < 0 ? "W" :"E";
    } else {
        str += coordinate < 0 ? "S" :"N";
    }
    return str;
};

/**
 *
 * @param {Point} lonlat
 * @returns {string}
 */
const formatLonLats=function(lonlat){
    if (! lonlat || isNaN(lonlat.lat) || isNaN(lonlat.lon)){
        return "-----";
    }
    let ns=this.formatLonLatsDecimal(lonlat.lat, 'lat');
    let ew=this.formatLonLatsDecimal(lonlat.lon, 'lon');
    return ns + ', ' + ew;
};
formatLonLats.parameters=[];

/**
 * format a number with a fixed number of fractions
 * @param number
 * @param fix
 * @param fract
 * @param addSpace if set - add a space for positive numbers
 * @param prefixZero if set - use 0 instead of space to fill the fixed digits
 * @returns {string}
 */

const formatDecimal=function(number,fix,fract,addSpace,prefixZero){
    let sign="";
    number=parseFloat(number);
    if (isNaN(number)){
        rt="";
        while (fix > 0) {
            rt+="-";
            fix--;
        }
        return rt;
    }
    if (addSpace !== undefined && addSpace) sign=" ";
    if (number < 0) {
        number=-number;
        sign="-";
    }
    let rt=number.toFixed(fract);
    let v=10;
    fix-=1;
    while (fix > 0){
        if (number < v){
            if (prefixZero) rt="0"+rt;
            else  rt=" "+rt;
        }
        v=v*10;
        fix-=1;
    }
    return sign+rt;
};
formatDecimal.parameters=[
    {name:'fix',type:'NUMBER'},
    {name: 'fract',type:'NUMBER'},
    {name: 'addSpace',type:'BOOLEAN'},
    {name: 'prefixZero',type:'BOOLEAN'}
];
const formatDecimalOpt=function(number,fix,fract,addSpace){
    number=parseFloat(number);
    if (isNaN(number)) return formatDecimal(number,fix,fract,addSpace);
    if (Math.floor(number) == number){
        return formatDecimal(number,fix,0,addSpace);
    }
    return formatDecimal(number,fix,fract,addSpace);
};

formatDecimalOpt.parameters=[
    {name:'fix',type:'NUMBER'},
    {name: 'fract',type:'NUMBER'},
    {name: 'addSpace',type:'BOOLEAN'}
];

/**
 * format a distance
 * show 99.9 for values < 100, show 999 for values >= 100, max 5
 * @param distance in m
 * @param unit: one of nm,m,km
 */
const formatDistance=function(distance,opt_unit){
    let number=parseFloat(distance);
    if (isNaN(number)) return "    -"; //4 spaces
    let factor=navcompute.NM;
    if (opt_unit == 'm') factor=1;
    if (opt_unit == 'km') factor=1000;
    number=number/factor;
    if (number < 1){
        return formatDecimal(number,3,2);
    }
    if (number < 100){
        return formatDecimal(number,4,1);
    }
    return formatDecimal(number,5,0);
};
formatDistance.parameters=[
    {name:'unit',type:'SELECT',list:['nm','m','km'],default:'nm'}
];

/**
 *
 * @param speed in m/s
 * @param opt_unit one of kn,ms,kmh
 * @returns {*}
 */

const formatSpeed=function(speed,opt_unit){
    let number=parseFloat(speed);
    if (isNaN(number)) return "  -"; //2 spaces
    let factor=3600/navcompute.NM;
    if (opt_unit == 'ms') factor=1;
    if (opt_unit == 'kmh') factor=3.6;
    number=number*factor;
    if (number < 100){
        return formatDecimal(number,2,1);
    }
    return formatDecimal(number,3,0);
};

formatSpeed.parameters=[
    {name:'unit',type:'SELECT',list:['kn','ms','kmh'],default:'kn'}
];

const formatDirection=function(dir,opt_rad){
    if (opt_rad){
        dir=180*dir/Math.PI;
    }
    return formatDecimal(dir,3,0);
};
formatDirection.parameters=[
    {name:'inputRadian',type:'BOOLEAN',default:false}
];

/**
 *
 * @param {Date} curDate
 * @returns {string}
 */
const formatTime=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "--:--:--";
    let datestr=this.formatDecimal(curDate.getHours(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getMinutes(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getSeconds(),2,0).replace(" ","0");
    return datestr;
};
formatTime.parameters=[]
/**
 *
 * @param {Date} curDate
 * @returns {string} hh:mm
 */
const formatClock=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "--:--";
    let datestr=this.formatDecimal(curDate.getHours(),2,0).replace(" ","0")+":"+
        this.formatDecimal(curDate.getMinutes(),2,0).replace(" ","0");
    return datestr;
};
formatClock.parameters=[]
/**
 * format date and time
 * @param {Date} curDate
 * @returns {string}
 */
const formatDateTime=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "----/--/-- --:--:--";
    let datestr=this.formatDecimal(curDate.getFullYear(),4,0)+"/"+
        this.formatDecimal(curDate.getMonth()+1,2,0,false,true)+"/"+
        this.formatDecimal(curDate.getDate(),2,0,false,true)+" "+
        this.formatDecimal(curDate.getHours(),2,0,false,true)+":"+
        this.formatDecimal(curDate.getMinutes(),2,0,false,true)+":"+
        this.formatDecimal(curDate.getSeconds(),2,0,false,true);
    return datestr;
};
formatDateTime.parameters=[];

const formatDate=function(curDate){
    if (! curDate || ! (curDate instanceof Date)) return "----/--/--";
    let datestr=this.formatDecimal(curDate.getFullYear(),4,0)+"/"+
        this.formatDecimal(curDate.getMonth()+1,2,0)+"/"+
        this.formatDecimal(curDate.getDate(),2,0);
    return datestr;
};
formatDate.parameters=[];

const formatString=function(data){
    return data;
};
formatString.parameters=[];
const formatPressure=function(data,opt_unit){
    try {
        if (!opt_unit || opt_unit.toLowerCase() === 'pa') return formatDecimal(data);
        if (opt_unit.toLowerCase() === 'hpa') {
            return (parseFloat(data)/100).toFixed(2)
        }
        if (opt_unit.toLowerCase() === 'bar') {
            return formatDecimal(parseFloat(data)/100000,2,4);
        }
    }catch(e){
        return "-----";
    }
}
formatPressure.parameters=[
    {name:'unit',type:'SELECT',list:['pa','hpa','bar'],default:'pa'}
]

const formatTemperature=function(data,opt_unit){
    try{
        if (! opt_unit || opt_unit.toLowerCase().match(/^k/)){
            return formatDecimal(data,3,1);
        }
        if (opt_unit.toLowerCase().match(/^c/)){
            return formatDecimal(parseFloat(data)-273.15,3,1)
        }
    }catch(e){
        return "-----"
    }
}
formatTemperature.parameters=[
    {name:'unit',type:'SELECT',list:['celsius','kelvin'],default:'kelvin'}
]

export default {
    formatDateTime,
    formatClock,
    formatTime,
    formatDecimalOpt,
    formatDecimal,
    formatLonLats,
    formatLonLatsDecimal,
    formatDistance,
    formatDirection,
    formatSpeed,
    formatString,
    formatDate,
    formatPressure,
    formatTemperature
};<|endoftext|>


<commit_before>Array.prototype.find||(Array.prototype.find=function(n){var t;if(this===null)throw new TypeError("Array.prototype.find called on null or undefined");if(typeof n!="function")throw new TypeError("predicate must be a function");var i=Object(this),u=i.length>>>0,f=arguments[1],r;for(t=0;t<u;t++)if(r=i[t],n.call(f,r,t,i))return r;return undefined});"angular"in window&&function(){"use strict";angular.module("xsockets",[]);angular.module("xsockets").provider("xsocketsController",[function(){var n=this,i=JSON.parse(localStorage.getItem("ci")?localStorage.getItem("ci"):"{}"),r=function(n){var t="?";return delete n.C,Object.keys(n).forEach(function(i){t+=i+"="+encodeURIComponent(n[i])+"&"}),t=t.slice(0,t.length-1)},t=function(t,i){var u=n.listeners.filter(function(n){return n.controller===t.C&&n.topic===t.T}),r;u.forEach(function(n){n.fn.fire(JSON.parse(t.D),i,t.C)});n.promises.hasOwnProperty(t.T)&&(r=JSON.parse(t.D),n.promises[t.T].resolve({key:r.K,value:r.V}))},u=function(n,t){var i=n,e=function(n){return String.fromCharCode.apply(null,new Uint16Array(n))},u=function(n){for(var t=0,i=n.byteLength-1;i>=0;i--)t=t*256+n[i];return parseInt(t)},r=new Uint8Array(i,0,8),o=u(r),f=parseInt(8+u(r));t(e(new Uint8Array(i,8,o)),new Uint8Array(i,parseInt(f),i.byteLength-f),r)};this.promises={};this.onconnected=function(){this.isConnected=!0};this.ondisconnected=function(){n.reconnect()};this.connectionAttempts=0;this.controllers=[];this.listeners=[];this.queue=[];this.connection=undefined;this.isConnected=!1;this.isReconnecting=!1;this.reconnect=function(){(this.connectionAttempts++,this.isReconnecting)||(this.isReconnecting=!0,this.open())};this.url="";this.open=function(f,e,o){arguments.length>0&&(this.url=o?f:f+r(angular.extend({},i,e)));this.connection=new window.WebSocket(this.url);this.connection.binaryType="arraybuffer";this.connection.onclose=function(t){n.isReconnecting=!1;n.isConnected=!1;n.ondisconnected&&n.ondisconnected.apply(t)};this.connection.onopen=function(t){n.connectionAttempts=0;n.isReconnecting=!1;n.queue.forEach(function(t){n.send(t)});n.queue.length=0;n.onconnected&&n.onconnected.apply(t)};this.connection.onmessage=function(n){n.data instanceof ArrayBuffer?u(n.data,function(n,i,r){var u=JSON.parse(n);t(u,new Uint8Array(i),r)}):t(JSON.parse(n.data))}};this.sendBinary=function(n){this.connection.send(n)};this.send=function(n){this.connection.readyState===1?this.connection.send(n.toString()):this.queue.push(n)};this.setState=function(n,t){var i=this.controllers.find(function(t){return t.controller===n});i&&(i.readyState=t)};this.controllerIsOpen=function(t){return this.controllers.find(function(n){return n.controller===t})?!0:(n.controllers.push({controller:t,readyState:0}),!1)};this.uuid=function(n,t){for(t=n="";n++<36;t+=n*51&52?(n^15?8^Math.random()*(n^20?16:4):4).toString(16):"-");return t};this.listener=function(n,t,i,r){this.instance=n;this.topic=t;this.controller=i;this.fn=r};this.$get=["$q","$rootScope",function(t,i){return function(r,u){var e={init:"1",ping:"7",pong:"8",controller:{onError:"4",onOpen:"2",onClose:"3"},storage:{set:"s1",get:"s2",clear:"s4",remove:"s3"},pubSub:{subscribe:"5",unsubscribe:"6"}},y=function(n){var t=function(n){this.fn=n};return t.prototype.fire=function(t,i){n.$apply(this.fn.apply(this,[t,i]))},t}(i),s=n.uuid(),l=function(t,i,r){return n.listeners.filter(function(n){return n.topic===i&&n.controller===r&&n.instance===t})},a=function(t,i){var r=n.listeners.indexOf(l(s,t,i));n.listeners.splice(r,1)},c=function(t,i,u,f){var e=new n.listener(t,i,u,new y(f)),o=l(s,i,r),h;o.length===0?n.listeners.push(e):(h=n.listeners.indexOf(o[0]),n.listeners[h]=e)},p=function(t,i){for(var r=0;r<n.listeners.length;r++)n.listeners[r].controller===i&&n.listeners[r].instance===t&&n.listeners.splice(r,1)},w=function(n){for(var r,t=[0,0,0,0,0,0,0,0],i=0;i<t.length;i++)r=n&255,t[i]=r,n=(n-r)/256;return t},f=function(){var n=function(n,t,i){this.T=n?n.toLowerCase():undefined;this.D=t;this.C=i?i.toLowerCase():undefined;this.JSON={T:n,D:JSON.stringify(t),C:i}};return n.prototype.toString=function(){return JSON.stringify(this.JSON)},n}(),b=function(){var n=function(n,t,i){this.buffer=this.createBuffer(new f(t,i,r).toString(),n)};return n.prototype.stringToBuffer=function(n){for(var i=n.length,r=new Array(i),t=0;t<i;t++)r[t]=n.charCodeAt(t)&255;return new Uint8Array(r).buffer},n.prototype.appendBuffer=function(n,t){var i=new Uint8Array(n.byteLength+t.byteLength);return i.set(new Uint8Array(n),0),i.set(new Uint8Array(t),n.byteLength),i.buffer},n.prototype.createBuffer=function(n,t){var i=new Uint8Array(w(n.length));return this.appendBuffer(this.appendBuffer(i,this.stringToBuffer(n)),t)},n}(),k=function(n){var i=t.defer(),r=new FileReader;return r.onload=function(){return function(n){i.resolve(n.target.result)}}(n),r.readAsArrayBuffer(n),i.promise},o=function(t){n.send(t)},v=function(n,t){var i,u="set_"+n.toLowerCase();i=t instanceof Array?{value:t}:t instanceof Object?t:{value:t};o(new f(u,i,r))},d=function(n,t){var i="set_"+n.toLowerCase();o(new f(i,t,r))},g=function(t){n.controllerIsOpen(t)||o(new f(e.init,{init:!0},t))},nt=function(){o(new f(e.controller.onClose,{},r))},h={controllerName:r,uuid:s,onerror:null,onopen:null,onclose:null,on:function(n,t){c(s,n,r,t)},off:function(n){a(s,n,r)},invokeBinary:function(t){n.sendBinary(t)},createBlob:function(n,t){return new Blob([n],t)},createBinaryMessage:function(n,t,i){return new b(n,t,i).buffer},invoke:function(n,t){o(new f(n,t,r))},publish:function(n,t){o(new f(n,t,r))},kill:function(){n.connection.close()},getArrayBuffer:k,connectionAttempts:n.connectionAttempts,close:nt,subscribe:function(n,t){c(s,n,r,t);o(new f(e.pubSub.subscribe,{T:n},r))},unsubscribe:function(n){a(s,n,r);o(new f(e.pubSub.unsubscribe,{T:n},r))},setEnum:d,storage:{set:function(n,t){n=n.toLowerCase();var i=new f(e.storage.set,{K:n,V:typeof t=="object"?JSON.stringify(t):t},r);return o(i),i},get:function(i){var u,s,h;return i=i.toLowerCase(),u=t.defer(),s=e.storage.get+":"+i,n.promises[s]=u,h=new f(e.storage.get,{K:i},r),o(h),u.promise},clear:function(){var n=new f(e.storage.clear,{},r);o(n)},remove:function(n){n=n.toLowerCase();var t=new f(e.storage.remove,{K:n},r);o(t)}},setProperty:v,getListeners:function(){return n.listeners.filter(function(n){return n.controller===r&&n.instance===s})},removeListeners:p};return c(s,e.controller.onOpen,r,function(n){var t={persistentId:n.PI,connectionId:n.CI};if(localStorage.setItem("ci",JSON.stringify(t)),h.onopen)h.onopen(t)}),c(s,e.controller.onClose,r,function(){h.onclose&&h.onclose()}),c(s,e.controller.onError,r,function(n){if(instance.onerror)h.onerror(n,r)}),arguments[1]instanceof Array?u.forEach(function(n){v(n.name,n.value)}):arguments.length===2&&arguments[1].$on("$destroy",function(){h.close()}),arguments.length===3&&arguments[2].$on("$destroy",function(){h.close()}),g(r),h}}]}])}();<commit_msg>forgot to minify<commit_after>Array.prototype.find||(Array.prototype.find=function(n){if(null===this)throw new TypeError("Array.prototype.find called on null or undefined")
if("function"!=typeof n)throw new TypeError("predicate must be a function")
for(var e,t=Object(this),r=t.length>>>0,o=arguments[1],i=0;r>i;i++)if(e=t[i],n.call(o,e,i,t))return e}),"angular"in window&&!function(){"use strict"
angular.module("xsockets",[]),angular.module("xsockets").provider("xsocketsController",[function(){var n=this,e=JSON.parse(localStorage.getItem("ci")?localStorage.getItem("ci"):"{}"),t=function(n){var e="?"
return delete n.C,Object.keys(n).forEach(function(t){e+=t+"="+encodeURIComponent(n[t])+"&"}),e=e.slice(0,e.length-1)},r=function(e,t){var r=n.listeners.filter(function(n){var t=n.topic
return t instanceof RegExp?n.controller===e.C&&e.T.match(t):n.controller===e.C&&t===e.T})
if(r.forEach(function(n){n.fn.fire(JSON.parse(e.D),t,e.C)}),n.promises.hasOwnProperty(e.T)){var o=JSON.parse(e.D)
n.promises[e.T].resolve({key:o.K,value:o.V})}},o=function(n,e){var t=n,r=function(n){return String.fromCharCode.apply(null,new Uint16Array(n))},o=function(n){for(var e=0,t=n.byteLength-1;t>=0;t--)e=256*e+n[t]
return parseInt(e)},i=new Uint8Array(t,0,8),s=o(i),c=parseInt(8+o(i))
e(r(new Uint8Array(t,8,s)),new Uint8Array(t,parseInt(c),t.byteLength-c),i)}
this.promises={},this.onconnected=function(){this.isConnected=!0},this.ondisconnected=function(){n.reconnect()},this.connectionAttempts=0,this.maxConnectionAttempts=5,this.controllers=[],this.listeners=[],this.queue=[],this.connection=void 0,this.isConnected=!1,this.isReconnecting=!1,this.reconnect=function(){this.connectionAttempts++,this.isReconnecting||(this.isReconnecting=!0,this.open())},this.url="",this.open=function(i,s,c){arguments.length>0&&(c?this.url=i:this.url=i+t(angular.extend({},e,s))),this.connection=new window.WebSocket(this.url,"XSocketsNET"),this.connection.binaryType="arraybuffer",this.connection.onclose=function(e){n.isReconnecting=!1,n.isConnected=!1,n.ondisconnected&&n.ondisconnected.apply(e)},this.connection.onopen=function(e){n.connectionAttempts=0,n.isReconnecting=!1,n.queue.forEach(function(e){n.send(e)}),n.queue.length=0,n.onconnected&&n.onconnected.apply(e)},this.connection.onmessage=function(n){n.data instanceof ArrayBuffer?o(n.data,function(n,e,t){var o=JSON.parse(n)
r(o,new Uint8Array(e),t)}):r(JSON.parse(n.data))}},this.sendBinary=function(n){this.connection.send(n)},this.send=function(n){1===this.connection.readyState?this.connection.send(n.toString()):this.queue.push(n)},this.setState=function(n,e){var t=this.controllers.find(function(e){return e.controller===n})
t&&(t.readyState=e)},this.controllerIsOpen=function(e){return this.controllers.find(function(n){return n.controller===e})?!0:(n.controllers.push({controller:e,readyState:0}),!1)},this.uuid=function(n,e){for(e=n="";n++<36;e+=51*n&52?(15^n?8^Math.random()*(20^n?16:4):4).toString(16):"-");return e},this.listener=function(n,e,t,r){this.instance=n,this.topic=e,this.controller=t,this.fn=r},this.$get=["$q","$rootScope",function(e,t){return function(r,o){var i={init:"1",ping:"7",pong:"8",controller:{onError:"4",onOpen:"2",onClose:"3"},storage:{set:"s1",get:"s2",clear:"s4",remove:"s3"},pubSub:{subscribe:"5",unsubscribe:"6"}},s=function(n){var e=function(n){this.fn=n}
return e.prototype.fire=function(e,t){n.$digest(this.fn.apply(this,[e,t]))},e}(t),c=n.uuid(),u=function(e,t,r){var o=n.listeners.filter(function(n){var o=n.topic===t&&n.controller===r&&n.instance===e
return o})
return o},a=function(e,t){var r=n.listeners.indexOf(u(c,e,t))
n.listeners.splice(r,1)},f=function(e,t,o,i){var a=new n.listener(e,t,o,new s(i)),f=u(c,t,r)
if(0===f.length)n.listeners.push(a)
else{var l=n.listeners.indexOf(f[0])
n.listeners[l]=a}},l=function(e,t){for(var r=0;r<n.listeners.length;r++)n.listeners[r].controller===t&&n.listeners[r].instance===e&&n.listeners.splice(r,1)},h=function(n){for(var e=[0,0,0,0,0,0,0,0],t=0;t<e.length;t++){var r=255&n
e[t]=r,n=(n-r)/256}return e},p=function(){var n=function(n,e,t){this.T=n?n.toLowerCase():void 0,this.D=e,this.C=t?t.toLowerCase():void 0,this.JSON={T:n,D:JSON.stringify(e),C:t}}
return n.prototype.toString=function(){return JSON.stringify(this.JSON)},n}(),d=function(){var n=function(n,e,t){this.buffer=this.createBuffer(new p(e,t,r).toString(),n)}
return n.prototype.stringToBuffer=function(n){var e,t=n.length,r=new Array(t)
for(e=0;t>e;e++)r[e]=255&n.charCodeAt(e)
return new Uint8Array(r).buffer},n.prototype.appendBuffer=function(n,e){var t=new Uint8Array(n.byteLength+e.byteLength)
return t.set(new Uint8Array(n),0),t.set(new Uint8Array(e),n.byteLength),t.buffer},n.prototype.createBuffer=function(n,e){var t=new Uint8Array(h(n.length)),r=this.appendBuffer(this.appendBuffer(t,this.stringToBuffer(n)),e)
return r},n}(),g=function(n){var t=e.defer(),r=new FileReader
return r.onload=function(){return function(n){t.resolve(n.target.result)}}(n),r.readAsArrayBuffer(n),t.promise},y=function(e){n.send(e)},v=function(n,e){var t,o="set_"+n.toLowerCase()
t=e instanceof Array?{value:e}:e instanceof Object?e:{value:e},y(new p(o,t,r))},w=function(n,e){var t="set_"+n.toLowerCase()
y(new p(t,e,r))},b=function(e){n.controllerIsOpen(e)||y(new p(i.init,{init:!0},e))},m=function(){y(new p(i.controller.onClose,{},r))},S={controllerName:r,uuid:c,onerror:null,onopen:null,onclose:null,on:function(n,e){f(c,n,r,e)},off:function(n){a(c,n,r)},invokeBinary:function(e){n.sendBinary(e)},createBlob:function(n,e){return new Blob([n],e)},createBinaryMessage:function(n,e,t){return new d(n,e,t).buffer},invoke:function(n,e){y(new p(n,e,r))},publish:function(n,e){y(new p(n,e,r))},kill:function(){n.connection.close()},getArrayBuffer:g,connectionAttempts:n.connectionAttempts,close:m,subscribe:function(n,e){f(c,n,r,e),y(new p(i.pubSub.subscribe,{T:n},r))},unsubscribe:function(n){a(c,n,r),y(new p(i.pubSub.unsubscribe,{T:n},r))},setEnum:w,storage:{set:function(n,e){n=n.toLowerCase()
var t=new p(i.storage.set,{K:n,V:"object"==typeof e?JSON.stringify(e):e},r)
return y(t),t},get:function(t){t=t.toLowerCase()
var o=e.defer(),s=i.storage.get+":"+t
n.promises[s]=o
var c=new p(i.storage.get,{K:t},r)
return y(c),o.promise},clear:function(){var n=new p(i.storage.clear,{},r)
y(n)},remove:function(n){n=n.toLowerCase()
var e=new p(i.storage.remove,{K:n},r)
y(e)}},setProperty:v,getListeners:function(){return n.listeners.filter(function(n){return n.controller===r&&n.instance===c})},removeListeners:l}
return f(c,i.controller.onOpen,r,function(n){var e={persistentId:n.PI,connectionId:n.CI}
localStorage.setItem("ci",JSON.stringify(e)),S.onopen&&S.onopen(e)}),f(c,i.controller.onClose,r,function(n){S.onclose&&S.onclose()}),f(c,i.controller.onError,r,function(n){S.onerror&&S.onerror(n,r)}),arguments[1]instanceof Array?o.forEach(function(n){v(n.name,n.value)}):2===arguments.length&&arguments[1].$on("$destroy",function(){S.close()}),3===arguments.length&&arguments[2].$on("$destroy",function(){S.close()}),b(r),S}}]}])}()
<|endoftext|>


<commit_before>const UrlPathValidator = require('../../../../services/validators/url-path-validator')
const getClaimSummary = require('../../../../services/data/get-claim-summary')
const claimSummaryHelper = require('../../../helpers/claim-summary-helper')
const dateHelper = require('../../../../views/helpers/date-helper')
const claimExpenseHelper = require('../../../../views/helpers/claim-expense-helper')
const ClaimSummary = require('../../../../services/domain/claim-summary')
const ValidationError = require('../../../../services/errors/validation-error')
const benefitUploadNotRequired = require('../../../helpers/benefit-upload-not-required')
const displayHelper = require('../../../../views/helpers/display-helper')
const SessionHandler = require('../../../../services/validators/session-handler')

module.exports = function (router) {
  router.get('/apply/eligibility/claim/summary', function (req, res, next) {
    UrlPathValidator(req.params)
    var isValidSession = SessionHandler.validateSession(req.session, req.url)

    if (!isValidSession) {
      return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
    }

    getClaimSummary(req.session.claimId, req.session.claimType)
      .then(function (claimDetails) {
        return res.render('apply/eligibility/claim/claim-summary',
          {
            claimType: req.session.claimType,
            referenceId: req.session.referenceId,
            claimId: req.session.claimId,
            claimDetails: claimDetails,
            dateHelper: dateHelper,
            claimExpenseHelper: claimExpenseHelper,
            displayHelper: displayHelper,
            benefitUploadNotRequired: benefitUploadNotRequired(req.session.claimType),
            URL: req.url
          })
      })
      .catch(function (error) {
        next(error)
      })
  })

  router.post('/apply/eligibility/claim/summary', function (req, res, next) {
    UrlPathValidator(req.params)
    var isValidSession = SessionHandler.validateSession(req.session, req.url)

    if (!isValidSession) {
      return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
    }

    var referenceId = req.session.referenceId
    var claimId = req.session.claimId
    var claimType = req.session.claimType

    var savedClaimDetails
    getClaimSummary(req.session.claimId, req.session.claimType)
      .then(function (claimDetails) {
        savedClaimDetails = claimDetails

        var visitConfirmation = claimDetails.claim.visitConfirmation
        var benefit = claimDetails.claim.Benefit
        var benefitDocument = claimSummaryHelper.getBenefitDocument(claimDetails.claim.benefitDocument)
        var claimExpenses = claimDetails.claimExpenses
        var isAdvanceClaim = claimDetails.claim.IsAdvanceClaim
        var benefitUpload = benefitUploadNotRequired(claimType)

        new ClaimSummary(visitConfirmation, benefit, benefitDocument, claimExpenses, isAdvanceClaim, benefitUpload) // eslint-disable-line no-new
        return res.redirect(`/apply/eligibility/claim/payment-details?isAdvance=${isAdvanceClaim}`)
      })
      .catch(function (error) {
        if (error instanceof ValidationError) {
          return res.status(400).render('apply/eligibility/claim/claim-summary', {
            errors: error.validationErrors,
            claimType: claimType,
            referenceId: referenceId,
            claimId: claimId,
            claimDetails: savedClaimDetails,
            dateHelper: dateHelper,
            claimExpenseHelper: claimExpenseHelper,
            displayHelper: displayHelper,
            benefitUploadNotRequired: benefitUploadNotRequired(claimType),
            URL: req.url
          })
        } else {
          next(error)
        }
      })
  })

  router.get('/apply/eligibility/claim/summary/view-document/:claimDocumentId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.getDocumentFilePath(req.params.claimDocumentId)
      .then(function (file) {
        return res.download(file.path, file.name)
      })
      .catch(function (error) {
        next(error)
      })
  })

  router.post('/apply/eligibility/claim/summary/remove-expense/:claimExpenseId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.removeExpenseAndDocument(req.session.claimId, req.params.claimExpenseId, req.query.claimDocumentId)
      .then(function () {
        return res.redirect(claimSummaryHelper.buildClaimSummaryUrl(req))
      })
      .catch(function (error) {
        next(error)
      })
  })

  router.post('/apply/eligibility/claim/summary/remove-document/:claimDocumentId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.removeDocument(req.params.claimDocumentId)
      .then(function () {
        return res.redirect(claimSummaryHelper.buildRemoveDocumentUrl(req))
      })
      .catch(function (error) {
        next(error)
      })
  })
}
<commit_msg>Adding error handling logic for adding documents for deleted expenses<commit_after>const UrlPathValidator = require('../../../../services/validators/url-path-validator')
const getClaimSummary = require('../../../../services/data/get-claim-summary')
const claimSummaryHelper = require('../../../helpers/claim-summary-helper')
const dateHelper = require('../../../../views/helpers/date-helper')
const claimExpenseHelper = require('../../../../views/helpers/claim-expense-helper')
const ClaimSummary = require('../../../../services/domain/claim-summary')
const ValidationError = require('../../../../services/errors/validation-error')
const benefitUploadNotRequired = require('../../../helpers/benefit-upload-not-required')
const displayHelper = require('../../../../views/helpers/display-helper')
const SessionHandler = require('../../../../services/validators/session-handler')
const ErrorHandler = require('../../../../services/validators/error-handler')
const ERROR_MESSAGES = require('../../../../services/validators/validation-error-messages')

module.exports = function (router) {
  router.get('/apply/eligibility/claim/summary', function (req, res, next) {
    UrlPathValidator(req.params)
    var isValidSession = SessionHandler.validateSession(req.session, req.url)

    if (!isValidSession) {
      return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
    }
    var savedClaimDetails
    getClaimSummary(req.session.claimId, req.session.claimType)
      .then(function (claimDetails) {
        savedClaimDetails = claimDetails

        if (req.session.ExpenseIsEnabled != null) {
          req.session.ExpenseIsEnabled = null
          var errors = ErrorHandler()
          errors.add('claim-expense', ERROR_MESSAGES.getExpenseDisabled)
          throw new ValidationError(errors.get())
        }

        return res.render('apply/eligibility/claim/claim-summary',
          {
            claimType: req.session.claimType,
            referenceId: req.session.referenceId,
            claimId: req.session.claimId,
            claimDetails: savedClaimDetails,
            dateHelper: dateHelper,
            claimExpenseHelper: claimExpenseHelper,
            displayHelper: displayHelper,
            benefitUploadNotRequired: benefitUploadNotRequired(req.session.claimType),
            URL: req.url
          })
      })
      .catch(function (error) {
        if (error instanceof ValidationError) {
          return res.status(400).render('apply/eligibility/claim/claim-summary', {
            errors: error.validationErrors,
            claimType: req.session.claimType,
            referenceId: req.session.referenceId,
            claimId: req.session.claimId,
            claimDetails: savedClaimDetails,
            dateHelper: dateHelper,
            claimExpenseHelper: claimExpenseHelper,
            displayHelper: displayHelper,
            benefitUploadNotRequired: benefitUploadNotRequired(req.session.claimType),
            URL: req.url
          })
        } else {
          next(error)
        }
      })
  })

  router.post('/apply/eligibility/claim/summary', function (req, res, next) {
    UrlPathValidator(req.params)
    var isValidSession = SessionHandler.validateSession(req.session, req.url)

    if (!isValidSession) {
      return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
    }

    var referenceId = req.session.referenceId
    var claimId = req.session.claimId
    var claimType = req.session.claimType

    var savedClaimDetails
    getClaimSummary(req.session.claimId, req.session.claimType)
      .then(function (claimDetails) {
        savedClaimDetails = claimDetails

        var visitConfirmation = claimDetails.claim.visitConfirmation
        var benefit = claimDetails.claim.Benefit
        var benefitDocument = claimSummaryHelper.getBenefitDocument(claimDetails.claim.benefitDocument)
        var claimExpenses = claimDetails.claimExpenses
        var isAdvanceClaim = claimDetails.claim.IsAdvanceClaim
        var benefitUpload = benefitUploadNotRequired(claimType)

        new ClaimSummary(visitConfirmation, benefit, benefitDocument, claimExpenses, isAdvanceClaim, benefitUpload) // eslint-disable-line no-new
        return res.redirect(`/apply/eligibility/claim/payment-details?isAdvance=${isAdvanceClaim}`)
      })
      .catch(function (error) {
        if (error instanceof ValidationError) {
          return res.status(400).render('apply/eligibility/claim/claim-summary', {
            errors: error.validationErrors,
            claimType: claimType,
            referenceId: referenceId,
            claimId: claimId,
            claimDetails: savedClaimDetails,
            dateHelper: dateHelper,
            claimExpenseHelper: claimExpenseHelper,
            displayHelper: displayHelper,
            benefitUploadNotRequired: benefitUploadNotRequired(claimType),
            URL: req.url
          })
        } else {
          next(error)
        }
      })
  })

  router.get('/apply/eligibility/claim/summary/view-document/:claimDocumentId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.getDocumentFilePath(req.params.claimDocumentId)
      .then(function (file) {
        return res.download(file.path, file.name)
      })
      .catch(function (error) {
        next(error)
      })
  })

  router.post('/apply/eligibility/claim/summary/remove-expense/:claimExpenseId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.removeExpenseAndDocument(req.session.claimId, req.params.claimExpenseId, req.query.claimDocumentId)
      .then(function () {
        return res.redirect(claimSummaryHelper.buildClaimSummaryUrl(req))
      })
      .catch(function (error) {
        next(error)
      })
  })

  router.post('/apply/eligibility/claim/summary/remove-document/:claimDocumentId', function (req, res, next) {
    UrlPathValidator(req.params)

    return claimSummaryHelper.removeDocument(req.params.claimDocumentId)
      .then(function () {
        return res.redirect(claimSummaryHelper.buildRemoveDocumentUrl(req))
      })
      .catch(function (error) {
        next(error)
      })
  })
}
<|endoftext|>


<commit_before>// Standard matcher for inspector app routes.

'use strict';

var db          = require('mano').db
  , xhrGet      = require('mano/lib/client/xhr-driver').get
  , serverSync  = require('mano/lib/client/server-sync')
  , deferred    = require('deferred')
  , baseMatcher;

baseMatcher = function (businessProcessId) {
	this.businessProcess = db.BusinessProcess.getById(businessProcessId);

	return Boolean(this.businessProcess);
};

module.exports = function (step) {
	return function (businessProcessId) {
		var resolution = baseMatcher.call(this, businessProcessId)
		  , visitedBusinessProcesses;

		if (!resolution || !this.businessProcess.dataForms.dataSnapshot.jsonString) {
			document.body.classList.add('throbber-active');
			return xhrGet('/get-business-process-data/', { id: businessProcessId })(function (result) {
				var def, interval;
				if (!result.passed) return false;
				if (baseMatcher.call(this, businessProcessId)) return true;
				def = deferred();
				serverSync.once('sync', function () {
					var baseResolution;
					if (def.promise.resolved) return;
					clearInterval(interval);
					baseResolution = baseMatcher.call(this, businessProcessId);
					if (!baseResolution) {
						console.error("Data sync issue");
						def.resolve(false);
						return;
					}
					def.resolve(baseResolution);
				}.bind(this));
				// 'sync' will be emitted only if updates go to current tab,
				// so if SSE connection is handled by other tab, we may end with infinte wait
				// to we avoid that, following check on interval is done
				interval = setInterval(function () {
					var baseResolution = baseMatcher.call(this, businessProcessId);
					if (!baseResolution) return;
					clearInterval(interval);
					def.resolve(baseResolution);
				}.bind(this), 1000);
				return def.promise;
			}.bind(this)).finally(function () { document.body.classList.remove('throbber-active'); });
		}

		visitedBusinessProcesses = this.user.recentlyVisited.businessProcesses.inspector;

		if (visitedBusinessProcesses.last !== this.businessProcess) {
			visitedBusinessProcesses.add(this.businessProcess);
		}

		return deferred(true);
	};
};
<commit_msg>Issue #1704. Use recentlyVisited to check if business process is loaded<commit_after>// Standard matcher for inspector app routes.

'use strict';

var db          = require('mano').db
  , xhrGet      = require('mano/lib/client/xhr-driver').get
  , serverSync  = require('mano/lib/client/server-sync')
  , deferred    = require('deferred')
  , baseMatcher;

baseMatcher = function (businessProcessId) {
	var visitedBusinessProcesses = this.user.recentlyVisited.businessProcesses.inspector;

	this.businessProcess = db.BusinessProcess.getById(businessProcessId);

	return Boolean(this.businessProcess && visitedBusinessProcesses.has(this.businessProcess));
};

module.exports = function (step) {
	return function (businessProcessId) {
		var resolution = baseMatcher.call(this, businessProcessId)
		  , visitedBusinessProcesses;

		if (!resolution) {
			document.body.classList.add('throbber-active');
			return xhrGet('/get-business-process-data/', { id: businessProcessId })(function (result) {
				var def, interval;
				if (!result.passed) return false;
				if (baseMatcher.call(this, businessProcessId)) return true;
				def = deferred();
				serverSync.once('sync', function () {
					var baseResolution;
					if (def.promise.resolved) return;
					clearInterval(interval);
					baseResolution = baseMatcher.call(this, businessProcessId);
					if (!baseResolution) {
						console.error("Data sync issue");
						def.resolve(false);
						return;
					}
					def.resolve(baseResolution);
				}.bind(this));
				// 'sync' will be emitted only if updates go to current tab,
				// so if SSE connection is handled by other tab, we may end with infinte wait
				// to we avoid that, following check on interval is done
				interval = setInterval(function () {
					var baseResolution = baseMatcher.call(this, businessProcessId);
					if (!baseResolution) return;
					clearInterval(interval);
					def.resolve(baseResolution);
				}.bind(this), 1000);
				return def.promise;
			}.bind(this)).finally(function () { document.body.classList.remove('throbber-active'); });
		}

		visitedBusinessProcesses = this.user.recentlyVisited.businessProcesses.inspector;

		if (visitedBusinessProcesses.last !== this.businessProcess) {
			visitedBusinessProcesses.add(this.businessProcess);
		}

		return deferred(true);
	};
};
<|endoftext|>


<commit_before>'use strict';

// Testing tools
var should = require('chai').should();
var rewire = require('rewire');

/* jshint ignore:start */
var sinon = require('sinon');
/* jshint ignore:end */

// Helper modules
var dgram = require('dgram');
var osc = require('osc-min');

// Module under test
var controller;

/* globals sinon */

describe('OSCController', function() {
    beforeEach(function() {
        try {
            controller.closeSockets();
        } catch (e) {
        }

        controller = rewire('../../controllers/osc.server.controller.js');
    });

    it('should set the outgoing port', function() {
        controller.outgoingPort.should.equal(7000);
    });

    it('should set the outgoing host', function() {
        controller.outgoingHost.should.equal('localhost');
    });

    it('should set the incoming port', function() {
        controller.incomingPort.should.equal(7001);
    });

    it('should configure an EventEmitter', function() {
        controller.eventEmitter.should.not.equal(undefined);
        controller.eventEmitter.constructor.name.should.equal('EventEmitter');
    });

    describe('#buildLogMessageFromMessage', function() {

        var originalError = console.error;
        var originalLog = console.log;
        var originalInfo = console.info;
        var errorSpy, logSpy, infoSpy;
        var buildLogMessageFromMessage;

        beforeEach(function() {
            buildLogMessageFromMessage = controller.__get__('buildLogMessageFromMessage');

            errorSpy = sinon.spy();
            logSpy = sinon.spy();
            infoSpy = sinon.spy();

            controller.__set__({
                console: {
                    error: errorSpy,
                    log: logSpy,
                    info: infoSpy
                }
            });
        });

        afterEach(function() {
            controller.__set__({
                console: {
                    error: originalError,
                    log: originalLog,
                    info: originalInfo
                }
            });
        });

        it('should only accept an array as its argument', function() {
            buildLogMessageFromMessage('not an array');

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/Malformed OSC error message received.*/);
        });

        it('should log normal messages with console.info', function() {
            buildLogMessageFromMessage([{value: 'info'}, {}]);

            infoSpy.calledOnce.should.equal(true);
            infoSpy.args[0][0].should.match(/MaxMSP: /);
        });

        it('should log error messages with console.error', function() {
            buildLogMessageFromMessage([{value: 'error'}, {value: 'hi'}]);

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/MaxMSP: /);
        });

        it('should build the log message', function() {
            buildLogMessageFromMessage([{value: 'error'}, {value: 'an error'}]);

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/MaxMSP: an error/);
        });
    });

    describe('#createOSCReceiver', function() {
        var createOSCReceiver;

        beforeEach(function() {
            createOSCReceiver = controller.__get__('createOSCReceiver');
            controller.incomingPort = 9999;
        });

        it('should bind the socket to the incoming port and the correct callback', function(done) {

            createOSCReceiver();

            var originalIncomingMessageHandler = controller.__get__('incomingMessageHandler');
            var incomingMessageHandlerSpy = sinon.spy();
            controller.__set__({
                incomingMessageHandler: incomingMessageHandlerSpy
            });

            var buf;
            buf = osc.toBuffer({
                address: '/heartbeat',
                args: [12]
            });

            var socket = dgram.createSocket('udp4');
            socket.send(buf, 0, buf.length, controller.incomingPort, 'localhost');

            setTimeout(function() {
                incomingMessageHandlerSpy.calledOnce.should.equal(true);
                controller.__set__({
                    incomingMessageHandler: originalIncomingMessageHandler
                });
                socket.close();
                done();
            }, 50);
        });
    });

    describe('#incomingMessageHandler', function() {
        it('should send log messages from Max to the log', function() {

            // Spy on buildLogMessage...
            var buildSpy = sinon.spy();
            var revert = controller.__set__({
                buildLogMessageFromMessage: buildSpy
            });

            // Create an OSC buffer
            var buf;
            buf = osc.toBuffer({
                address: '/eim/status/log',
                args: [12]
            });

            // Send buffer to message handler
            var incomingMessageHandler = controller.__get__('incomingMessageHandler');
            incomingMessageHandler(buf);

            // Check expectations
            buildSpy.calledOnce.should.equal(true);

            //noinspection JSUnresolvedVariable
            buildSpy.args[0][0][0].should.deep.equal({type: 'float', value: 12});

            // Revert controller
            revert();
        });

        it('should emit an event for other messages', function(done) {

            // Listen for the right event
            controller.eventEmitter.on('oscMessageReceived', function() {
                done();
            });

            // Create an OSC buffer
            var buf;
            buf = osc.toBuffer({
                address: '/eim/status/starting',
                args: [12]
            });

            // Send buffer to message handler
            var incomingMessageHandler = controller.__get__('incomingMessageHandler');
            incomingMessageHandler(buf);
        });
    });

    describe('#closeSockets', function() {
        it('should close the incoming and outgoing sockets', function() {
            var outgoingSpy = sinon.spy();
            var incomingSpy = sinon.spy();

            var revert = controller.__set__({
                oscSender: {
                    close: outgoingSpy
                },
                oscReceiver: {
                    close: incomingSpy
                }
            });

            controller.closeSockets();

            outgoingSpy.calledOnce.should.equal(true);
            incomingSpy.calledOnce.should.equal(true);

            revert();
        });
    });

    describe('#init', function() {
        beforeEach(function() {
            controller.incomingPort = 9999;
        });

        it('should open a new pair of sockets', function(done) {
            controller.init(function() {
                controller.__get__('oscSender').constructor.name.should.equal('Socket');
                controller.__get__('oscReceiver').constructor.name.should.equal('Socket');
                done();
            });
        });
    });

    describe('#sendJSONMessage', function() {

        var message = {
            oscType: 'message',
            address: '/address/pattern',
            args: [{
                type: 'string',
                value: 'howdy'
            }]
        };

        beforeEach(function() {
            controller.__set__({
                console: {
                    log: function() {
                    },
                    info: function() {
                    }
                }
            });
            controller.incomingPort = 9999;
        });

        it('should ensure that the socket has been initialized', function(done) {

            var spy = sinon.spy();
            controller.init = spy;

            controller.sendJSONMessage(message);

            this.timeout(50);
            setTimeout(function() {
                spy.callCount.should.equal(1);
                done();
            }, 10);
        });

        it('should format the message using osc-min', function(done) {
            var oscMock = {
                toBuffer: function() {
                    revert();
                    done();
                    return 'a string';
                }
            };

            var revert = controller.__set__({
                osc: oscMock
            });

            controller.sendJSONMessage(message);
        });

        it('should send the message via the outgoing port', function(done) {

            // Setup a simple UDP listener
            var listener = dgram.createSocket('udp4');

            listener.bind(controller.outgoingPort, function afterBindCallback() {
                listener.on('message', function onMessageCallback(msg) {
                    listener.close();
                    var receivedMessage = osc.fromBuffer(msg);
                    receivedMessage.should.eql(message);
                    done();
                });

                controller.sendJSONMessage(message);
            });
        });
    });

    describe('message sending endpoint', function() {
        beforeEach(function() {
            controller.__set__({
                console: {
                    log: function() {
                    },
                    info: function() {
                    }
                }
            });
            controller.incomingPort = 9999;
        });

        it('should call sendJSONMessage with the message from the request parameters', function() {
            var request = {
                params: {
                    message: 'Boy, howdy!'
                }
            };

            var spy = sinon.spy(controller, 'sendJSONMessage');

            controller.sendMessage(request, {json: function() {}});

            spy.callCount.should.equal(1);

            var args = spy.args[0][0];

            //noinspection JSUnresolvedVariable
            args.should.deep.equal({
                oscType: 'message',
                address: '/eim/control',
                args: {
                    type: 'string',
                    value: 'Boy, howdy!'
                }
            });
        });
    });
});<commit_msg>Ensure that server starts before osc.server.controller.test.js tests<commit_after>'use strict';

// Testing tools
var should = require('chai').should();
var rewire = require('rewire');

/* jshint ignore:start */
var sinon = require('sinon');
/* jshint ignore:end */

// Helper modules
var dgram = require('dgram');
var osc = require('osc-min');

// Server
var server = require('../../../server');
var app;

// Module under test
var controller;

/* globals sinon */

describe('OSCController', function() {
    before(function(done) {
        server.then(function(startedApp) {
            app = startedApp;
            done();
        });
    });

    beforeEach(function() {
        try {
            controller.closeSockets();
        } catch (e) {
        }

        controller = rewire('../../controllers/osc.server.controller.js');
    });

    it('should set the outgoing port', function() {
        controller.outgoingPort.should.equal(7000);
    });

    it('should set the outgoing host', function() {
        controller.outgoingHost.should.equal('localhost');
    });

    it('should set the incoming port', function() {
        controller.incomingPort.should.equal(7001);
    });

    it('should configure an EventEmitter', function() {
        controller.eventEmitter.should.not.equal(undefined);
        controller.eventEmitter.constructor.name.should.equal('EventEmitter');
    });

    describe('#buildLogMessageFromMessage', function() {

        var originalError = console.error;
        var originalLog = console.log;
        var originalInfo = console.info;
        var errorSpy, logSpy, infoSpy;
        var buildLogMessageFromMessage;

        beforeEach(function() {
            buildLogMessageFromMessage = controller.__get__('buildLogMessageFromMessage');

            errorSpy = sinon.spy();
            logSpy = sinon.spy();
            infoSpy = sinon.spy();

            controller.__set__({
                console: {
                    error: errorSpy,
                    log: logSpy,
                    info: infoSpy
                }
            });
        });

        afterEach(function() {
            controller.__set__({
                console: {
                    error: originalError,
                    log: originalLog,
                    info: originalInfo
                }
            });
        });

        it('should only accept an array as its argument', function() {
            buildLogMessageFromMessage('not an array');

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/Malformed OSC error message received.*/);
        });

        it('should log normal messages with console.info', function() {
            buildLogMessageFromMessage([{value: 'info'}, {}]);

            infoSpy.calledOnce.should.equal(true);
            infoSpy.args[0][0].should.match(/MaxMSP: /);
        });

        it('should log error messages with console.error', function() {
            buildLogMessageFromMessage([{value: 'error'}, {value: 'hi'}]);

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/MaxMSP: /);
        });

        it('should build the log message', function() {
            buildLogMessageFromMessage([{value: 'error'}, {value: 'an error'}]);

            errorSpy.calledOnce.should.equal(true);
            errorSpy.args[0][0].should.match(/MaxMSP: an error/);
        });
    });

    describe('#createOSCReceiver', function() {
        var createOSCReceiver;

        beforeEach(function() {
            createOSCReceiver = controller.__get__('createOSCReceiver');
            controller.incomingPort = 9999;
        });

        it('should bind the socket to the incoming port and the correct callback', function(done) {

            createOSCReceiver();

            var originalIncomingMessageHandler = controller.__get__('incomingMessageHandler');
            var incomingMessageHandlerSpy = sinon.spy();
            controller.__set__({
                incomingMessageHandler: incomingMessageHandlerSpy
            });

            var buf;
            buf = osc.toBuffer({
                address: '/heartbeat',
                args: [12]
            });

            var socket = dgram.createSocket('udp4');
            socket.send(buf, 0, buf.length, controller.incomingPort, 'localhost');

            setTimeout(function() {
                incomingMessageHandlerSpy.calledOnce.should.equal(true);
                controller.__set__({
                    incomingMessageHandler: originalIncomingMessageHandler
                });
                socket.close();
                done();
            }, 50);
        });
    });

    describe('#incomingMessageHandler', function() {
        it('should send log messages from Max to the log', function() {

            // Spy on buildLogMessage...
            var buildSpy = sinon.spy();
            var revert = controller.__set__({
                buildLogMessageFromMessage: buildSpy
            });

            // Create an OSC buffer
            var buf;
            buf = osc.toBuffer({
                address: '/eim/status/log',
                args: [12]
            });

            // Send buffer to message handler
            var incomingMessageHandler = controller.__get__('incomingMessageHandler');
            incomingMessageHandler(buf);

            // Check expectations
            buildSpy.calledOnce.should.equal(true);

            //noinspection JSUnresolvedVariable
            buildSpy.args[0][0][0].should.deep.equal({type: 'float', value: 12});

            // Revert controller
            revert();
        });

        it('should emit an event for other messages', function(done) {

            // Listen for the right event
            controller.eventEmitter.on('oscMessageReceived', function() {
                done();
            });

            // Create an OSC buffer
            var buf;
            buf = osc.toBuffer({
                address: '/eim/status/starting',
                args: [12]
            });

            // Send buffer to message handler
            var incomingMessageHandler = controller.__get__('incomingMessageHandler');
            incomingMessageHandler(buf);
        });
    });

    describe('#closeSockets', function() {
        it('should close the incoming and outgoing sockets', function() {
            var outgoingSpy = sinon.spy();
            var incomingSpy = sinon.spy();

            var revert = controller.__set__({
                oscSender: {
                    close: outgoingSpy
                },
                oscReceiver: {
                    close: incomingSpy
                }
            });

            controller.closeSockets();

            outgoingSpy.calledOnce.should.equal(true);
            incomingSpy.calledOnce.should.equal(true);

            revert();
        });
    });

    describe('#init', function() {
        beforeEach(function() {
            controller.incomingPort = 9999;
        });

        it('should open a new pair of sockets', function(done) {
            controller.init(function() {
                controller.__get__('oscSender').constructor.name.should.equal('Socket');
                controller.__get__('oscReceiver').constructor.name.should.equal('Socket');
                done();
            });
        });
    });

    describe('#sendJSONMessage', function() {

        var message = {
            oscType: 'message',
            address: '/address/pattern',
            args: [{
                type: 'string',
                value: 'howdy'
            }]
        };

        beforeEach(function() {
            controller.__set__({
                console: {
                    log: function() {
                    },
                    info: function() {
                    }
                }
            });
            controller.incomingPort = 9999;
        });

        it('should ensure that the socket has been initialized', function(done) {

            var spy = sinon.spy();
            controller.init = spy;

            controller.sendJSONMessage(message);

            this.timeout(50);
            setTimeout(function() {
                spy.callCount.should.equal(1);
                done();
            }, 10);
        });

        it('should format the message using osc-min', function(done) {
            var oscMock = {
                toBuffer: function() {
                    revert();
                    done();
                    return 'a string';
                }
            };

            var revert = controller.__set__({
                osc: oscMock
            });

            controller.sendJSONMessage(message);
        });

        it('should send the message via the outgoing port', function(done) {

            // Setup a simple UDP listener
            var listener = dgram.createSocket('udp4');

            listener.bind(controller.outgoingPort, function afterBindCallback() {
                listener.on('message', function onMessageCallback(msg) {
                    listener.close();
                    var receivedMessage = osc.fromBuffer(msg);
                    receivedMessage.should.eql(message);
                    done();
                });

                controller.sendJSONMessage(message);
            });
        });
    });

    describe('message sending endpoint', function() {
        beforeEach(function() {
            controller.__set__({
                console: {
                    log: function() {
                    },
                    info: function() {
                    }
                }
            });
            controller.incomingPort = 9999;
        });

        it('should call sendJSONMessage with the message from the request parameters', function() {
            var request = {
                params: {
                    message: 'Boy, howdy!'
                }
            };

            var spy = sinon.spy(controller, 'sendJSONMessage');

            controller.sendMessage(request, {json: function() {}});

            spy.callCount.should.equal(1);

            var args = spy.args[0][0];

            //noinspection JSUnresolvedVariable
            args.should.deep.equal({
                oscType: 'message',
                address: '/eim/control',
                args: {
                    type: 'string',
                    value: 'Boy, howdy!'
                }
            });
        });
    });
});<|endoftext|>


<commit_before>/**
 * BabelsbergScript is a way to describe constraints in a convenient syntax.
 * @name BabelsbergScript
 * @tutorial babelsbergscript-tutorial
 */
(function() {
    var Http = {
        request: function(method, url, callback) {
            var xhr = new (window.ActiveXObject || XMLHttpRequest)(
                        'Microsoft.XMLHTTP');
            xhr.open(method.toUpperCase(), url, true);
            if ('overrideMimeType' in xhr)
                xhr.overrideMimeType('text/plain');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    var status = xhr.status;
                    if (status === 0 || status === 200) {
                        callback.call(xhr, xhr.responseText);
                    } else {
                        throw new Error(
                            'Could not load ' + url + ' (Error ' +
                                status + ')'
                        );
                    }
                }
            };
            return xhr.send(null);
        }
    };

    /**
     * Transforms the given {@link BabelsbergScript} source code as regular JavaScript.
     * @function Babelsberg.compile
     * @public
     * @param {string} code The source code that should be transformed.
     * @return {string} A transformed version of the given source code.
     */
    Babelsberg.compile = function(code) {
        var t = new BabelsbergSrcTransform();
        return t.transform(code);
    };

    /**
     * Transforms and executes the given {@link BabelsbergScript} source code.
     * @function Babelsberg.execute
     * @public
     * @param {string} code The source code that should be executed.
     * @param {Object} scope The scope in which the given code is executed.
     */
    Babelsberg.execute = function(code, scope) {
        var params = [],
            args = [],
            func;
        code = Babelsberg.compile(code);
        var firefox = window.InstallTrigger;
        if (firefox || window.chrome) {
            var script = document.createElement('script'),
                head = document.head;
            if (firefox)
                code = '\n' + code;
            script.appendChild(document.createTextNode(
                'bbb._execute = function(' + params + ') {' + code + '\n}'
            ));
            head.appendChild(script);
            func = bbb._execute;
            delete bbb._execute;
            head.removeChild(script);
        } else {
            func = Function(params, code);
        }
        var res = func.apply(scope, args) || {};
    };

    function load() {
        function checkScript(script) {
            if (/^text\/(?:x-|)babelsbergscript$/.test(script.type) &&
                    !script.getAttribute('babelsberg-ignore')) {
                var src = script.src;
                if (src) {
                    Http.request('get', src, function(code) {
                        Babelsberg.execute(code);
                    });
                } else {
                    Babelsberg.execute(script.innerHTML);
                }
                script.setAttribute('babelsberg-ignore', true);
            }
        };

        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++)
            checkScript(scripts[i]);
    }

    if (document.readyState === 'complete') {
        setTimeout(load);
    } else {
        contentLoaded(window, load);
    }
})();
<commit_msg>add an event to listen to when all babelsbergscripts were compiled<commit_after>/**
 * BabelsbergScript is a way to describe constraints in a convenient syntax.
 * @name BabelsbergScript
 * @tutorial babelsbergscript-tutorial
 */
(function() {
    var Http = {
        request: function(method, url, callback) {
            var xhr = new (window.ActiveXObject || XMLHttpRequest)(
                        'Microsoft.XMLHTTP');
            xhr.open(method.toUpperCase(), url, true);
            if ('overrideMimeType' in xhr)
                xhr.overrideMimeType('text/plain');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    var status = xhr.status;
                    if (status === 0 || status === 200) {
                        callback.call(xhr, xhr.responseText);
                    } else {
                        throw new Error(
                            'Could not load ' + url + ' (Error ' +
                                status + ')'
                        );
                    }
                }
            };
            return xhr.send(null);
        }
    };

    /**
     * Transforms the given {@link BabelsbergScript} source code as regular JavaScript.
     * @function Babelsberg.compile
     * @public
     * @param {string} code The source code that should be transformed.
     * @return {string} A transformed version of the given source code.
     */
    Babelsberg.compile = function(code) {
        var t = new BabelsbergSrcTransform();
        return t.transform(code);
    };

    /**
     * Transforms and executes the given {@link BabelsbergScript} source code.
     * @function Babelsberg.execute
     * @public
     * @param {string} code The source code that should be executed.
     * @param {Object} scope The scope in which the given code is executed.
     */
    Babelsberg.execute = function(code, scope) {
        var params = [],
            args = [],
            func;
        code = Babelsberg.compile(code);
        var firefox = window.InstallTrigger;
        if (firefox || window.chrome) {
            var script = document.createElement('script'),
                head = document.head;
            if (firefox)
                code = '\n' + code;
            script.appendChild(document.createTextNode(
                'bbb._execute = function(' + params + ') {' + code + '\n}'
            ));
            head.appendChild(script);
            func = bbb._execute;
            delete bbb._execute;
            head.removeChild(script);
        } else {
            func = Function(params, code);
        }
        var res = func.apply(scope, args) || {};
    };

    function load() {
        var numScripts = 0,
            fired = false;

        function checkForFinish() {
            if (numScripts === 0 && !fired) {
                var event = new CustomEvent(
                    "babelsbergready",
                    {
                        detail: {
                            message: "Babelsberg Scripts loaded",
                            time: new Date(),
                        },
                        bubbles: true,
                        cancelable: true
                    }
                );
                fired = true;
                document.dispatchEvent(event);
            }
        }

        function checkScript(script) {
            if (/^text\/(?:x-|)babelsbergscript$/.test(script.type) &&
                    !script.getAttribute('babelsberg-ignore')) {
                var src = script.src;
                if (src) {
                    numScripts += 1;
                    Http.request('get', src, function(code) {
                        Babelsberg.execute(code);
                        numScripts -= 1;
                        checkForFinish();
                    });
                } else {
                    Babelsberg.execute(script.innerHTML);
                }
                script.setAttribute('babelsberg-ignore', true);
            }
        };

        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++)
            checkScript(scripts[i]);
        checkForFinish();
    }

    if (document.readyState === 'complete') {
        setTimeout(load);
    } else {
        contentLoaded(window, load);
    }
})();
<|endoftext|>


<commit_before>var dotBlockDefault = doT.template(' \

 \

 \

 \
             \
             \
                {{=it.name}} \
             \
             \
                 \
             \

 \

{{=it.description}}
 \
        {{=it.block_param_html}} \

 \

')

var dotIF = doT.template(' \

 \

 \

 \
             \
             \
                {{=it.name}} \
             \

 \
                then \
                else \

 \

 \

 \

')

function sanitizeObject(obj) {
    var newObj = {}
    for (var key of Object.keys(obj)) {
        var newVal = $('
').text(obj[key]).html()
        newObj[key] = newVal
    }
    return newObj
}

function initDrawflow() {
    editor = new Drawflow($drawflow[0]);
    editor.start();

    $('#block-tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })

    $chosenWorkflows.chosen()
        .on('change', function (evt, param) {
            // console.log(param);
        });
    $chosenBlocks.chosen()
        .on('change', function (evt, param) {
            // console.log(param);
        });

    $('.sidebar-workflow-block').each(function () {
        var $block = $(this)
        all_blocks.forEach(function (block) {
            if ($block[0].id == block['id']) {
                $block.data('block', block)
            }
        });
    })

    $('.sidebar-workflow-block').each(function() {
        if ($(this).data('block').disabled) {
            $(this).addClass('disabled')
        }
        $(this).draggable({
            helper: "clone",
            scroll: false,
            disabled: $(this).data('block').disabled,
            start: function (event, ui) {
                $(this).addClass('disabled')
            },
            stop: function (event, ui) {
                $(this).removeClass('disabled')
                // addNode($(this).data('block'), ui.position)
            }
        });
    })

    $canvas.droppable({
        drop: function (event, ui) {
            // console.log(event)
            // console.log(ui)
            addNode(ui.draggable.data('block'), ui.position)
        }
    });

}

function getTemplateForBlock(block) {
    var html = block.name
    if (block.html !== undefined) {
        html = block.html
    } else {
        if (block.html_template !== undefined) {
            html = window['dot' + block.html_template](block)
        } else {
            html = dotBlockDefault(block)
        }
    }
    return html
}

function genBlockParamHtml(block) {
    if (!block.params) {
        return ''
    }
    var html = ''
    block.params.forEach(function(param) {
        paramHtml = ''
        switch (param.type) {
            case 'input':
                paramHtml = genInput(param)[0].outerHTML
                break;
            case 'select':
                paramHtml = genSelect(param)[0].outerHTML
                break;
            default:
                break;
        }
        html += paramHtml
    })
    return html
}

function genSelect(options) {
    var $select = $('<select>').css({
        width: '100%',
    })
    options.options.forEach(function(option) {
        var optionValue = ''
        var optionName = ''
        if (typeof option === 'string') {
            optionValue = option
            optionName = option
        } else {
            optionValue = option.value
            optionName = option.name
        }
        var $option = $('<option>')
            .val(optionValue)
            .text(optionName)
        $select.append($option)
    })
    if (options.default !== undefined) {
        $select.val(options.default)
    }
    return $select
}

function genInput(options) {
    var $input = $('<input>')
    $input.attr('type', 'text')
    if (options.default !== undefined) {
        // $input.val(options.default)
        $input.attr('value', options.default) // wtf why does it not work?!
    }
    if (options.placeholder !== undefined) {
        $input.attr('placeholder', options.placeholder)
    }
    return $input
}

function addNode(block, position) {
    var canvasPosition = $canvas[0].getBoundingClientRect()
    var adjsutedPosition = {
        left: position.left - canvasPosition.left,
        top: position.top,
    }
    block['block_param_html'] = genBlockParamHtml(block)
    var html = getTemplateForBlock(block)
    editor.addNode(
        block.name,
        block.inputs === undefined ? 1 : block.inputs,
        block.outputs === undefined ? 1 : block.outputs,
        adjsutedPosition.left,
        adjsutedPosition.top,
        block.class === undefined ? '' : block.class,
        block,
        html
    );
}<commit_msg>chg: [workflow:editor] Added TODO<commit_after>var dotBlockDefault = doT.template(' \

 \

 \

 \
             \
             \
                {{=it.name}} \
             \
             \
                 \
             \

 \

{{=it.description}}
 \
        {{=it.block_param_html}} \

 \

')

var dotIF = doT.template(' \

 \

 \

 \
             \
             \
                {{=it.name}} \
             \

 \
                then \
                else \

 \

 \

 \

')

function sanitizeObject(obj) {
    var newObj = {}
    for (var key of Object.keys(obj)) {
        var newVal = $('
').text(obj[key]).html()
        newObj[key] = newVal
    }
    return newObj
}

function initDrawflow() {
    editor = new Drawflow($drawflow[0]);
    editor.start();

    $('#block-tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })

    $chosenWorkflows.chosen()
        .on('change', function (evt, param) {
            // console.log(param);
        });
    $chosenBlocks.chosen()
        .on('change', function (evt, param) {
            // console.log(param);
        });

    $('.sidebar-workflow-block').each(function () {
        var $block = $(this)
        all_blocks.forEach(function (block) {
            if ($block[0].id == block['id']) {
                $block.data('block', block)
            }
        });
    })

    $('.sidebar-workflow-block').each(function() {
        if ($(this).data('block').disabled) {
            $(this).addClass('disabled')
        }
        $(this).draggable({
            helper: "clone",
            scroll: false,
            disabled: $(this).data('block').disabled,
            start: function (event, ui) {
                $(this).addClass('disabled')
            },
            stop: function (event, ui) {
                $(this).removeClass('disabled')
                // addNode($(this).data('block'), ui.position)
            }
        });
    })

    $canvas.droppable({
        drop: function (event, ui) {
            // console.log(event)
            // console.log(ui)
            addNode(ui.draggable.data('block'), ui.position)
        }
    });

}

function getTemplateForBlock(block) {
    var html = block.name
    if (block.html !== undefined) {
        html = block.html
    } else {
        if (block.html_template !== undefined) {
            html = window['dot' + block.html_template](block)
        } else {
            html = dotBlockDefault(block)
        }
    }
    return html
}

function genBlockParamHtml(block) {
    if (!block.params) {
        return ''
    }
    var html = ''
    block.params.forEach(function(param) {
        paramHtml = ''
        switch (param.type) {
            case 'input':
                paramHtml = genInput(param)[0].outerHTML
                break;
            case 'select':
                paramHtml = genSelect(param)[0].outerHTML
                break;
            default:
                break;
        }
        html += paramHtml
    })
    return html
}

function genSelect(options) {
    var $select = $('<select>').css({
        width: '100%',
    })
    options.options.forEach(function(option) {
        var optionValue = ''
        var optionName = ''
        if (typeof option === 'string') {
            optionValue = option
            optionName = option
        } else {
            optionValue = option.value
            optionName = option.name
        }
        var $option = $('<option>')
            .val(optionValue)
            .text(optionName)
        $select.append($option)
    })
    if (options.default !== undefined) {
        $select.val(options.default)
    }
    return $select
}

function genInput(options) {
    var $input = $('<input>')
    $input.attr('type', 'text')
    if (options.default !== undefined) {
        // $input.val(options.default)
        $input.attr('value', options.default) // wtf why does it not work?!
    }
    if (options.placeholder !== undefined) {
        $input.attr('placeholder', options.placeholder)
    }
    return $input
}

function addNode(block, position) {
    var canvasPosition = $canvas[0].getBoundingClientRect()

    var adjsutedPosition = {
        left: position.left - canvasPosition.left,
        top: position.top,
    }

    // TODO: Take into account zoon level
    // pos_x = pos_x * (editor.precanvas.clientWidth / (editor.precanvas.clientWidth * editor.zoom)) - (editor.precanvas.getBoundingClientRect().x * (editor.precanvas.clientWidth / (editor.precanvas.clientWidth * editor.zoom)));
    // pos_y = pos_y * (editor.precanvas.clientHeight / (editor.precanvas.clientHeight * editor.zoom)) - (editor.precanvas.getBoundingClientRect().y * (editor.precanvas.clientHeight / (editor.precanvas.clientHeight * editor.zoom)));

    block['block_param_html'] = genBlockParamHtml(block)
    var html = getTemplateForBlock(block)
    editor.addNode(
        block.name,
        block.inputs === undefined ? 1 : block.inputs,
        block.outputs === undefined ? 1 : block.outputs,
        adjsutedPosition.left,
        adjsutedPosition.top,
        block.class === undefined ? '' : block.class,
        block,
        html
    );
}<|endoftext|>


<commit_before>/*global grunticon:true*/
(function(grunticon, window){
	"use strict";
	var document = window.document;

	// x-domain get (with cors if available)
	var ajaxGet = function( url, cb ) {
		var xhr = new window.XMLHttpRequest();
		if ( "withCredentials" in xhr ) {
			xhr.open( "GET", url, true );
		} else if ( typeof window.XDomainRequest !== "undefined" ) { //IE
			xhr = new window.XDomainRequest();
			xhr.open( "GET", url );
		}
		if( cb ){
			xhr.onload = cb;
		}
		xhr.send();
		return xhr;
	};

	var svgLoadedCORSCallback = function(callback){
		if( grunticon.method !== "svg" ){
			return;
		}
		grunticon.ready(function(){
			ajaxGet( grunticon.href, function() {
				// check to see if we've already created a style block for this href
				var existingStyle = window
					.document
					.querySelector( 'style[data-href$="'+ grunticon.href +'"]' );
				var ref = grunticon.getCSS( grunticon.href );

				if( existingStyle ){
					// NOTE this will do nothing at all if the embeds are already there
					// and the embed attribute has been removed. The only purpose for this
					// is if the markup has been "rerendered" in the page after the
					// initial embed at which point the embed attributes should exist and
					// the existing embeds should be gone
					grunticon.embedIcons( grunticon.getIcons( existingStyle ) );
				} else {
					var style = document.createElement( "style" );
					style.innerHTML = this.responseText;
					style.setAttribute("data-href", grunticon.href);
					ref.parentNode.insertBefore( style, ref );
					ref.parentNode.removeChild( ref );
					grunticon.embedIcons( grunticon.getIcons( style ) );
				}

				// only call the callback if the href gets something out of the DOM
				// TODO this functions should probably throw an exception when the href
				// is now found in the page
				if( (existingStyle || ref) && typeof callback === "function" ){
					callback();
				}
			} );
		});
	};

	grunticon.ajaxGet = ajaxGet;
	grunticon.svgLoadedCORSCallback = svgLoadedCORSCallback; //TODO: Deprecated
	grunticon.embedSVGCors = svgLoadedCORSCallback;

}(grunticon, this));
<commit_msg>move existing style block check outside ajax<commit_after>/*global grunticon:true*/
(function(grunticon, window){
	"use strict";
	var document = window.document;

	// x-domain get (with cors if available)
	var ajaxGet = function( url, cb ) {
		var xhr = new window.XMLHttpRequest();
		if ( "withCredentials" in xhr ) {
			xhr.open( "GET", url, true );
		} else if ( typeof window.XDomainRequest !== "undefined" ) { //IE
			xhr = new window.XDomainRequest();
			xhr.open( "GET", url );
		}
		if( cb ){
			xhr.onload = cb;
		}
		xhr.send();
		return xhr;
	};

	var svgLoadedCORSCallback = function(callback){
		if( grunticon.method !== "svg" ){
			return;
		}

		grunticon.ready(function(){
			var existingStyle = window
				.document
				.querySelector( 'style[data-href$="'+ grunticon.href +'"]' );

			var ref = grunticon.getCSS( grunticon.href );
			callback = callback || function(){};

			if( existingStyle ){
				// NOTE this will do nothing at all if the embeds are already there
				// and the embed attribute has been removed. The only purpose for this
				// is if the markup has been "rerendered" in the page after the
				// initial embed at which point the embed attributes should exist and
				// the existing embeds should be gone
				grunticon.embedIcons( grunticon.getIcons( existingStyle ) );
				callback();
			} else if ( ref ) {
				ajaxGet( grunticon.href, function() {
					var style = document.createElement( "style" );
					style.innerHTML = this.responseText;
					style.setAttribute("data-href", grunticon.href);
					ref.parentNode.insertBefore( style, ref );
					ref.parentNode.removeChild( ref );
					grunticon.embedIcons( grunticon.getIcons( style ) );
					callback();
				});
			}
		});
	};

	grunticon.ajaxGet = ajaxGet;
	grunticon.svgLoadedCORSCallback = svgLoadedCORSCallback; //TODO: Deprecated
	grunticon.embedSVGCors = svgLoadedCORSCallback;

}(grunticon, this));
<|endoftext|>